mirror of
https://github.com/pezkuwichain/revive.git
synced 2026-04-28 18:57:58 +00:00
Merge remote-tracking branch 'origin/main' into resolc.js
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
name: Build revive-debian
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REVIVE_DEBIAN_PACKAGE: revive-debian-x86
|
||||
DEBIAN_CONTAINER: revive-builder-debian-x86
|
||||
DEBIAN_CONTAINER_BUILDER: build-debian-builder.sh
|
||||
DEBIAN_CONTAINER_RUNNER: run-debian-builder.sh
|
||||
REVIVE_DEBIAN_INSTALL: ${{ github.workspace }}/target/release
|
||||
REVIVE_DEBIAN_BINARY: resolc
|
||||
RUST_VERSION: "1.80"
|
||||
|
||||
jobs:
|
||||
build-revive-debian-x86:
|
||||
name: debian-container-x86
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: build-container
|
||||
run: |
|
||||
(cd utils && ./${{ env.DEBIAN_CONTAINER_BUILDER}} --build-arg RUST_VERSION=${{ env.RUST_VERSION}} . )
|
||||
|
||||
- name: build-revive-debian
|
||||
run: |
|
||||
rustup show
|
||||
cargo --version
|
||||
rustup +nightly show
|
||||
cargo +nightly --version
|
||||
bash --version
|
||||
utils/${{ env.DEBIAN_CONTAINER_RUNNER }} utils/build-revive.sh -o ${{ env.REVIVE_DEBIAN_INSTALL}}
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ env.REVIVE_DEBIAN_PACKAGE }}
|
||||
path: ${{ env.REVIVE_DEBIAN_INSTALL }}/${{ env.REVIVE_DEBIAN_BINARY }}
|
||||
retention-days: 1
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: Install solc
|
||||
run: |
|
||||
mkdir -p solc
|
||||
curl -sSL --output solc/solc https://github.com/ethereum/solidity/releases/download/v0.8.26/solc-static-linux
|
||||
curl -sSL --output solc/solc https://github.com/ethereum/solidity/releases/download/v0.8.28/solc-static-linux
|
||||
chmod +x solc/solc
|
||||
echo "$(pwd)/solc/" >> $GITHUB_PATH
|
||||
|
||||
@@ -31,7 +31,10 @@ jobs:
|
||||
echo "$(pwd)/llvm18/bin" >> $GITHUB_PATH
|
||||
|
||||
- name: Install apt dependencies
|
||||
run: sudo apt update && sudo apt install -y libtinfo5
|
||||
run: |
|
||||
sudo add-apt-repository -y ppa:ethereum/ethereum
|
||||
sudo apt update
|
||||
sudo apt install -y libtinfo5 ethereum
|
||||
|
||||
- name: Format
|
||||
run: make format
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
## v0.1.0-dev.5
|
||||
|
||||
This is development pre-release.
|
||||
|
||||
# Added
|
||||
- Implement the `CODESIZE` and `EXTCODESIZE` opcodes.
|
||||
|
||||
# Changed
|
||||
- Include the full revive version in the contract metadata.
|
||||
|
||||
# Fixed
|
||||
|
||||
## v0.1.0-dev-4
|
||||
|
||||
This is development pre-release.
|
||||
|
||||
# Added
|
||||
- Support the `ORIGIN` opcode.
|
||||
|
||||
# Changed
|
||||
- Update polkavm to `v0.14.0`.
|
||||
- Enable the `a`, `fast-unaligned-access` and `xtheadcondmov` LLVM target features, decreasing the code size for some contracts.
|
||||
|
||||
# Fixed
|
||||
Generated
+9592
-412
File diff suppressed because it is too large
Load Diff
+40
-12
@@ -2,7 +2,31 @@
|
||||
resolver = "2"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0-dev.5"
|
||||
authors = [
|
||||
"Cyrill Leutwiler <cyrill@parity.io>",
|
||||
"Parity Technologies <admin@parity.io>",
|
||||
]
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2021"
|
||||
repository = "https://github.com/paritytech/revive"
|
||||
rust-version = "1.80.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
revive-benchmarks = { version = "0.1.0-dev.5", path = "crates/benchmarks" }
|
||||
revive-builtins = { version = "0.1.0-dev.5", path = "crates/builtins" }
|
||||
revive-common = { version = "0.1.0-dev.5", path = "crates/common" }
|
||||
revive-differential = { version = "0.1.0-dev.5", path = "crates/differential" }
|
||||
revive-integration = { version = "0.1.0-dev.5", path = "crates/integration" }
|
||||
revive-linker = { version = "0.1.0-dev.5", path = "crates/linker" }
|
||||
lld-sys = { version = "0.1.0-dev.5", path = "crates/lld-sys" }
|
||||
revive-llvm-context = { version = "0.1.0-dev.5", path = "crates/llvm-context" }
|
||||
revive-runtime-api = { version = "0.1.0-dev.5", path = "crates/runtime-api" }
|
||||
revive-runner = { version = "0.1.0-dev.5", path = "crates/runner" }
|
||||
revive-solidity = { version = "0.1.0-dev.5", path = "crates/solidity" }
|
||||
revive-stdlib = { version = "0.1.0-dev.5", path = "crates/stdlib" }
|
||||
|
||||
hex = "0.4"
|
||||
petgraph = "0.6"
|
||||
cc = "1.0"
|
||||
@@ -25,30 +49,34 @@ thiserror = "1.0"
|
||||
which = "5.0"
|
||||
path-slash = "0.2"
|
||||
rayon = "1.8"
|
||||
structopt = { version = "0.3", default-features = false }
|
||||
clap = { version = "4", default-features = false, features = ["derive"] }
|
||||
rand = "0.8"
|
||||
polkavm-common = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
polkavm-linker = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
polkavm-disassembler = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
polkavm = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
alloy-primitives = "0.6"
|
||||
alloy-sol-types = "0.6"
|
||||
polkavm-common = "0.14"
|
||||
polkavm-linker = "0.14"
|
||||
polkavm-disassembler = "0.14"
|
||||
polkavm = "0.14"
|
||||
alloy-primitives = { version = "0.8", features = ["serde"] }
|
||||
alloy-sol-types = "0.8"
|
||||
alloy-genesis = "0.3"
|
||||
alloy-serde = "0.3"
|
||||
env_logger = { version = "0.10.0", default-features = false }
|
||||
serde_stacker = "0.1"
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
log = { version = "0.4" }
|
||||
|
||||
# Benchmarking against EVM
|
||||
primitive-types = { version = "0.12", features = ["codec"] }
|
||||
evm-interpreter = { git = "https://github.com/xermicus/evm.git", branch = "separate-compilation" }
|
||||
# polkadot-sdk and friends
|
||||
codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
|
||||
scale-info = { version = "2.11.1", default-features = false }
|
||||
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "2b6b69641ccff4d7aa9c32051bbb2f1e775ef8cc" }
|
||||
|
||||
# llvm
|
||||
[workspace.dependencies.inkwell]
|
||||
git = "https://github.com/TheDan64/inkwell.git"
|
||||
rev = "6c0fb56b3554e939f9ca61b465043d6a84fb7b95"
|
||||
rev = "7b410298b6a93450adaa90b1841d5805a3038f12"
|
||||
default-features = false
|
||||
features = ["serde", "llvm18-0", "no-libffi-linking", "target-riscv"]
|
||||
|
||||
[profile.benchmark]
|
||||
[profile.bench]
|
||||
inherits = "release"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
|
||||
@@ -23,11 +23,20 @@ install-wasm:
|
||||
install-npm:
|
||||
npm install && npm fund
|
||||
|
||||
# install-revive: Build and install to the directory specified in REVIVE_INSTALL_DIR
|
||||
ifeq ($(origin REVIVE_INSTALL_DIR), undefined)
|
||||
REVIVE_INSTALL_DIR=`pwd`/release/revive-debian
|
||||
endif
|
||||
install-revive:
|
||||
cargo install --path crates/solidity --root $(REVIVE_INSTALL_DIR)
|
||||
|
||||
format:
|
||||
cargo fmt --all --check
|
||||
|
||||
clippy:
|
||||
cargo clippy --all-features --workspace --tests --benches -- --deny warnings --allow dead_code
|
||||
|
||||
test: format clippy test-cli test-workspace
|
||||
cargo test --workspace
|
||||
|
||||
test-integration: install-bin
|
||||
cargo test --package revive-integration
|
||||
@@ -41,28 +50,18 @@ test-workspace: install
|
||||
test-cli: install
|
||||
npm run test:cli
|
||||
|
||||
bench-prepare: install-bin
|
||||
cargo criterion --bench prepare --features bench-evm,bench-pvm --message-format=json \
|
||||
| criterion-table > crates/benchmarks/PREPARE.md
|
||||
bench-pvm: install-bin
|
||||
cargo criterion --bench execute --features bench-pvm-interpreter --message-format=json \
|
||||
| criterion-table > crates/benchmarks/PVM.md
|
||||
|
||||
bench-execute: install-bin
|
||||
cargo criterion --bench execute --features bench-evm,bench-pvm --message-format=json \
|
||||
| criterion-table > crates/benchmarks/EXECUTE.md
|
||||
|
||||
bench-extensive: install-bin
|
||||
cargo criterion --all --all-features --message-format=json \
|
||||
| criterion-table > crates/benchmarks/BENCHMARKS.md
|
||||
|
||||
bench-quick: install-bin
|
||||
cargo criterion --all --features bench-evm
|
||||
bench-evm: install-bin
|
||||
cargo criterion --bench execute --features bench-evm --message-format=json \
|
||||
| criterion-table > crates/benchmarks/EVM.md
|
||||
|
||||
bench: install-bin
|
||||
cargo criterion --all --features bench-evm,bench-pvm --message-format=json \
|
||||
cargo criterion --all --all-features --message-format=json \
|
||||
| criterion-table > crates/benchmarks/BENCHMARKS.md
|
||||
|
||||
clippy:
|
||||
cargo clippy --all-features --workspace --tests --benches
|
||||
|
||||
docs: docs-build
|
||||
mdbook serve --open docs/
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||

|
||||

|
||||
|
||||
# revive
|
||||
|
||||
@@ -50,4 +50,4 @@ Please consult the [Makefile](Makefile) targets to learn how to run tests and be
|
||||
Ensure that your branch passes `make test` locally when submitting a pull request.
|
||||
|
||||
## Design overview
|
||||
`revive` uses [solc](https://github.com/ethereum/solidity/), the Ethereum Solidity compiler, as the [Solidity frontend](crates/solidity/src/lib.rs) to process smart contracts written in Solidity. The YUL IR code (or legacy EVM assembly as a fallback for older `solc` versions) emitted by `solc` is then translated to LLVM IR, targetting a runtime similar to [Polkadots `contracts` pallet](https://docs.rs/pallet-contracts/latest/pallet_contracts/api_doc/trait.Current.html).
|
||||
`revive` uses [solc](https://github.com/ethereum/solidity/), the Ethereum Solidity compiler, as the [Solidity frontend](crates/solidity/src/lib.rs) to process smart contracts written in Solidity. The YUL IR code (or legacy EVM assembly as a fallback for older `solc` versions) emitted by `solc` is then translated to LLVM IR, targetting [Polkadots `revive` pallet](https://docs.rs/pallet-revive/latest/pallet_revive/trait.SyscallDoc.html).
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# Release checklist
|
||||
|
||||
Prior to the first stable release we neither have formal release processes nor do we follow a fixed release schedule.
|
||||
|
||||
To create a new pre-release:
|
||||
|
||||
1. Merge a release PR which updates the `-dev.X` versions in the workspace `Cargo.toml` and updates the `CHANGELOG.md` accordingly
|
||||
2. Push a release tag to `main`
|
||||
3. Manually trigger the `Build revive-debian` action
|
||||
4. Create a __pre-release__ from the tag and manually upload the build artifact generated by the action
|
||||
5. Update the [contract-docs](https://github.com/paritytech/contract-docs/) accordingly
|
||||
@@ -0,0 +1,73 @@
|
||||
# Benchmarks
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Benchmark Results](#benchmark-results)
|
||||
- [Baseline](#baseline)
|
||||
- [OddPorduct](#oddporduct)
|
||||
- [TriangleNumber](#trianglenumber)
|
||||
- [FibonacciRecursive](#fibonaccirecursive)
|
||||
- [FibonacciIterative](#fibonacciiterative)
|
||||
- [FibonacciBinet](#fibonaccibinet)
|
||||
- [SHA1](#sha1)
|
||||
|
||||
## Benchmark Results
|
||||
|
||||
### Baseline
|
||||
|
||||
| | `EVM` | `PVMInterpreter` |
|
||||
|:--------|:------------------------|:-------------------------------- |
|
||||
| **`0`** | `5.97 us` (✅ **1.00x**) | `27.04 us` (❌ *4.53x slower*) |
|
||||
|
||||
### OddPorduct
|
||||
|
||||
| | `EVM` | `PVMInterpreter` |
|
||||
|:-------------|:--------------------------|:-------------------------------- |
|
||||
| **`10000`** | `4.26 ms` (✅ **1.00x**) | `2.88 ms` (✅ **1.48x faster**) |
|
||||
| **`100000`** | `42.37 ms` (✅ **1.00x**) | `28.35 ms` (✅ **1.49x faster**) |
|
||||
| **`300000`** | `127.88 ms` (✅ **1.00x**) | `88.43 ms` (✅ **1.45x faster**) |
|
||||
|
||||
### TriangleNumber
|
||||
|
||||
| | `EVM` | `PVMInterpreter` |
|
||||
|:-------------|:--------------------------|:-------------------------------- |
|
||||
| **`10000`** | `2.85 ms` (✅ **1.00x**) | `2.37 ms` (✅ **1.20x faster**) |
|
||||
| **`100000`** | `27.85 ms` (✅ **1.00x**) | `23.01 ms` (✅ **1.21x faster**) |
|
||||
| **`360000`** | `103.01 ms` (✅ **1.00x**) | `83.66 ms` (✅ **1.23x faster**) |
|
||||
|
||||
### FibonacciRecursive
|
||||
|
||||
| | `EVM` | `PVMInterpreter` |
|
||||
|:---------|:--------------------------|:--------------------------------- |
|
||||
| **`12`** | `195.19 us` (✅ **1.00x**) | `333.53 us` (❌ *1.71x slower*) |
|
||||
| **`16`** | `1.22 ms` (✅ **1.00x**) | `1.97 ms` (❌ *1.62x slower*) |
|
||||
| **`20`** | `8.14 ms` (✅ **1.00x**) | `13.20 ms` (❌ *1.62x slower*) |
|
||||
| **`24`** | `55.09 ms` (✅ **1.00x**) | `88.56 ms` (❌ *1.61x slower*) |
|
||||
|
||||
### FibonacciIterative
|
||||
|
||||
| | `EVM` | `PVMInterpreter` |
|
||||
|:----------|:-------------------------|:--------------------------------- |
|
||||
| **`64`** | `33.39 us` (✅ **1.00x**) | `86.02 us` (❌ *2.58x slower*) |
|
||||
| **`128`** | `52.91 us` (✅ **1.00x**) | `126.38 us` (❌ *2.39x slower*) |
|
||||
| **`256`** | `82.33 us` (✅ **1.00x**) | `208.74 us` (❌ *2.54x slower*) |
|
||||
|
||||
### FibonacciBinet
|
||||
|
||||
| | `EVM` | `PVMInterpreter` |
|
||||
|:----------|:-------------------------|:--------------------------------- |
|
||||
| **`64`** | `32.29 us` (✅ **1.00x**) | `161.75 us` (❌ *5.01x slower*) |
|
||||
| **`128`** | `36.02 us` (✅ **1.00x**) | `172.59 us` (❌ *4.79x slower*) |
|
||||
| **`256`** | `41.21 us` (✅ **1.00x**) | `185.30 us` (❌ *4.50x slower*) |
|
||||
|
||||
### SHA1
|
||||
|
||||
| | `EVM` | `PVMInterpreter` |
|
||||
|:----------|:--------------------------|:--------------------------------- |
|
||||
| **`1`** | `160.17 us` (✅ **1.00x**) | `403.46 us` (❌ *2.52x slower*) |
|
||||
| **`64`** | `286.69 us` (✅ **1.00x**) | `479.79 us` (❌ *1.67x slower*) |
|
||||
| **`512`** | `1.18 ms` (✅ **1.00x**) | `1.37 ms` (❌ *1.16x slower*) |
|
||||
|
||||
---
|
||||
Made with [criterion-table](https://github.com/nu11ptr/criterion-table)
|
||||
|
||||
|
||||
@@ -1,32 +1,28 @@
|
||||
[package]
|
||||
name = "revive-benchmarks"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = [
|
||||
"Cyrill Leutwiler <cyrill@parity.io>",
|
||||
]
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
description = "revive compiler benchmarks"
|
||||
|
||||
[features]
|
||||
default = ["bench-pvm-interpreter"]
|
||||
bench-pvm-interpreter = []
|
||||
bench-pvm = []
|
||||
bench-pvm-interpreter = ["revive-runner"]
|
||||
bench-evm = ["revive-differential"]
|
||||
bench-extensive = []
|
||||
|
||||
[dependencies]
|
||||
hex = { workspace = true }
|
||||
polkavm = { workspace = true }
|
||||
revive-integration = { path = "../integration" }
|
||||
revive-differential = { path = "../differential", optional = true }
|
||||
alloy-primitives = { workspace = true }
|
||||
|
||||
revive-integration = { workspace = true }
|
||||
revive-differential = { workspace = true, optional = true }
|
||||
revive-runner = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { workspace = true }
|
||||
|
||||
[[bench]]
|
||||
name = "execute"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "prepare"
|
||||
harness = false
|
||||
|
||||
@@ -1,103 +1,42 @@
|
||||
#![cfg(any(feature = "bench-pvm-interpreter", feature = "bench-evm"))]
|
||||
|
||||
use alloy_primitives::U256;
|
||||
use criterion::{
|
||||
criterion_group, criterion_main, measurement::Measurement, BenchmarkGroup, BenchmarkId,
|
||||
Criterion,
|
||||
criterion_group, criterion_main,
|
||||
measurement::{Measurement, WallTime},
|
||||
BenchmarkGroup, BenchmarkId, Criterion,
|
||||
};
|
||||
use revive_integration::cases::Contract;
|
||||
|
||||
fn bench<P, L, I, M>(mut group: BenchmarkGroup<'_, M>, parameters: &[P], labels: &[L], contract: I)
|
||||
where
|
||||
fn bench<P, L, I>(
|
||||
mut group: BenchmarkGroup<'_, WallTime>,
|
||||
parameters: &[P],
|
||||
labels: &[L],
|
||||
contract: I,
|
||||
) where
|
||||
P: Clone,
|
||||
L: std::fmt::Display,
|
||||
I: Fn(P) -> Contract,
|
||||
M: Measurement,
|
||||
{
|
||||
assert_eq!(parameters.len(), labels.len());
|
||||
|
||||
group.sample_size(10);
|
||||
|
||||
for (p, l) in parameters.iter().zip(labels.iter()) {
|
||||
let contract = contract(p.clone());
|
||||
|
||||
#[cfg(feature = "bench-evm")]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
group.bench_with_input(BenchmarkId::new("EVM", l), p, move |b, _| {
|
||||
b.iter(|| {
|
||||
revive_differential::execute(revive_differential::prepare(
|
||||
contract.evm_runtime.clone(),
|
||||
contract.calldata.clone(),
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
group.bench_with_input(BenchmarkId::new("EVM", l), p, |b, _| {
|
||||
let code = &contract.evm_runtime;
|
||||
let input = &contract.calldata;
|
||||
b.iter_custom(|iters| revive_benchmarks::measure_evm(code, input, iters));
|
||||
});
|
||||
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
{
|
||||
#[cfg(all(feature = "bench-pvm-interpreter", not(feature = "bench-extensive")))]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let (transaction, mut instance, export) = revive_benchmarks::prepare_pvm(
|
||||
&contract.pvm_runtime,
|
||||
contract.calldata,
|
||||
polkavm::BackendKind::Interpreter,
|
||||
);
|
||||
group.bench_with_input(BenchmarkId::new("PVMInterpreter", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "bench-pvm", not(feature = "bench-extensive")))]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let (transaction, mut instance, export) = revive_benchmarks::prepare_pvm(
|
||||
&contract.pvm_runtime,
|
||||
contract.calldata,
|
||||
polkavm::BackendKind::Compiler,
|
||||
);
|
||||
group.bench_with_input(BenchmarkId::new("PVM", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
{
|
||||
use revive_benchmarks::instantiate_engine;
|
||||
use revive_integration::mock_runtime::{instantiate_module, recompile_code, State};
|
||||
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let engine = instantiate_engine(polkavm::BackendKind::Interpreter);
|
||||
let module = recompile_code(&contract.pvm_runtime, &engine);
|
||||
let transaction = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata);
|
||||
group.bench_with_input(BenchmarkId::new("PVMInterpreter", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let (mut instance, export) = instantiate_module(&module, &engine);
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm")]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let engine = instantiate_engine(polkavm::BackendKind::Compiler);
|
||||
let module = recompile_code(&contract.pvm_runtime, &engine);
|
||||
let transaction = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata);
|
||||
group.bench_with_input(BenchmarkId::new("PVM", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let (mut instance, export) = instantiate_module(&module, &engine);
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
group.bench_with_input(BenchmarkId::new("PVMInterpreter", l), p, |b, _| {
|
||||
let specs = revive_benchmarks::create_specs(&contract);
|
||||
b.iter_custom(|iters| revive_benchmarks::measure_pvm(&specs, iters));
|
||||
});
|
||||
}
|
||||
|
||||
group.finish();
|
||||
@@ -107,14 +46,6 @@ fn group<'error, M>(c: &'error mut Criterion<M>, group_name: &str) -> BenchmarkG
|
||||
where
|
||||
M: Measurement,
|
||||
{
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
{
|
||||
let mut group = c.benchmark_group(group_name);
|
||||
group.sample_size(10);
|
||||
group
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
return c.benchmark_group(group_name);
|
||||
}
|
||||
|
||||
@@ -127,49 +58,46 @@ fn bench_baseline(c: &mut Criterion) {
|
||||
|
||||
fn bench_odd_product(c: &mut Criterion) {
|
||||
let group = group(c, "OddPorduct");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = &[300000, 1200000, 12000000, 180000000, 720000000];
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = &[10_000, 100_000];
|
||||
let parameters = &[10_000, 100_000, 300000];
|
||||
|
||||
bench(group, parameters, parameters, Contract::odd_product);
|
||||
}
|
||||
|
||||
fn bench_triangle_number(c: &mut Criterion) {
|
||||
let group = group(c, "TriangleNumber");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = &[360000, 1440000, 14400000, 216000000, 864000000];
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = &[10_000, 100_000];
|
||||
let parameters = &[10_000, 100_000, 360000];
|
||||
|
||||
bench(group, parameters, parameters, Contract::triangle_number);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_recurisve(c: &mut Criterion) {
|
||||
let group = group(c, "FibonacciRecursive");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = &[24, 27, 31, 36, 39];
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = &[12, 16, 20];
|
||||
let parameters = [12, 16, 20, 24]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
bench(group, parameters, parameters, Contract::fib_recursive);
|
||||
bench(group, ¶meters, ¶meters, Contract::fib_recursive);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_iterative(c: &mut Criterion) {
|
||||
let group = group(c, "FibonacciIterative");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = &[256, 162500, 650000, 6500000, 100000000, 400000000];
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = &[64, 128, 256];
|
||||
let parameters = [64, 128, 256]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
bench(group, parameters, parameters, Contract::fib_iterative);
|
||||
bench(group, ¶meters, ¶meters, Contract::fib_iterative);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_binet(c: &mut Criterion) {
|
||||
let group = group(c, "FibonacciBinet");
|
||||
let parameters = &[64, 128, 256];
|
||||
let parameters = [64, 128, 256]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
bench(group, parameters, parameters, Contract::fib_binet);
|
||||
bench(group, ¶meters, ¶meters, Contract::fib_binet);
|
||||
}
|
||||
|
||||
fn bench_sha1(c: &mut Criterion) {
|
||||
@@ -177,7 +105,9 @@ fn bench_sha1(c: &mut Criterion) {
|
||||
let parameters = &[vec![0xff], vec![0xff; 64], vec![0xff; 512]];
|
||||
let labels = parameters.iter().map(|p| p.len()).collect::<Vec<_>>();
|
||||
|
||||
bench(group, parameters, &labels, Contract::sha1);
|
||||
bench(group, parameters, &labels, |input| {
|
||||
Contract::sha1(input.into())
|
||||
});
|
||||
}
|
||||
|
||||
criterion_group!(
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
|
||||
|
||||
use revive_integration::cases::Contract;
|
||||
|
||||
fn bench(
|
||||
c: &mut Criterion,
|
||||
group_name: &str,
|
||||
#[cfg(feature = "bench-evm")] evm_runtime: Vec<u8>,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))] pvm_runtime: Vec<u8>,
|
||||
) {
|
||||
let mut group = c.benchmark_group(group_name);
|
||||
let code_size = 0;
|
||||
|
||||
#[cfg(feature = "bench-evm")]
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("Evm", code_size),
|
||||
&evm_runtime,
|
||||
|b, code| b.iter(|| revive_differential::prepare(code.clone(), Vec::new())),
|
||||
);
|
||||
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Interpreter);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMInterpreterCompile", code_size),
|
||||
&(&pvm_runtime, engine),
|
||||
|b, (code, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::recompile_code(code, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Interpreter);
|
||||
let module = revive_integration::mock_runtime::recompile_code(&pvm_runtime, &engine);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMInterpreterInstantiate", code_size),
|
||||
&(module, engine),
|
||||
|b, (module, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::instantiate_module(module, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Compiler);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMCompile", code_size),
|
||||
&(&pvm_runtime, engine),
|
||||
|b, (code, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::recompile_code(code, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Compiler);
|
||||
let module = revive_integration::mock_runtime::recompile_code(&pvm_runtime, &engine);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMInstantiate", code_size),
|
||||
&(module, engine),
|
||||
|b, (module, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::instantiate_module(module, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn bench_baseline(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareBaseline",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::baseline().evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::baseline().pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_odd_product(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareOddProduct",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::odd_product(0).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::baseline().pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_triangle_number(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareTriangleNumber",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::triangle_number(0).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::triangle_number(0).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_recursive(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareFibonacciRecursive",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::fib_recursive(0).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::fib_recursive(0).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_iterative(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareFibonacciIterative",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::fib_iterative(0).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::fib_iterative(0).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_binet(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareFibonacciBinet",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::fib_binet(0).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::fib_binet(0).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_sha1(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareSHA1",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::sha1(Default::default()).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::sha1(Default::default()).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
criterion_group!(
|
||||
name = prepare;
|
||||
config = Criterion::default();
|
||||
targets = bench_baseline,
|
||||
bench_odd_product,
|
||||
bench_triangle_number,
|
||||
bench_fibonacci_recursive,
|
||||
bench_fibonacci_iterative,
|
||||
bench_fibonacci_binet,
|
||||
bench_sha1
|
||||
);
|
||||
criterion_main!(prepare);
|
||||
@@ -1,25 +1,70 @@
|
||||
use polkavm::{BackendKind, Config, Engine, ExportIndex, Instance, SandboxKind};
|
||||
use revive_integration::mock_runtime::{self, TransactionBuilder};
|
||||
use revive_integration::mock_runtime::{State, Transaction};
|
||||
|
||||
pub fn prepare_pvm(
|
||||
code: &[u8],
|
||||
input: Vec<u8>,
|
||||
backend: BackendKind,
|
||||
) -> (TransactionBuilder, Instance<Transaction>, ExportIndex) {
|
||||
let mut config = Config::new();
|
||||
config.set_backend(Some(backend));
|
||||
config.set_sandbox(Some(SandboxKind::Linux));
|
||||
|
||||
let (instance, export_index) = mock_runtime::prepare(code, Some(config));
|
||||
let transaction = State::default().transaction().calldata(input);
|
||||
|
||||
(transaction, instance, export_index)
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
pub fn create_specs(contract: &revive_integration::cases::Contract) -> revive_runner::Specs {
|
||||
use revive_runner::*;
|
||||
use SpecsAction::*;
|
||||
Specs {
|
||||
differential: false,
|
||||
actions: vec![
|
||||
Instantiate {
|
||||
code: Code::Bytes(contract.pvm_runtime.to_vec()),
|
||||
origin: TestAddress::Alice,
|
||||
data: Default::default(),
|
||||
value: Default::default(),
|
||||
gas_limit: Default::default(),
|
||||
storage_deposit_limit: Default::default(),
|
||||
salt: Default::default(),
|
||||
},
|
||||
Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
data: contract.calldata.to_vec(),
|
||||
value: Default::default(),
|
||||
gas_limit: Default::default(),
|
||||
storage_deposit_limit: Default::default(),
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn instantiate_engine(backend: BackendKind) -> Engine {
|
||||
let mut config = Config::new();
|
||||
config.set_backend(Some(backend));
|
||||
config.set_sandbox(Some(SandboxKind::Linux));
|
||||
mock_runtime::setup(Some(config))
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
pub fn measure_pvm(specs: &revive_runner::Specs, iters: u64) -> std::time::Duration {
|
||||
use revive_runner::*;
|
||||
let mut total_time = std::time::Duration::default();
|
||||
|
||||
for _ in 0..iters {
|
||||
let results = specs.clone().run();
|
||||
|
||||
let CallResult::Exec { result, wall_time } =
|
||||
results.get(1).expect("contract should have been called")
|
||||
else {
|
||||
panic!("expected a execution result");
|
||||
};
|
||||
let ret = result.result.as_ref().unwrap();
|
||||
assert!(!ret.did_revert());
|
||||
|
||||
total_time += *wall_time;
|
||||
}
|
||||
|
||||
total_time
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-evm")]
|
||||
pub fn measure_evm(code: &[u8], input: &[u8], iters: u64) -> std::time::Duration {
|
||||
let mut total_time = std::time::Duration::default();
|
||||
|
||||
let code = hex::encode(code);
|
||||
|
||||
for _ in 0..iters {
|
||||
let log = revive_differential::Evm::default()
|
||||
.code_blob(code.as_bytes().to_vec())
|
||||
.input(input.to_vec().into())
|
||||
.bench(true)
|
||||
.run();
|
||||
assert!(log.output.run_success(), "evm run failed: {log:?}");
|
||||
|
||||
total_time += log.execution_time().unwrap();
|
||||
}
|
||||
|
||||
total_time
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Use this template for reporting issues
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
### 🐛 Bug Report
|
||||
|
||||
#### 📝 Description
|
||||
|
||||
Provide a clear and concise description of the bug.
|
||||
|
||||
#### 🔄 Reproduction Steps
|
||||
|
||||
Steps to reproduce the behaviour
|
||||
|
||||
#### 🤔 Expected Behavior
|
||||
|
||||
Describe what you expected to happen.
|
||||
|
||||
#### 😯 Current Behavior
|
||||
|
||||
Describe what actually happened.
|
||||
|
||||
#### 🖥️ Environment
|
||||
|
||||
Any relevant environment details.
|
||||
|
||||
#### 📋 Additional Context
|
||||
|
||||
Add any other context about the problem here. If applicable, add screenshots to help explain.
|
||||
|
||||
#### 📎 Log Output
|
||||
|
||||
```
|
||||
Paste any relevant log output here.
|
||||
```
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Use this template for requesting features
|
||||
title: ''
|
||||
labels: feat
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
### 🌟 Feature Request
|
||||
|
||||
#### 📝 Description
|
||||
|
||||
Provide a clear and concise description of the feature you'd like to see.
|
||||
|
||||
#### 🤔 Rationale
|
||||
|
||||
Explain why this feature is important and how it benefits the project.
|
||||
|
||||
#### 📋 Additional Context
|
||||
|
||||
Add any other context or information about the feature request here.
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
# What ❔
|
||||
|
||||
<!-- What are the changes this PR brings about? -->
|
||||
<!-- Example: This PR adds a PR template to the repo. -->
|
||||
<!-- (For bigger PRs adding more context is appreciated) -->
|
||||
|
||||
## Why ❔
|
||||
|
||||
<!-- Why are these changes done? What goal do they contribute to? What are the principles behind them? -->
|
||||
<!-- Example: PR templates ensure PR reviewers, observers, and future iterators are in context about the evolution of repos. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
<!-- Check your PR fulfills the following items. -->
|
||||
<!-- For draft PRs check the boxes as you complete them. -->
|
||||
|
||||
- [ ] PR title corresponds to the body of PR.
|
||||
- [ ] Tests for the changes have been added / updated.
|
||||
- [ ] Documentation comments have been added / updated.
|
||||
- [ ] Code has been formatted via `cargo fmt` and checked with `cargo clippy`.
|
||||
@@ -1,9 +0,0 @@
|
||||
name: Cargo license check
|
||||
on: pull_request
|
||||
|
||||
jobs:
|
||||
cargo-deny:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: EmbarkStudios/cargo-deny-action@v1
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
name: "Rust CI"
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: cargo build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- run: cargo build --verbose
|
||||
|
||||
formatting:
|
||||
name: cargo fmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
components: rustfmt
|
||||
- name: Rustfmt Check
|
||||
uses: actions-rust-lang/rustfmt@v1
|
||||
@@ -1,17 +0,0 @@
|
||||
name: Leaked Secrets Scan
|
||||
on: [pull_request]
|
||||
jobs:
|
||||
TruffleHog:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: TruffleHog OSS
|
||||
uses: trufflesecurity/trufflehog@0c66d30c1f4075cee1aada2e1ab46dabb1b0071a
|
||||
with:
|
||||
path: ./
|
||||
base: ${{ github.event.repository.default_branch }}
|
||||
head: HEAD
|
||||
extra_args: --debug --only-verified
|
||||
@@ -20,7 +20,7 @@ pub const BIT_LENGTH_ETH_ADDRESS: usize =
|
||||
pub const BIT_LENGTH_WORD: usize = crate::byte_length::BYTE_LENGTH_WORD * BIT_LENGTH_BYTE;
|
||||
|
||||
/// Bit length of the runtime value type.
|
||||
pub const BIT_LENGTH_VALUE: usize = crate::byte_length::BYTE_LENGTH_VALUE * BIT_LENGTH_BYTE;
|
||||
pub const BIT_LENGTH_VALUE: usize = BIT_LENGTH_WORD;
|
||||
|
||||
/// Bit length of thre runimte block number type.
|
||||
pub const BIT_LENGTH_BLOCK_NUMBER: usize =
|
||||
|
||||
@@ -6,15 +6,12 @@ pub const BYTE_LENGTH_BYTE: usize = 1;
|
||||
/// The x86 word byte-length.
|
||||
pub const BYTE_LENGTH_X32: usize = 4;
|
||||
|
||||
/// Native stack alignment size in bytes
|
||||
#[cfg(not(feautre = "riscv-64"))]
|
||||
pub const BYTE_LENGTH_STACK_ALIGN: usize = 4;
|
||||
#[cfg(feautre = "riscv-64")]
|
||||
pub const BYTE_LENGTH_STACK_ALIGN: usize = 8;
|
||||
|
||||
/// The x86_64 word byte-length.
|
||||
pub const BYTE_LENGTH_X64: usize = 8;
|
||||
|
||||
/// EVM native stack alignment size in bytes
|
||||
pub const BYTE_LENGTH_STACK_ALIGN: usize = 32;
|
||||
|
||||
/// The ETH address byte-length.
|
||||
pub const BYTE_LENGTH_ETH_ADDRESS: usize = 20;
|
||||
|
||||
@@ -25,7 +22,7 @@ pub const BYTE_LENGTH_WORD: usize = 32;
|
||||
pub const BYTE_LENGTH_VALUE: usize = 32;
|
||||
|
||||
/// Byte length of the runtime block number type.
|
||||
pub const BYTE_LENGTH_BLOCK_NUMBER: usize = 8;
|
||||
pub const BYTE_LENGTH_BLOCK_NUMBER: usize = 4;
|
||||
|
||||
/// Byte length of the runtime block timestamp type.
|
||||
pub const BYTE_LENGTH_BLOCK_TIMESTAMP: usize = 8;
|
||||
pub const BYTE_LENGTH_BLOCK_TIMESTAMP: usize = 4;
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
//!
|
||||
//! The exit code constants.
|
||||
//!
|
||||
//! The revive exit code constants.
|
||||
|
||||
/// The common application success exit code.
|
||||
pub const EXIT_CODE_SUCCESS: i32 = 0;
|
||||
|
||||
@@ -6,7 +6,6 @@ pub(crate) mod byte_length;
|
||||
pub(crate) mod evm_version;
|
||||
pub(crate) mod exit_code;
|
||||
pub(crate) mod extension;
|
||||
pub(crate) mod polkavm;
|
||||
pub(crate) mod utils;
|
||||
|
||||
pub use self::base::*;
|
||||
@@ -15,5 +14,4 @@ pub use self::byte_length::*;
|
||||
pub use self::evm_version::EVMVersion;
|
||||
pub use self::exit_code::*;
|
||||
pub use self::extension::*;
|
||||
pub use self::polkavm::address::*;
|
||||
pub use self::utils::*;
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
//! The PolkaVM address constants.
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_TO_L1: u16 = 0xFFFF;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_PRECOMPILE: u16 = 0xFFFD;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_META: u16 = 0xFFFC;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_MIMIC_CALL: u16 = 0xFFFB;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_MIMIC_CALL: u16 = 0xFFFA;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_MIMIC_CALL_BYREF: u16 = 0xFFF9;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_MIMIC_CALL_BYREF: u16 = 0xFFF8;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_RAW_FAR_CALL: u16 = 0xFFF7;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_RAW_FAR_CALL_BYREF: u16 = 0xFFF6;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_CALL: u16 = 0xFFF5;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_CALL_BYREF: u16 = 0xFFF4;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SET_CONTEXT_VALUE_CALL: u16 = 0xFFF3;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SET_PUBDATA_PRICE: u16 = 0xFFF2;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_INCREMENT_TX_COUNTER: u16 = 0xFFF1;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_PTR_CALLDATA: u16 = 0xFFF0;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_CALL_FLAGS: u16 = 0xFFEF;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_PTR_RETURN_DATA: u16 = 0xFFEE;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_EVENT_INITIALIZE: u16 = 0xFFED;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_EVENT_WRITE: u16 = 0xFFEC;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_LOAD_CALLDATA: u16 = 0xFFEB;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_LOAD_RETURN_DATA: u16 = 0xFFEA;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_ADD: u16 = 0xFFE9;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_SHRINK: u16 = 0xFFE8;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_PACK: u16 = 0xFFE7;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_MULTIPLICATION_HIGH_REGISTER: u16 = 0xFFE6;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_EXTRA_ABI_DATA: u16 = 0xFFE5;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_DATA_LOAD: u16 = 0xFFE4;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_DATA_COPY: u16 = 0xFFE3;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_DATA_SIZE: u16 = 0xFFE2;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_DECLARE: u16 = 0xFFE1;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_SET: u16 = 0xFFE0;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_FINALIZE: u16 = 0xFFDF;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_GET: u16 = 0xFFDE;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_DECOMMIT: u16 = 0xFFDD;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_LOAD_DECOMMIT: u16 = 0xFFDC;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_RETURN_FORWARD: u16 = 0xFFDB;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_REVERT_FORWARD: u16 = 0xFFDA;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_SWAP: u16 = 0xFFD9;
|
||||
@@ -1,5 +0,0 @@
|
||||
//!
|
||||
//! The PolkaVM constants.
|
||||
//!
|
||||
|
||||
pub mod address;
|
||||
@@ -6,6 +6,10 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
evm-interpreter = { workspace = true }
|
||||
primitive-types = { workspace = true }
|
||||
alloy-primitives = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
alloy-primitives = { workspace = true, features = ["serde"] }
|
||||
alloy-genesis = { workspace = true }
|
||||
alloy-serde = { workspace = true }
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"config": {
|
||||
"chainId": 420420420,
|
||||
"homesteadBlock": 0,
|
||||
"eip150Block": 0,
|
||||
"eip155Block": 0,
|
||||
"eip158Block": 0,
|
||||
"byzantiumBlock": 0,
|
||||
"constantinopleBlock": 0,
|
||||
"petersburgBlock": 0,
|
||||
"istanbulBlock": 0,
|
||||
"berlinBlock": 0,
|
||||
"londonBlock": 0,
|
||||
"arrowGlacierBlock": 0,
|
||||
"grayGlacierBlock": 0,
|
||||
"shanghaiTime": 0,
|
||||
"cancunTime": 0,
|
||||
"terminalTotalDifficulty": 0,
|
||||
"terminalTotalDifficultyPassed": true
|
||||
},
|
||||
"coinbase": "0x0000000000000000000000000000000000000000",
|
||||
"difficulty": "0x20000",
|
||||
"extraData": "",
|
||||
"gasLimit": "0xffffffff",
|
||||
"nonce": "0x0000000000000042",
|
||||
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"timestamp": "0x00",
|
||||
"alloc": {
|
||||
"0101010101010101010101010101010101010101": {
|
||||
"balance": "1000000000"
|
||||
},
|
||||
"0202020202020202020202020202020202020202": {
|
||||
"balance": "1000000000"
|
||||
},
|
||||
"0303030303030303030303030303030303030303": {
|
||||
"balance": "1000000000"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
use std::time::Duration;
|
||||
|
||||
/// Parse a go formatted duration.
|
||||
///
|
||||
/// Sources:
|
||||
/// - https://crates.io/crates/go-parse-duration (fixed an utf8 bug)
|
||||
/// - https://github.com/golang/go/blob/master/src/time/format.go
|
||||
pub fn parse_go_duration(value: &str) -> Result<Duration, String> {
|
||||
parse_duration(value).map(|ns| Duration::from_nanos(ns.unsigned_abs()))
|
||||
}
|
||||
|
||||
fn parse_duration(string: &str) -> Result<i64, String> {
|
||||
// [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+
|
||||
let mut s = string;
|
||||
let mut d: i64 = 0; // duration to be returned
|
||||
let mut neg = false;
|
||||
|
||||
// Consume [-+]?
|
||||
if !s.is_empty() {
|
||||
let c = *s.as_bytes().first().unwrap();
|
||||
if c == b'-' || c == b'+' {
|
||||
neg = c == b'-';
|
||||
s = &s[1..];
|
||||
}
|
||||
}
|
||||
// Special case: if all that is left is "0", this is zero.
|
||||
if s == "0" {
|
||||
return Ok(0);
|
||||
}
|
||||
if s.is_empty() {
|
||||
return Err(format!("invalid duration: {string}"));
|
||||
}
|
||||
while !s.is_empty() {
|
||||
// integers before, after decimal point
|
||||
let mut v: i64;
|
||||
let mut f: i64 = 0;
|
||||
// value = v + f / scale
|
||||
let mut scale: f64 = 1f64;
|
||||
|
||||
// The next character must be [0-9.]
|
||||
let c = *s.as_bytes().first().unwrap();
|
||||
if !(c == b'.' || c.is_ascii_digit()) {
|
||||
return Err(format!("invalid duration: {string}"));
|
||||
}
|
||||
// Consume [0-9]*
|
||||
let pl = s.len();
|
||||
match leading_int(s) {
|
||||
Ok((_v, _s)) => {
|
||||
v = _v;
|
||||
s = _s;
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(format!("invalid duration: {string}"));
|
||||
}
|
||||
}
|
||||
let pre = pl != s.len(); // whether we consume anything before a period
|
||||
|
||||
// Consume (\.[0-9]*)?
|
||||
let mut post = false;
|
||||
if !s.is_empty() && *s.as_bytes().first().unwrap() == b'.' {
|
||||
s = &s[1..];
|
||||
let pl = s.len();
|
||||
let (f_, scale_, s_) = leading_fraction(s);
|
||||
{
|
||||
f = f_;
|
||||
scale = scale_;
|
||||
s = s_;
|
||||
}
|
||||
post = pl != s.len();
|
||||
}
|
||||
if !pre && !post {
|
||||
// no digits (e.g. ".s" or "-.s")
|
||||
return Err(format!("invalid duration: {string}"));
|
||||
}
|
||||
|
||||
// Consume unit.
|
||||
let mut i = 0;
|
||||
while i < s.len() {
|
||||
let c = *s.as_bytes().get(i).unwrap();
|
||||
if c == b'.' || c.is_ascii_digit() {
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if i == 0 {
|
||||
return Err(format!("missing unit in duration: {string}"));
|
||||
}
|
||||
let u = &s[..i];
|
||||
s = &s[i..];
|
||||
let unit = match u {
|
||||
"ns" => 1i64,
|
||||
"us" => 1000i64,
|
||||
"µs" => 1000i64, // U+00B5 = micro symbol
|
||||
"μs" => 1000i64, // U+03BC = Greek letter mu
|
||||
"ms" => 1000000i64,
|
||||
"s" => 1000000000i64,
|
||||
"m" => 60000000000i64,
|
||||
"h" => 3600000000000i64,
|
||||
_ => {
|
||||
return Err(format!("unknown unit {u} in duration {string}"));
|
||||
}
|
||||
};
|
||||
if v > (1 << (63 - 1)) / unit {
|
||||
// overflow
|
||||
return Err(format!("invalid duration {string}"));
|
||||
}
|
||||
v *= unit;
|
||||
if f > 0 {
|
||||
// f64 is needed to be nanosecond accurate for fractions of hours.
|
||||
// v >= 0 && (f*unit/scale) <= 3.6e+12 (ns/h, h is the largest unit)
|
||||
v += (f as f64 * (unit as f64 / scale)) as i64;
|
||||
if v < 0 {
|
||||
// overflow
|
||||
return Err(format!("invalid duration {string}"));
|
||||
}
|
||||
}
|
||||
d += v;
|
||||
if d < 0 {
|
||||
// overflow
|
||||
return Err(format!("invalid duration {string}"));
|
||||
}
|
||||
}
|
||||
if neg {
|
||||
d = -d;
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
fn leading_int(s: &str) -> Result<(i64, &str), String> {
|
||||
let mut x = 0;
|
||||
let mut i = 0;
|
||||
while i < s.len() {
|
||||
let c = s.chars().nth(i).unwrap();
|
||||
if !c.is_ascii_digit() {
|
||||
break;
|
||||
}
|
||||
if x > (1 << (63 - 1)) / 10 {
|
||||
return Err("overflow".into());
|
||||
}
|
||||
let d = i64::from(c.to_digit(10).unwrap());
|
||||
x = x * 10 + d;
|
||||
if x < 0 {
|
||||
// overflow
|
||||
return Err("overflow".into());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Ok((x, &s[i..]))
|
||||
}
|
||||
|
||||
fn leading_fraction(s: &str) -> (i64, f64, &str) {
|
||||
let mut i = 0;
|
||||
let mut x = 0i64;
|
||||
let mut scale = 1f64;
|
||||
let mut overflow = false;
|
||||
while i < s.len() {
|
||||
let c = s.chars().nth(i).unwrap();
|
||||
if !c.is_ascii_digit() {
|
||||
break;
|
||||
}
|
||||
if overflow {
|
||||
continue;
|
||||
}
|
||||
if x > (1 << (63 - 1)) / 10 {
|
||||
// It's possible for overflow to give a positive number, so take care.
|
||||
overflow = true;
|
||||
continue;
|
||||
}
|
||||
let d = i64::from(c.to_digit(10).unwrap());
|
||||
let y = x * 10 + d;
|
||||
if y < 0 {
|
||||
overflow = true;
|
||||
continue;
|
||||
}
|
||||
x = y;
|
||||
scale *= 10f64;
|
||||
i += 1;
|
||||
}
|
||||
(x, scale, &s[i..])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_duration;
|
||||
|
||||
#[test]
|
||||
fn test_parse_duration() {
|
||||
assert_eq!(parse_duration("8.731µs"), Ok(8731));
|
||||
assert_eq!(parse_duration("50ns"), Ok(50));
|
||||
assert_eq!(parse_duration("3ms"), Ok(3000000));
|
||||
assert_eq!(parse_duration("2us"), Ok(2000));
|
||||
assert_eq!(parse_duration("4.0s"), Ok(4000000000));
|
||||
assert_eq!(parse_duration("1h45m"), Ok(6300000000000));
|
||||
assert_eq!(
|
||||
parse_duration("1"),
|
||||
Err(String::from("missing unit in duration: 1")),
|
||||
);
|
||||
}
|
||||
}
|
||||
+554
-144
@@ -1,159 +1,569 @@
|
||||
use alloy_primitives::{keccak256, Address, B256};
|
||||
use evm_interpreter::{
|
||||
interpreter::{EtableInterpreter, RunInterpreter},
|
||||
trap::CallCreateTrap,
|
||||
Context, Etable, ExitError, Log, Machine, RuntimeBackend, RuntimeBaseBackend,
|
||||
RuntimeEnvironment, RuntimeState, TransactionContext, Valids,
|
||||
use core::str;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::Write,
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
str::FromStr,
|
||||
time::Duration,
|
||||
};
|
||||
use primitive_types::{H160, H256, U256};
|
||||
|
||||
static RUNTIME_ETABLE: Etable<RuntimeState, UnimplementedHandler, CallCreateTrap> =
|
||||
Etable::runtime();
|
||||
use alloy_genesis::{Genesis, GenesisAccount};
|
||||
use alloy_primitives::{hex::ToHexExt, Address, Bytes, B256, U256};
|
||||
use alloy_serde::storage::deserialize_storage_map;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Deserializer, Value};
|
||||
use tempfile::{NamedTempFile, TempPath};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UnimplementedHandler {
|
||||
logs: Vec<Log>,
|
||||
pub use self::go_duration::parse_go_duration;
|
||||
|
||||
mod go_duration;
|
||||
|
||||
const GENESIS_JSON: &str = include_str!("../genesis.json");
|
||||
const EXECUTABLE_NAME: &str = "evm";
|
||||
const EXECUTABLE_ARGS: [&str; 8] = [
|
||||
"--log.format=json",
|
||||
"run",
|
||||
"--dump",
|
||||
"--nomemory=false",
|
||||
"--noreturndata=false",
|
||||
"--json",
|
||||
"--codefile",
|
||||
"-",
|
||||
];
|
||||
const EXECUTABLE_ARGS_BENCH: [&str; 6] = [
|
||||
"run",
|
||||
"--bench",
|
||||
"--nomemory=false",
|
||||
"--noreturndata=false",
|
||||
"--codefile",
|
||||
"-",
|
||||
];
|
||||
const GAS_USED_MARKER: &str = "EVM gas used:";
|
||||
const REVERT_MARKER: &str = " error: ";
|
||||
|
||||
/// The geth EVM state dump structure
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct StateDump {
|
||||
pub root: Bytes,
|
||||
pub accounts: BTreeMap<Address, Account>,
|
||||
}
|
||||
|
||||
impl RuntimeEnvironment for UnimplementedHandler {
|
||||
fn block_hash(&self, _number: U256) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_number(&self) -> U256 {
|
||||
U256::from(123)
|
||||
}
|
||||
fn block_coinbase(&self) -> H160 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_timestamp(&self) -> U256 {
|
||||
U256::from(456)
|
||||
}
|
||||
fn block_difficulty(&self) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_randomness(&self) -> Option<H256> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_gas_limit(&self) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_base_fee_per_gas(&self) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn chain_id(&self) -> U256 {
|
||||
unimplemented!()
|
||||
impl From<StateDump> for Genesis {
|
||||
fn from(value: StateDump) -> Self {
|
||||
let mut genesis: Genesis = serde_json::from_str(GENESIS_JSON).unwrap();
|
||||
genesis.alloc = value
|
||||
.accounts
|
||||
.iter()
|
||||
.map(|(address, account)| (*address, account.clone().into()))
|
||||
.collect();
|
||||
genesis
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeBaseBackend for UnimplementedHandler {
|
||||
fn balance(&self, _address: H160) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn code_size(&self, _address: H160) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn code_hash(&self, _address: H160) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn code(&self, _address: H160) -> Vec<u8> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn storage(&self, _address: H160, _index: H256) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn exists(&self, _address: H160) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn nonce(&self, _address: H160) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
/// The geth EVM state dump account structure
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Account {
|
||||
pub balance: U256,
|
||||
pub nonce: u64,
|
||||
pub code: Option<Bytes>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "deserialize_storage_map"
|
||||
)]
|
||||
pub storage: Option<BTreeMap<B256, B256>>,
|
||||
pub key: Option<B256>,
|
||||
}
|
||||
|
||||
impl RuntimeBackend for UnimplementedHandler {
|
||||
fn original_storage(&self, _address: H160, _index: H256) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn deleted(&self, _address: H160) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
fn is_cold(&self, _address: H160, _index: Option<H256>) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn mark_hot(&mut self, _address: H160, _index: Option<H256>) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn set_storage(&mut self, _address: H160, _index: H256, _value: H256) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn log(&mut self, log: Log) -> Result<(), ExitError> {
|
||||
self.logs.push(log);
|
||||
Ok(())
|
||||
}
|
||||
fn mark_delete(&mut self, _address: H160) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn reset_storage(&mut self, _address: H160) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn set_code(&mut self, _address: H160, _code: Vec<u8>) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn reset_balance(&mut self, _address: H160) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn deposit(&mut self, _address: H160, _value: U256) {
|
||||
unimplemented!()
|
||||
}
|
||||
fn withdrawal(&mut self, _address: H160, _value: U256) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn inc_nonce(&mut self, _address: H160) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PreparedEvm {
|
||||
pub valids: Valids,
|
||||
pub vm: Machine<RuntimeState>,
|
||||
}
|
||||
|
||||
pub fn prepare(code: Vec<u8>, data: Vec<u8>) -> PreparedEvm {
|
||||
let address = Address::default().create2(B256::default(), keccak256([]).0);
|
||||
let caller = Address::default().create2(B256::default(), keccak256([]).0);
|
||||
|
||||
let state = RuntimeState {
|
||||
context: Context {
|
||||
address: H160::from(address.0 .0),
|
||||
caller: H160::from(caller.0 .0),
|
||||
apparent_value: U256::default(),
|
||||
},
|
||||
transaction_context: TransactionContext {
|
||||
gas_price: U256::default(),
|
||||
origin: H160::default(),
|
||||
impl From<Account> for GenesisAccount {
|
||||
fn from(value: Account) -> Self {
|
||||
GenesisAccount {
|
||||
balance: value.balance,
|
||||
nonce: Some(value.nonce),
|
||||
code: value.code,
|
||||
storage: value.storage,
|
||||
private_key: value.key,
|
||||
}
|
||||
.into(),
|
||||
retbuf: Vec::new(),
|
||||
};
|
||||
|
||||
PreparedEvm {
|
||||
valids: Valids::new(&code[..]),
|
||||
vm: evm_interpreter::Machine::new(code.into(), data.to_vec().into(), 1024, 0xFFFF, state),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute(pre: PreparedEvm) -> (Vec<u8>, Vec<Log>) {
|
||||
let mut vm = EtableInterpreter::new_valid(pre.vm, &RUNTIME_ETABLE, pre.valids);
|
||||
let mut handler = UnimplementedHandler::default();
|
||||
vm.run(&mut handler).exit().unwrap().unwrap();
|
||||
(vm.retval.clone(), handler.logs)
|
||||
/// Contains the output from geth `emv` invocations
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct EvmOutput {
|
||||
pub output: Bytes,
|
||||
#[serde(rename = "gasUsed")]
|
||||
pub gas_used: U256,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl EvmOutput {
|
||||
/// Return if there was no error found.
|
||||
///
|
||||
/// Panics if the gas used is zero as this indicates nothing was run.
|
||||
pub fn run_success(&self) -> bool {
|
||||
assert_ne!(self.gas_used, U256::ZERO, "nothing was executed: {self:?}");
|
||||
self.error.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Contains the full log from geth `emv` invocations
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EvmLog {
|
||||
pub account_deployed: Option<Address>,
|
||||
pub output: EvmOutput,
|
||||
pub state_dump: StateDump,
|
||||
pub stderr: String,
|
||||
}
|
||||
|
||||
impl EvmLog {
|
||||
pub const EXECUTION_TIME_MARKER: &'static str = "execution time:";
|
||||
|
||||
/// Parse the reported execution time from stderr (requires --bench)
|
||||
pub fn execution_time(&self) -> Result<Duration, String> {
|
||||
for line in self.stderr.lines() {
|
||||
if let Some(value) = line.split("execution time:").nth(1) {
|
||||
return parse_go_duration(value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"execution time marker '{}' not found in raw EVM log",
|
||||
Self::EXECUTION_TIME_MARKER
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_gas_used_from_bench(&mut self) {
|
||||
for line in self.stderr.lines() {
|
||||
if let Some(gas_line) = line.split(GAS_USED_MARKER).nth(1) {
|
||||
let gas_used = gas_line.trim().parse::<u64>().unwrap_or_else(|error| {
|
||||
panic!("invalid output '{gas_line}' for gas used: {error}")
|
||||
});
|
||||
self.output.gas_used = U256::from(gas_used);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for EvmLog {
|
||||
fn from(value: &str) -> Self {
|
||||
let mut output = None;
|
||||
let mut state_dump = None;
|
||||
for value in Deserializer::from_str(value).into_iter::<Value>() {
|
||||
let Ok(value) = value else { continue };
|
||||
if let Ok(value @ EvmOutput { .. }) = serde_json::from_value(value.clone()) {
|
||||
output = Some(value);
|
||||
continue;
|
||||
}
|
||||
if let Ok(value @ StateDump { .. }) = serde_json::from_value(value) {
|
||||
state_dump = Some(value);
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(output), Some(state_dump)) = (output, state_dump) {
|
||||
return Self {
|
||||
account_deployed: None,
|
||||
output,
|
||||
state_dump,
|
||||
stderr: value.into(),
|
||||
};
|
||||
}
|
||||
|
||||
EvmLog {
|
||||
account_deployed: None,
|
||||
output: EvmOutput {
|
||||
error: value.find(REVERT_MARKER).map(|_| REVERT_MARKER.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
state_dump: Default::default(),
|
||||
stderr: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builder for running contracts in geth `evm`
|
||||
pub struct Evm {
|
||||
genesis_json: Option<String>,
|
||||
genesis_path: Option<PathBuf>,
|
||||
code: Option<Vec<u8>>,
|
||||
input: Option<Bytes>,
|
||||
receiver: Option<String>,
|
||||
sender: String,
|
||||
value: Option<u128>,
|
||||
gas: Option<u64>,
|
||||
create: bool,
|
||||
bench: bool,
|
||||
}
|
||||
|
||||
impl Default for Evm {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
genesis_json: Some(GENESIS_JSON.to_string()),
|
||||
genesis_path: None,
|
||||
code: None,
|
||||
input: None,
|
||||
receiver: None,
|
||||
sender: Address::default().encode_hex(),
|
||||
value: None,
|
||||
gas: None,
|
||||
create: false,
|
||||
bench: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Evm {
|
||||
/// Create a new EVM with the given `genesis`
|
||||
pub fn from_genesis(genesis: Genesis) -> Self {
|
||||
Self::default().genesis_json(genesis)
|
||||
}
|
||||
|
||||
/// Run the `code`
|
||||
pub fn code_blob(self, blob: Vec<u8>) -> Self {
|
||||
Self {
|
||||
code: Some(blob),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the calldata
|
||||
pub fn input(self, bytes: Bytes) -> Self {
|
||||
Self {
|
||||
input: (!bytes.is_empty()).then_some(bytes),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the create flag
|
||||
pub fn deploy(self, enable: bool) -> Self {
|
||||
Self {
|
||||
create: enable,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the transferred value
|
||||
pub fn value(self, value: u128) -> Self {
|
||||
Self {
|
||||
value: Some(value),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the gas limit
|
||||
pub fn gas(self, limit: u64) -> Self {
|
||||
Self {
|
||||
gas: Some(limit),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Provide the prestate genesis configuration
|
||||
pub fn genesis_json(self, genesis: Genesis) -> Self {
|
||||
let genesis_json = serde_json::to_string(&genesis).expect("state dump should be valid");
|
||||
// TODO: Investigate
|
||||
let genesis_json = genesis_json.replace("\"0x0\"", "0").into();
|
||||
|
||||
Self {
|
||||
genesis_json,
|
||||
genesis_path: None,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Provide a path to the genesis file to be used
|
||||
pub fn genesis_path(self, path: PathBuf) -> Self {
|
||||
Self {
|
||||
genesis_path: Some(path),
|
||||
genesis_json: None,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the callee address
|
||||
pub fn receiver(self, address: Address) -> Self {
|
||||
Self {
|
||||
receiver: Some(address.encode_hex()),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the caller address
|
||||
pub fn sender(self, address: Address) -> Self {
|
||||
Self {
|
||||
sender: address.encode_hex(),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Run as a benchmark
|
||||
pub fn bench(self, flag: bool) -> Self {
|
||||
Self {
|
||||
bench: flag,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate the address of the contract account this deploy call would create
|
||||
pub fn expect_account_created(&self) -> Address {
|
||||
assert!(self.create, "expected a deploy call");
|
||||
let sender = Address::from_str(&self.sender).expect("sender address should be valid");
|
||||
let genesis: Genesis = match (self.genesis_json.as_ref(), self.genesis_path.as_ref()) {
|
||||
(Some(json), None) => serde_json::from_str(json).unwrap(),
|
||||
(None, Some(path)) => {
|
||||
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
|
||||
}
|
||||
_ => panic!("provided a genesis json and a genesis json path"),
|
||||
};
|
||||
let nonce = genesis
|
||||
.alloc
|
||||
.get(&sender)
|
||||
.map(|account| account.nonce.unwrap_or(0))
|
||||
.unwrap_or(0);
|
||||
sender.create(nonce)
|
||||
}
|
||||
|
||||
/// Return the path to the genesis file;
|
||||
/// writes the genesis file into a tmpdir if necessary.
|
||||
///
|
||||
/// `TempPath`` will delete on drop, so need to keep it around
|
||||
fn write_genesis_file(&self, temp_path: &mut Option<TempPath>) -> String {
|
||||
match (self.genesis_json.as_ref(), self.genesis_path.as_ref()) {
|
||||
(Some(json), None) => {
|
||||
let mut temp_file = NamedTempFile::new().unwrap();
|
||||
temp_file.write_all(json.as_bytes()).unwrap();
|
||||
let path = temp_file.into_temp_path();
|
||||
*temp_path = Some(path);
|
||||
temp_path.as_ref().unwrap().display().to_string()
|
||||
}
|
||||
(None, Some(path)) => path.display().to_string(),
|
||||
_ => panic!("provided a genesis json and a genesis json path"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the call in a geth `evm` subprocess.
|
||||
///
|
||||
/// Definitively not a hairy plumbing function.
|
||||
pub fn run(self) -> EvmLog {
|
||||
let mut temp_path = None;
|
||||
let genesis_json_path = &self.write_genesis_file(&mut temp_path);
|
||||
|
||||
// Static args
|
||||
let mut command = Command::new(PathBuf::from(EXECUTABLE_NAME));
|
||||
command
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
if self.bench {
|
||||
command.args(EXECUTABLE_ARGS_BENCH);
|
||||
} else {
|
||||
command.args(EXECUTABLE_ARGS);
|
||||
};
|
||||
|
||||
// Dynamic args
|
||||
command.args(["--prestate", genesis_json_path]);
|
||||
command.args(["--sender", &self.sender]);
|
||||
if let Some(input) = &self.input {
|
||||
command.args(["--input", hex::encode(input).as_str()]);
|
||||
}
|
||||
let account_deployed = if self.create {
|
||||
command.arg("--create");
|
||||
self.expect_account_created().into()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match (&self.code, &self.receiver) {
|
||||
(Some(_), None) => {}
|
||||
(None, Some(address)) => {
|
||||
command.args(["--receiver", address]);
|
||||
}
|
||||
(Some(_), Some(_)) => panic!("code and receiver specified"),
|
||||
_ => panic!("no code file or receiver specified"),
|
||||
}
|
||||
if let Some(gas) = self.gas {
|
||||
command.args(["--gas", &format!("{gas}")]);
|
||||
}
|
||||
if let Some(value) = self.value {
|
||||
command.args(["--value", &format!("{value}")]);
|
||||
}
|
||||
|
||||
// Run the evm subprocess and assert success return value
|
||||
let process = command.spawn().unwrap_or_else(|error| {
|
||||
panic!("{EXECUTABLE_NAME} subprocess spawning error: {error:?}")
|
||||
});
|
||||
let buf = vec![];
|
||||
process
|
||||
.stdin
|
||||
.as_ref()
|
||||
.unwrap_or_else(|| panic!("{EXECUTABLE_NAME} stdin getting error"))
|
||||
.write_all(self.code.as_ref().unwrap_or(&buf))
|
||||
.unwrap_or_else(|err| panic!("{EXECUTABLE_NAME} stdin writing error: {err:?}"));
|
||||
|
||||
let output = process
|
||||
.wait_with_output()
|
||||
.unwrap_or_else(|err| panic!("{EXECUTABLE_NAME} subprocess output error: {err}"));
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{EXECUTABLE_NAME} command failed: {output:?}",
|
||||
);
|
||||
drop(temp_path);
|
||||
|
||||
let stdout = str::from_utf8(output.stdout.as_slice())
|
||||
.unwrap_or_else(|err| panic!("{EXECUTABLE_NAME} stdout failed to parse: {err}"));
|
||||
let stderr = str::from_utf8(output.stderr.as_slice())
|
||||
.unwrap_or_else(|err| panic!("{EXECUTABLE_NAME} stderr failed to parse: {err}"));
|
||||
|
||||
let mut log: EvmLog = stdout.into();
|
||||
log.stderr = stderr.into();
|
||||
if self.bench {
|
||||
log.parse_gas_used_from_bench();
|
||||
}
|
||||
|
||||
// Set the deployed account
|
||||
log.account_deployed = account_deployed;
|
||||
log
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{str::FromStr, time::Duration};
|
||||
|
||||
use alloy_genesis::Genesis;
|
||||
use alloy_primitives::{Bytes, B256, U256};
|
||||
|
||||
use crate::{Evm, EvmLog, EvmOutput, StateDump};
|
||||
|
||||
const OUTPUT_JSON_OK: &str = r#"{"output":"0000000000000000000000000000000000000000000000000000000000000000","gasUsed":"0x11d"}"#;
|
||||
const OUTPUT_JSON_REVERTED: &str =
|
||||
r#"{"output":"","gasUsed":"0x2d","error":"execution reverted"}"#;
|
||||
const STATE_DUMP: &str = r#"
|
||||
{
|
||||
"root": "eb5d51177cb9049b848ea92f87f9a3f00abfb683d0866c2eddecc5692ad27f86",
|
||||
"accounts": {
|
||||
"0x1f2a98889594024BFfdA3311CbE69728d392C06D": {
|
||||
"balance": "0",
|
||||
"nonce": 1,
|
||||
"root": "0x63cfcda8d81a8b1840b1b9722c37f929a4037e53ad1ce6abdef31c0c8bac1f61",
|
||||
"codeHash": "0xa6e0062c5ba829446695f179b97702a75f7d354e33445d2e928ed00e1a39e88f",
|
||||
"code": "0x608060405260043610610028575f3560e01c80633fa4f2451461002c578063b144adfb1461004a575b5f80fd5b610034610086565b60405161004191906100c5565b60405180910390f35b348015610055575f80fd5b50610070600480360381019061006b919061013c565b61008d565b60405161007d91906100c5565b60405180910390f35b5f34905090565b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f819050919050565b6100bf816100ad565b82525050565b5f6020820190506100d85f8301846100b6565b92915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61010b826100e2565b9050919050565b61011b81610101565b8114610125575f80fd5b50565b5f8135905061013681610112565b92915050565b5f60208284031215610151576101506100de565b5b5f61015e84828501610128565b9150509291505056fea2646970667358221220a2109c2f05a629fff4640e9f0cf12a698bbea9b0858a4029901e88bf5d1c926964736f6c63430008190033",
|
||||
"storage": {
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000": "02"
|
||||
},
|
||||
"address": "0x1f2a98889594024bffda3311cbe69728d392c06d",
|
||||
"key": "0xcbeeb4463624bc2f332dcfe2b479eddb1c380ec862ee63d9f31b31b854fb7c61"
|
||||
}
|
||||
}
|
||||
}"#;
|
||||
const EVM_BIN_FIXTURE: &str = "6080604052348015600e575f80fd5b506040516101403803806101408339818101604052810190602e9190607f565b805f806101000a81548160ff0219169083151502179055505060a5565b5f80fd5b5f8115159050919050565b606181604f565b8114606a575f80fd5b50565b5f81519050607981605a565b92915050565b5f602082840312156091576090604b565b5b5f609c84828501606d565b91505092915050565b608f806100b15f395ff3fe6080604052348015600e575f80fd5b50600436106026575f3560e01c8063cde4efa914602a575b5f80fd5b60306032565b005b5f8054906101000a900460ff16155f806101000a81548160ff02191690831515021790555056fea264697066735822122046c92dd2fd612b1ed93d184dad4c49f61c44690722c4a6c7c746ebeb0aadeb4a64736f6c63430008190033";
|
||||
const EVM_BIN_RUNTIME_FIXTURE: &str = "6080604052348015600e575f80fd5b50600436106026575f3560e01c8063cde4efa914602a575b5f80fd5b60306032565b005b5f8054906101000a900460ff16155f806101000a81548160ff02191690831515021790555056fea264697066735822122046c92dd2fd612b1ed93d184dad4c49f61c44690722c4a6c7c746ebeb0aadeb4a64736f6c63430008190033";
|
||||
const EVM_BIN_FIXTURE_INPUT: &str =
|
||||
"0000000000000000000000000000000000000000000000000000000000000001";
|
||||
const EVM_BIN_RUNTIME_FIXTURE_INPUT: &str = "cde4efa9";
|
||||
const STDERR_BENCH_OK: &str = r#"EVM gas used: 560071
|
||||
execution time: 1.460881ms
|
||||
allocations: 29
|
||||
allocated bytes: 2558
|
||||
"#;
|
||||
const STDERR_BENCH_REVERT: &str = r#"EVM gas used: 69
|
||||
execution time: 10.11µs
|
||||
allocations: 43
|
||||
allocated bytes: 3711"#;
|
||||
const STDOUT_BENCH_REVERT: &str = r#" error: execution reverted"#;
|
||||
|
||||
#[test]
|
||||
fn parse_evm_output_ok() {
|
||||
serde_json::from_str::<EvmOutput>(OUTPUT_JSON_OK).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_evm_output_revert() {
|
||||
serde_json::from_str::<EvmOutput>(OUTPUT_JSON_REVERTED).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_evm_output_bench_ok() {
|
||||
let mut log = EvmLog::from("");
|
||||
log.stderr = STDERR_BENCH_OK.into();
|
||||
log.parse_gas_used_from_bench();
|
||||
assert!(log.output.run_success());
|
||||
|
||||
assert_eq!(log.execution_time().unwrap(), Duration::from_nanos(1460881));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_evm_output_bench_revert() {
|
||||
let mut log = EvmLog::from(STDOUT_BENCH_REVERT);
|
||||
log.stderr = STDERR_BENCH_REVERT.into();
|
||||
log.parse_gas_used_from_bench();
|
||||
assert!(!log.output.run_success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_state_dump() {
|
||||
serde_json::from_str::<StateDump>(STATE_DUMP).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evm_log_from_str() {
|
||||
let log = format!("{OUTPUT_JSON_OK}\n{STATE_DUMP}");
|
||||
let _ = EvmLog::from(log.as_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_genesis() {
|
||||
let log = format!("{OUTPUT_JSON_OK}\n{STATE_DUMP}");
|
||||
let log = EvmLog::from(log.as_str());
|
||||
let mut genesis: Genesis = log.state_dump.into();
|
||||
let storage = genesis
|
||||
.alloc
|
||||
.pop_first()
|
||||
.expect("should have one account in genesis")
|
||||
.1
|
||||
.storage
|
||||
.expect("genesis account should have storage");
|
||||
let storage_value = storage
|
||||
.get(&B256::ZERO)
|
||||
.expect("genesis account should have key 0 occupied");
|
||||
assert_eq!(*storage_value, B256::from(U256::from(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipper() {
|
||||
let log_runtime = Evm::default()
|
||||
.code_blob(EVM_BIN_RUNTIME_FIXTURE.as_bytes().to_vec())
|
||||
.input(Bytes::from_str(EVM_BIN_RUNTIME_FIXTURE_INPUT).unwrap())
|
||||
.run();
|
||||
assert!(log_runtime.output.run_success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prestate() {
|
||||
let log_deploy = Evm::default()
|
||||
.code_blob(EVM_BIN_FIXTURE.as_bytes().to_vec())
|
||||
.input(Bytes::from_str(EVM_BIN_FIXTURE_INPUT).unwrap())
|
||||
.deploy(true)
|
||||
.run();
|
||||
assert!(log_deploy.output.run_success());
|
||||
|
||||
let address = log_deploy.account_deployed.unwrap();
|
||||
let genesis: Genesis = log_deploy.state_dump.into();
|
||||
let log_runtime = Evm::default()
|
||||
.genesis_json(genesis)
|
||||
.receiver(address)
|
||||
.input(Bytes::from_str(EVM_BIN_RUNTIME_FIXTURE_INPUT).unwrap())
|
||||
.run();
|
||||
assert!(log_runtime.output.run_success(), "{:?}", log_runtime.output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_flipper() {
|
||||
let log_runtime = Evm::default()
|
||||
.code_blob(EVM_BIN_RUNTIME_FIXTURE.as_bytes().to_vec())
|
||||
.input(Bytes::from_str(EVM_BIN_RUNTIME_FIXTURE_INPUT).unwrap())
|
||||
.bench(true)
|
||||
.run();
|
||||
assert!(log_runtime.output.run_success());
|
||||
assert!(log_runtime.execution_time().unwrap() > Duration::from_nanos(0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
[package]
|
||||
name = "revive-integration"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
description = "revive compiler integration test cases"
|
||||
|
||||
[dependencies]
|
||||
polkavm = { workspace = true }
|
||||
@@ -12,12 +14,13 @@ alloy-sol-types = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
log = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
revive-solidity = { path = "../solidity" }
|
||||
revive-differential = { path = "../differential" }
|
||||
revive-llvm-context = { path = "../llvm-context" }
|
||||
revive-common = { path = "../common" }
|
||||
revive-solidity = { workspace = true }
|
||||
revive-differential = { workspace = true }
|
||||
revive-llvm-context = { workspace = true }
|
||||
revive-common = { workspace = true }
|
||||
revive-runner = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
sha1 = { workspace = true }
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"Baseline": 934,
|
||||
"Computation": 4360,
|
||||
"DivisionArithmetics": 39824,
|
||||
"ERC20": 52825,
|
||||
"Events": 1749,
|
||||
"FibonacciIterative": 2973,
|
||||
"Flipper": 3563,
|
||||
"SHA1": 32623
|
||||
"Baseline": 967,
|
||||
"Computation": 4022,
|
||||
"DivisionArithmetics": 31787,
|
||||
"ERC20": 44233,
|
||||
"Events": 1743,
|
||||
"FibonacciIterative": 2927,
|
||||
"Flipper": 3408,
|
||||
"SHA1": 26009
|
||||
}
|
||||
@@ -1,5 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/* runner.json
|
||||
|
||||
{
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"origin": "Alice",
|
||||
"value": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Baseline {
|
||||
|
||||
@@ -2,6 +2,31 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Bitwise"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "3fa4f245"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Bitwise {
|
||||
function opByte(uint i, uint x) public payable returns (uint ret) {
|
||||
assembly {
|
||||
|
||||
@@ -2,12 +2,49 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Block"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "8381f58a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b80777ea"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Block {
|
||||
function timestamp() public view returns (uint ret) {
|
||||
ret = block.timestamp;
|
||||
}
|
||||
|
||||
function number() public view returns (uint ret) {
|
||||
ret = block.number;
|
||||
if (block.number == 0) {
|
||||
ret = 1;
|
||||
} else {
|
||||
ret = block.number;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,19 +2,57 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Call {
|
||||
function value_transfer(address payable destination) public payable {
|
||||
destination.transfer(msg.value);
|
||||
}
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Upload": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Callee"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Caller"
|
||||
}
|
||||
},
|
||||
"value": 123
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "5a6535fc00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004cafebabe00000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Callee {
|
||||
function echo(bytes memory payload) public pure returns (bytes memory) {
|
||||
return payload;
|
||||
}
|
||||
|
||||
function call(
|
||||
address callee,
|
||||
bytes memory payload
|
||||
) public pure returns (bytes memory) {
|
||||
return Call(callee).echo(payload);
|
||||
receive() external payable {}
|
||||
}
|
||||
|
||||
contract Caller {
|
||||
constructor() payable {
|
||||
Callee callee = new Callee();
|
||||
payable(address(callee)).transfer(msg.value);
|
||||
}
|
||||
|
||||
function call(bytes memory payload) public returns (bytes memory) {
|
||||
Callee callee = new Callee();
|
||||
return callee.echo(payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,44 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "0f760610000000000000000000000000000000000000000000000000000000000000000d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"VerifyCall": {
|
||||
"success": true,
|
||||
"output": "000000000000000000000000000000000000000000000000000000000000005b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "00261b660000000000000000000000000000000000000000000000000000000000000005"
|
||||
}
|
||||
},
|
||||
{
|
||||
"VerifyCall": {
|
||||
"success": true,
|
||||
"output": "00000000000000000000000000000000000000000000000000000000000003b1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Computation {
|
||||
function triangle_number(int64 n) public pure returns (int64 sum) {
|
||||
unchecked {
|
||||
|
||||
@@ -2,6 +2,47 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Context"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "846a1ee1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "fc9c8d39"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "3af973b1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Context {
|
||||
function address_this() public view returns (address ret) {
|
||||
ret = address(this);
|
||||
@@ -10,4 +51,12 @@ contract Context {
|
||||
function caller() public view returns (address ret) {
|
||||
ret = msg.sender;
|
||||
}
|
||||
|
||||
function chain_id() public view returns (uint) {
|
||||
uint256 id;
|
||||
assembly {
|
||||
id := chainid()
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,64 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.24;
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Upload": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "CreateA"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "CreateB"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"value": 10000
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract CreateA {
|
||||
address creator;
|
||||
|
||||
constructor() payable {
|
||||
creator = msg.sender;
|
||||
}
|
||||
constructor() payable {}
|
||||
}
|
||||
|
||||
contract CreateB {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.24;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "TestSha3"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "f9fbd5540000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c68656c6c6f20776f726c64210000000000000000000000000000000000000000"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract TestSha3 {
|
||||
function test(string memory _pre) external payable returns (bytes32) {
|
||||
bytes32 hash = keccak256(bytes(_pre));
|
||||
return bytes32(uint(hash) + 1);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,32 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Upload": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "ERC20"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "ERC20Tester"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol
|
||||
interface IERC20 {
|
||||
function totalSupply() external view returns (uint);
|
||||
@@ -72,3 +98,26 @@ contract ERC20 is IERC20 {
|
||||
emit Transfer(msg.sender, address(0), amount);
|
||||
}
|
||||
}
|
||||
|
||||
contract ERC20Tester {
|
||||
constructor() {
|
||||
address BOB = address(0xffffffffffffffffffffffffffffffffffffff);
|
||||
ERC20 token = new ERC20();
|
||||
assert(token.decimals() == 18);
|
||||
|
||||
token.mint(300);
|
||||
assert(token.balanceOf(address(this)) == 300);
|
||||
token.transfer(BOB, 100);
|
||||
assert(token.balanceOf(address(this)) == 200);
|
||||
assert(token.balanceOf(BOB) == 100);
|
||||
|
||||
token.approve(address(this), 100);
|
||||
|
||||
token.transferFrom(address(this), BOB, 100);
|
||||
assert(token.balanceOf(BOB) == 200);
|
||||
assert(token.balanceOf(address(this)) == 100);
|
||||
|
||||
token.burn(100);
|
||||
assert(token.balanceOf(address(this)) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,39 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Events"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "4d43bec90000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "4d43bec9000000000000000000000000000000000000000000000000000000000000007b"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Events {
|
||||
event A() anonymous;
|
||||
event E(uint, uint indexed, uint indexed, uint indexed);
|
||||
|
||||
@@ -14,4 +14,16 @@ contract ExtCode {
|
||||
ret := codesize()
|
||||
}
|
||||
}
|
||||
|
||||
function ExtCodeHash(address who) public view returns (bytes32 ret) {
|
||||
assembly {
|
||||
ret := extcodehash(who)
|
||||
}
|
||||
}
|
||||
|
||||
function CodeHash() public view returns (bytes32 ret) {
|
||||
assembly {
|
||||
ret := extcodehash(address())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,29 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
// https://medium.com/coinmonks/fibonacci-in-solidity-8477d907e22a
|
||||
/* runner.json
|
||||
{
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "6b83dd2e0000000000000000000000000000000000000000000000000000000000000006"
|
||||
}
|
||||
},
|
||||
{
|
||||
"VerifyCall": {
|
||||
"success": true,
|
||||
"output": "0000000000000000000000000000000000000000000000000000000000000008"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract FibonacciRecursive {
|
||||
function f(uint n) internal pure returns (uint) {
|
||||
@@ -36,6 +58,7 @@ contract FibonacciIterative {
|
||||
}
|
||||
}
|
||||
|
||||
// https://medium.com/coinmonks/fibonacci-in-solidity-8477d907e22a
|
||||
contract FibonacciBinet {
|
||||
function fib3(uint n) external pure returns (uint a) {
|
||||
if (n == 0) {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Upload": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "ImmutablesTester"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Immutables"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract ImmutablesTester {
|
||||
// Read should work in the runtime code
|
||||
uint public immutable foo;
|
||||
// Read should work in the runtime code
|
||||
uint public immutable bar;
|
||||
// Read should work in the runtime code
|
||||
uint public immutable zoo;
|
||||
|
||||
// Assign and read should work in the constructor
|
||||
constructor(uint _foo) payable {
|
||||
foo = _foo;
|
||||
bar = foo + 1;
|
||||
zoo = bar + 2;
|
||||
|
||||
assert(zoo == _foo + 3);
|
||||
}
|
||||
}
|
||||
|
||||
contract Immutables {
|
||||
fallback() external {
|
||||
ImmutablesTester tester = new ImmutablesTester(127);
|
||||
|
||||
assert(tester.foo() == 127);
|
||||
assert(tester.bar() == tester.foo() + 1);
|
||||
assert(tester.zoo() == tester.bar() + 2);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,31 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "MCopy"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "0ee188b0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000030102030000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract MCopy {
|
||||
function memcpy(bytes memory payload) public pure returns (bytes memory) {
|
||||
return payload;
|
||||
|
||||
@@ -2,6 +2,40 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "MSize",
|
||||
"solc_optimizer": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "f016832c"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "f4a63aa5"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract MSize {
|
||||
uint[] public data;
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "MStore8"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad4210000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad4210000000000000000000000000000000000000000000000000000000000000001"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad4210000000000000000000000000000000000000000000000000000000000000002"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad42100000000000000000000000000000000000000000000000000000000000000ff"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad4210000000000000000000000000000000000000000000000000000000000000100"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad4210000000000000000000000000000000000000000000000000000000000000101"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad4210000000000000000000000000000000000000000000000000000000000000102"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad42100000000000000000000000000000000000000000000000000000000075bcd15"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "b09ad421ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract MStore8 {
|
||||
function mStore8(uint value) public pure returns (uint256 word) {
|
||||
assembly {
|
||||
mstore8(0x80, value)
|
||||
word := mload(0x80)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Upload": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Callee"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "ReturnDataOob"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Callee {
|
||||
function echo(bytes memory payload) public pure returns (bytes memory) {
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
|
||||
contract ReturnDataOob {
|
||||
fallback() external {
|
||||
new Callee().echo(hex"1234");
|
||||
assembly {
|
||||
let pos := mload(64)
|
||||
let size := add(returndatasize(), 1)
|
||||
returndatacopy(pos, 0, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,31 @@
|
||||
// SPDX-License-Identifier: BSD-2-Clause
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "SHA1"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "1605782b00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000200ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract SHA1 {
|
||||
function sha1(bytes memory data) public pure returns (bytes20 ret) {
|
||||
assembly {
|
||||
|
||||
@@ -2,13 +2,54 @@
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Storage"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "fabc9efaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "558b9f9bffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Storage {
|
||||
function transient(uint value) public returns (uint ret) {
|
||||
assembly {
|
||||
let slot := 123
|
||||
let slot := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
|
||||
tstore(slot, value)
|
||||
let success := call(0, 0, 0, 0, 0, 0, 0)
|
||||
ret := tload(slot)
|
||||
}
|
||||
}
|
||||
|
||||
function persistent(uint value) public returns (uint ret) {
|
||||
assembly {
|
||||
let slot := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
|
||||
sstore(slot, value)
|
||||
ret := sload(slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Upload": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "TransactionOrigin"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "TransactionTester"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "f8a8fd6d"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract TransactionTester {
|
||||
constructor() payable {
|
||||
assert(tx.origin == new TransactionOrigin().test());
|
||||
}
|
||||
|
||||
function test() public payable returns (address ret) {
|
||||
ret = tx.origin;
|
||||
}
|
||||
}
|
||||
|
||||
contract TransactionOrigin {
|
||||
function test() public payable returns (address ret) {
|
||||
assert(msg.sender != tx.origin);
|
||||
|
||||
ret = tx.origin;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Transfer"
|
||||
}
|
||||
},
|
||||
"value": 11
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "1c8d16b30000000000000000000000000303030303030303030303030303030303030303000000000000000000000000000000000000000000000000000000000000000a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "fb9e8d0500000000000000000000000003030303030303030303030303030303030303030000000000000000000000000000000000000000000000000000000000000001"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Transfer {
|
||||
constructor() payable {
|
||||
transfer_self(msg.value);
|
||||
}
|
||||
|
||||
function address_self() internal view returns (address payable) {
|
||||
return payable(address(this));
|
||||
}
|
||||
|
||||
function transfer_self(uint _amount) public payable {
|
||||
transfer_to(address_self(), _amount);
|
||||
}
|
||||
|
||||
function transfer_to(address payable _dest, uint _amount) public payable {
|
||||
_dest.transfer(_amount);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,66 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"differential": true,
|
||||
"actions": [
|
||||
{
|
||||
"Upload": {
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "ValueTester"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Instantiate": {
|
||||
"value": 1024,
|
||||
"code": {
|
||||
"Solidity": {
|
||||
"contract": "Value"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"value": 123,
|
||||
"data": "3fa4f245"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract ValueTester {
|
||||
constructor() payable {}
|
||||
|
||||
function balance_self() public view returns (uint ret) {
|
||||
ret = address(this).balance;
|
||||
}
|
||||
}
|
||||
|
||||
contract Value {
|
||||
constructor() payable {
|
||||
ValueTester tester = new ValueTester{value: msg.value}();
|
||||
|
||||
// own account
|
||||
assert(address(this).balance == 0);
|
||||
|
||||
// tester account
|
||||
assert(address(tester).balance == msg.value);
|
||||
assert(tester.balance_self() == msg.value);
|
||||
|
||||
// non-existant account
|
||||
assert(address(0xdeadbeef).balance == 0);
|
||||
}
|
||||
|
||||
function value() public payable returns (uint ret) {
|
||||
ret = msg.value;
|
||||
}
|
||||
|
||||
function balance_of(address _address) public view returns (uint ret) {
|
||||
ret = _address.balance;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,44 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8;
|
||||
|
||||
/* runner.json
|
||||
{
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"data": "0000000000000000000000000000000000000000000000000000000000000001"
|
||||
}
|
||||
},
|
||||
{
|
||||
"VerifyStorage": {
|
||||
"contract": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"key": "0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"expected": "0100000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Call": {
|
||||
"dest": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"data": "cde4efa9"
|
||||
}
|
||||
},
|
||||
{
|
||||
"VerifyStorage": {
|
||||
"contract": {
|
||||
"Instantiated": 0
|
||||
},
|
||||
"key": "0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"expected": "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
contract Flipper {
|
||||
bool coin;
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract MStore8 {
|
||||
function mStore8(uint value) public pure returns (uint256 word) {
|
||||
assembly {
|
||||
mstore8(0x80, value)
|
||||
word := mload(0x80)
|
||||
}
|
||||
}
|
||||
}
|
||||
+83
-397
@@ -1,7 +1,7 @@
|
||||
use alloy_primitives::{Address, I256, U256};
|
||||
use alloy_primitives::{Address, Bytes, I256, U256};
|
||||
use alloy_sol_types::{sol, SolCall, SolConstructor};
|
||||
|
||||
use crate::mock_runtime::{CallOutput, State};
|
||||
use revive_solidity::test_utils::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Contract {
|
||||
@@ -11,45 +11,90 @@ pub struct Contract {
|
||||
pub calldata: Vec<u8>,
|
||||
}
|
||||
|
||||
macro_rules! case {
|
||||
// Arguments:
|
||||
// 1. The file name, expect to live under "../contracts/"
|
||||
// 2. The Solidity contract name
|
||||
// 3. The derived Solidity function call name
|
||||
// 4. The method name on [Contract]
|
||||
// 5. Any parameters to the Solidity functions
|
||||
($file_name:literal, $contract_name:ident, $contract_method:ident, $method_name:ident, $( $v:ident: $t:ty ),* ) => {
|
||||
impl Contract {
|
||||
pub fn $method_name($($v: $t),*) -> Self {
|
||||
let code = include_str!(concat!("../contracts/", $file_name));
|
||||
let args = $contract_name::$contract_method::new(($($v,)*)).abi_encode();
|
||||
let name = stringify!($contract_name);
|
||||
Contract::build(args, name, code)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Arguments:
|
||||
// 1. The file name, expect to live under "../contracts/"
|
||||
// 2. The Solidity contract name
|
||||
// 3. Raw Calldata
|
||||
// 4. The method name on [Contract]
|
||||
($file_name:literal, $contract_name:literal, $calldata:expr, $method_name:ident) => {
|
||||
impl Contract {
|
||||
pub fn $method_name() -> Self {
|
||||
let code = include_str!(concat!("../contracts/", $file_name));
|
||||
Contract::build($calldata, $contract_name, code)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
case!("Create.sol", "CreateA", vec![0; 4], create_a);
|
||||
case!("Create.sol", "CreateB", vec![0; 4], create_b);
|
||||
|
||||
sol!(contract Baseline { function baseline() public payable; });
|
||||
case!("Baseline.sol", Baseline, baselineCall, baseline,);
|
||||
|
||||
sol!(contract Flipper {
|
||||
constructor (bool);
|
||||
|
||||
function flip() public;
|
||||
});
|
||||
case!("flipper.sol", Flipper, flipCall, flipper,);
|
||||
case!("flipper.sol", Flipper, constructorCall, flipper_constructor, coin: bool);
|
||||
|
||||
sol!(contract Computation {
|
||||
function odd_product(int32 n) public pure returns (int64);
|
||||
function triangle_number(int64 n) public pure returns (int64 sum);
|
||||
});
|
||||
case!("Computation.sol", Computation, odd_productCall, odd_product, n: i32);
|
||||
case!("Computation.sol", Computation, triangle_numberCall, triangle_number, n: i64);
|
||||
|
||||
sol!(
|
||||
contract FibonacciRecursive {
|
||||
function fib3(uint n) public pure returns (uint);
|
||||
}
|
||||
);
|
||||
case!("Fibonacci.sol", FibonacciRecursive, fib3Call, fib_recursive, n: U256);
|
||||
|
||||
sol!(
|
||||
contract FibonacciIterative {
|
||||
function fib3(uint n) external pure returns (uint b);
|
||||
}
|
||||
);
|
||||
case!("Fibonacci.sol", FibonacciIterative, fib3Call, fib_iterative, n: U256);
|
||||
|
||||
sol!(
|
||||
contract FibonacciBinet {
|
||||
function fib3(uint n) external pure returns (uint a);
|
||||
}
|
||||
);
|
||||
case!("Fibonacci.sol", FibonacciBinet, fib3Call, fib_binet, n: U256);
|
||||
|
||||
sol!(
|
||||
contract SHA1 {
|
||||
function sha1(bytes memory data) public pure returns (bytes20 ret);
|
||||
}
|
||||
);
|
||||
case!("SHA1.sol", SHA1, sha1Call, sha1, pre: Bytes);
|
||||
|
||||
sol!(
|
||||
interface IERC20 {
|
||||
contract ERC20 {
|
||||
function totalSupply() external view returns (uint);
|
||||
|
||||
function balanceOf(address account) external view returns (uint);
|
||||
@@ -73,6 +118,7 @@ sol!(
|
||||
event Approval(address indexed owner, address indexed spender, uint value);
|
||||
}
|
||||
);
|
||||
case!("ERC20.sol", ERC20, totalSupplyCall, erc20,);
|
||||
|
||||
sol!(
|
||||
contract Block {
|
||||
@@ -81,6 +127,8 @@ sol!(
|
||||
function number() public view returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Block.sol", Block, numberCall, block_number,);
|
||||
case!("Block.sol", Block, timestampCall, block_timestamp,);
|
||||
|
||||
sol!(
|
||||
contract Context {
|
||||
@@ -89,6 +137,8 @@ sol!(
|
||||
function caller() public pure returns (address);
|
||||
}
|
||||
);
|
||||
case!("Context.sol", Context, address_thisCall, context_address,);
|
||||
case!("Context.sol", Context, callerCall, context_caller,);
|
||||
|
||||
sol!(
|
||||
contract DivisionArithmetics {
|
||||
@@ -101,12 +151,17 @@ sol!(
|
||||
function smod(int n, int d) public pure returns (int r);
|
||||
}
|
||||
);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, divCall, division_arithmetics_div, n: U256, d: U256);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, sdivCall, division_arithmetics_sdiv, n: I256, d: I256);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, modCall, division_arithmetics_mod, n: U256, d: U256);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, smodCall, division_arithmetics_smod, n: I256, d: I256);
|
||||
|
||||
sol!(
|
||||
contract MStore8 {
|
||||
function mStore8(uint value) public pure returns (uint256 word);
|
||||
}
|
||||
);
|
||||
case!("MStore8.sol", MStore8, mStore8Call, mstore8, value: U256);
|
||||
|
||||
sol!(
|
||||
contract Events {
|
||||
@@ -116,26 +171,30 @@ sol!(
|
||||
function emitEvent(uint topics) public;
|
||||
}
|
||||
);
|
||||
|
||||
sol!(
|
||||
contract CreateB {
|
||||
fallback() external payable;
|
||||
}
|
||||
);
|
||||
case!("Events.sol", Events, emitEventCall, event, topics: U256);
|
||||
|
||||
sol!(
|
||||
contract ExtCode {
|
||||
function ExtCodeSize(address who) public view returns (uint ret);
|
||||
|
||||
function CodeSize() public pure returns (uint ret);
|
||||
|
||||
function ExtCodeHash(address who) public view returns (bytes32 ret);
|
||||
|
||||
function CodeHash() public view returns (bytes32 ret);
|
||||
}
|
||||
);
|
||||
case!("ExtCode.sol", ExtCode, ExtCodeSizeCall, ext_code_size, address: Address);
|
||||
case!("ExtCode.sol", ExtCode, CodeSizeCall, code_size,);
|
||||
case!("ExtCode.sol", ExtCode, ExtCodeHashCall, ext_code_hash, address: Address);
|
||||
case!("ExtCode.sol", ExtCode, CodeHashCall, code_hash,);
|
||||
|
||||
sol!(
|
||||
contract MCopy {
|
||||
function memcpy(bytes memory payload) public pure returns (bytes memory);
|
||||
}
|
||||
);
|
||||
case!("MCopy.sol", MCopy, memcpyCall, memcpy, payload: Bytes);
|
||||
|
||||
sol!(
|
||||
contract Call {
|
||||
@@ -149,420 +208,47 @@ sol!(
|
||||
) public payable returns (bytes memory);
|
||||
}
|
||||
);
|
||||
case!("Call.sol", Call, value_transferCall, call_value_transfer, destination: Address);
|
||||
case!("Call.sol", Call, callCall, call_call, destination: Address, payload: Bytes);
|
||||
case!("Call.sol", "Call", vec![], call_constructor);
|
||||
|
||||
sol!(
|
||||
contract Value {
|
||||
function balance_of(address _address) public view returns (uint ret);
|
||||
function balance_self() public view returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Value.sol", Value, balance_ofCall, value_balance_of, address: Address);
|
||||
case!("Value.sol", Value, balance_selfCall, value_balance_self,);
|
||||
|
||||
sol!(
|
||||
contract Bitwise {
|
||||
function opByte(uint i, uint x) public payable returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Bitwise.sol", Bitwise, opByteCall, bitwise_byte, index: U256, value: U256);
|
||||
|
||||
sol!(
|
||||
contract Storage {
|
||||
function transient(uint value) public returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Storage.sol", Storage, transientCall, storage_transient, value: U256);
|
||||
|
||||
impl Contract {
|
||||
/// Execute the contract.
|
||||
///
|
||||
/// Useful helper if the contract state can be ignored,
|
||||
/// as it spares the deploy transaciton.
|
||||
///
|
||||
/// - Inserts an account with given `code` into a new state.
|
||||
/// - Callee and caller account will be `Transaction::default_address()`.
|
||||
/// - Sets the calldata.
|
||||
/// - Doesn't execute the constructor or deploy code.
|
||||
/// - Calls the "call" export on a default backend config.
|
||||
pub fn execute(&self) -> (State, CallOutput) {
|
||||
State::default()
|
||||
.transaction()
|
||||
.with_default_account(&self.pvm_runtime)
|
||||
.calldata(self.calldata.clone())
|
||||
.call()
|
||||
}
|
||||
|
||||
pub fn baseline() -> Self {
|
||||
let code = include_str!("../contracts/Baseline.sol");
|
||||
let name = "Baseline";
|
||||
|
||||
fn build(calldata: Vec<u8>, name: &'static str, code: &str) -> Self {
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Baseline::baselineCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn odd_product(n: i32) -> Self {
|
||||
let code = include_str!("../contracts/Computation.sol");
|
||||
let name = "Computation";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Computation::odd_productCall::new((n,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn triangle_number(n: i64) -> Self {
|
||||
let code = include_str!("../contracts/Computation.sol");
|
||||
let name = "Computation";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Computation::triangle_numberCall::new((n,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fib_recursive(n: u32) -> Self {
|
||||
let code = include_str!("../contracts/Fibonacci.sol");
|
||||
let name = "FibonacciRecursive";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: FibonacciRecursive::fib3Call::new((U256::from(n),)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fib_iterative(n: u32) -> Self {
|
||||
let code = include_str!("../contracts/Fibonacci.sol");
|
||||
let name = "FibonacciIterative";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: FibonacciIterative::fib3Call::new((U256::from(n),)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fib_binet(n: u32) -> Self {
|
||||
let code = include_str!("../contracts/Fibonacci.sol");
|
||||
let name = "FibonacciBinet";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: FibonacciBinet::fib3Call::new((U256::from(n),)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sha1(pre: Vec<u8>) -> Self {
|
||||
let code = include_str!("../contracts/SHA1.sol");
|
||||
let name = "SHA1";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: SHA1::sha1Call::new((pre,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn flipper() -> Self {
|
||||
let code = include_str!("../contracts/flipper.sol");
|
||||
let name = "Flipper";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Flipper::flipCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn flipper_constructor(coin: bool) -> Self {
|
||||
let code = include_str!("../contracts/flipper.sol");
|
||||
let name = "Flipper";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Flipper::constructorCall::new((coin,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn erc20() -> Self {
|
||||
let code = include_str!("../contracts/ERC20.sol");
|
||||
let name = "ERC20";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: IERC20::totalSupplyCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn block_number() -> Self {
|
||||
let code = include_str!("../contracts/Block.sol");
|
||||
let name = "Block";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Block::numberCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn block_timestamp() -> Self {
|
||||
let code = include_str!("../contracts/Block.sol");
|
||||
let name = "Block";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Block::timestampCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn context_address() -> Self {
|
||||
let code = include_str!("../contracts/Context.sol");
|
||||
let name = "Context";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Context::address_thisCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn context_caller() -> Self {
|
||||
let code = include_str!("../contracts/Context.sol");
|
||||
let name = "Context";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Context::callerCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn division_arithmetics_div(n: U256, d: U256) -> Self {
|
||||
let code = include_str!("../contracts/DivisionArithmetics.sol");
|
||||
let name = "DivisionArithmetics";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: DivisionArithmetics::divCall::new((n, d)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn division_arithmetics_sdiv(n: I256, d: I256) -> Self {
|
||||
let code = include_str!("../contracts/DivisionArithmetics.sol");
|
||||
let name = "DivisionArithmetics";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: DivisionArithmetics::sdivCall::new((n, d)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn division_arithmetics_mod(n: U256, d: U256) -> Self {
|
||||
let code = include_str!("../contracts/DivisionArithmetics.sol");
|
||||
let name = "DivisionArithmetics";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: DivisionArithmetics::modCall::new((n, d)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn division_arithmetics_smod(n: I256, d: I256) -> Self {
|
||||
let code = include_str!("../contracts/DivisionArithmetics.sol");
|
||||
let name = "DivisionArithmetics";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: DivisionArithmetics::smodCall::new((n, d)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mstore8(value: U256) -> Self {
|
||||
let code = include_str!("../contracts/mStore8.sol");
|
||||
let name = "MStore8";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: MStore8::mStore8Call::new((value,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn event(topics: U256) -> Self {
|
||||
let code = include_str!("../contracts/Events.sol");
|
||||
let name = "Events";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Events::emitEventCall::new((topics,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_a() -> Self {
|
||||
let code = include_str!("../contracts/Create.sol");
|
||||
let name = "CreateA";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: vec![0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_b() -> Self {
|
||||
let code = include_str!("../contracts/Create.sol");
|
||||
let name = "CreateB";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: vec![0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ext_code_size(address: Address) -> Self {
|
||||
let code = include_str!("../contracts/ExtCode.sol");
|
||||
let name = "ExtCode";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: ExtCode::ExtCodeSizeCall::new((address,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code_size() -> Self {
|
||||
let code = include_str!("../contracts/ExtCode.sol");
|
||||
let name = "ExtCode";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: ExtCode::CodeSizeCall::new(()).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn memcpy(payload: Vec<u8>) -> Self {
|
||||
let code = include_str!("../contracts/MCopy.sol");
|
||||
let name = "MCopy";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: MCopy::memcpyCall::new((payload,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn call_value_transfer(destination: Address) -> Self {
|
||||
let code = include_str!("../contracts/Call.sol");
|
||||
let name = "Call";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Call::value_transferCall::new((destination,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn call_call(callee: Address, payload: Vec<u8>) -> Self {
|
||||
let code = include_str!("../contracts/Call.sol");
|
||||
let name = "Call";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Call::callCall::new((callee, payload)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn call_constructor() -> Self {
|
||||
let code = include_str!("../contracts/Call.sol");
|
||||
let name = "Call";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_balance_of(address: Address) -> Self {
|
||||
let code = include_str!("../contracts/Value.sol");
|
||||
let name = "Value";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Value::balance_ofCall::new((address,)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bitwise_byte(index: U256, value: U256) -> Self {
|
||||
let code = include_str!("../contracts/Bitwise.sol");
|
||||
let name = "Bitwise";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Bitwise::opByteCall::new((index, value)).abi_encode(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn storage_transient(value: U256) -> Self {
|
||||
let code = include_str!("../contracts/Storage.sol");
|
||||
let name = "Storage";
|
||||
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: crate::compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: crate::compile_blob(name, code),
|
||||
calldata: Storage::transientCall::new((value,)).abi_encode(),
|
||||
evm_runtime: compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: compile_blob(name, code),
|
||||
calldata,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloy_primitives::U256;
|
||||
use alloy_primitives::{Bytes, U256};
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
use serde::{de::Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, fs::File};
|
||||
@@ -605,9 +291,9 @@ mod tests {
|
||||
Contract::baseline as fn() -> Contract,
|
||||
Contract::flipper as fn() -> Contract,
|
||||
(|| Contract::odd_product(0)) as fn() -> Contract,
|
||||
(|| Contract::fib_iterative(0)) as fn() -> Contract,
|
||||
(|| Contract::fib_iterative(U256::ZERO)) as fn() -> Contract,
|
||||
Contract::erc20 as fn() -> Contract,
|
||||
(|| Contract::sha1(Vec::new())) as fn() -> Contract,
|
||||
(|| Contract::sha1(Bytes::new())) as fn() -> Contract,
|
||||
(|| Contract::division_arithmetics_div(U256::ZERO, U256::ZERO)) as fn() -> Contract,
|
||||
(|| Contract::event(U256::ZERO)) as fn() -> Contract,
|
||||
]
|
||||
|
||||
@@ -1,150 +1,4 @@
|
||||
use alloy_primitives::{Address, U256};
|
||||
use cases::Contract;
|
||||
use mock_runtime::{CallOutput, State};
|
||||
|
||||
use crate::mock_runtime::{Event, ReturnFlags};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use std::{collections::HashMap, sync::Mutex};
|
||||
|
||||
pub mod cases;
|
||||
pub mod mock_runtime;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub(crate) static PVM_BLOB_CACHE: Lazy<Mutex<HashMap<CompiledBlobId, Vec<u8>>>> =
|
||||
Lazy::new(Default::default);
|
||||
pub(crate) static EVM_BLOB_CACHE: Lazy<Mutex<HashMap<CompiledBlobId, Vec<u8>>>> =
|
||||
Lazy::new(Default::default);
|
||||
|
||||
#[derive(Hash, PartialEq, Eq)]
|
||||
struct CompiledBlobId {
|
||||
contract_name: String,
|
||||
solc_optimizer_enabled: bool,
|
||||
pipeline: revive_solidity::SolcPipeline,
|
||||
}
|
||||
|
||||
/// Compile the blob of `contract_name` found in given `source_code`.
|
||||
/// The `solc` optimizer will be enabled
|
||||
pub fn compile_blob(contract_name: &str, source_code: &str) -> Vec<u8> {
|
||||
compile_blob_with_options(
|
||||
contract_name,
|
||||
source_code,
|
||||
true,
|
||||
revive_solidity::SolcPipeline::Yul,
|
||||
)
|
||||
}
|
||||
|
||||
/// Compile the EVM bin-runtime of `contract_name` found in given `source_code`.
|
||||
/// The `solc` optimizer will be enabled
|
||||
pub fn compile_evm_bin_runtime(contract_name: &str, source_code: &str) -> Vec<u8> {
|
||||
let pipeline = revive_solidity::SolcPipeline::Yul;
|
||||
let solc_optimizer_enabled = true;
|
||||
let id = CompiledBlobId {
|
||||
contract_name: contract_name.to_owned(),
|
||||
pipeline,
|
||||
solc_optimizer_enabled,
|
||||
};
|
||||
|
||||
if let Some(blob) = EVM_BLOB_CACHE.lock().unwrap().get(&id) {
|
||||
return blob.clone();
|
||||
}
|
||||
|
||||
let file_name = "contract.sol";
|
||||
let contracts = revive_solidity::test_utils::build_solidity_with_options_evm(
|
||||
[(file_name.into(), source_code.into())].into(),
|
||||
Default::default(),
|
||||
None,
|
||||
pipeline,
|
||||
solc_optimizer_enabled,
|
||||
)
|
||||
.expect("source should compile");
|
||||
let bin_runtime = &contracts
|
||||
.get(contract_name)
|
||||
.unwrap_or_else(|| panic!("contract '{}' didn't produce bin-runtime", contract_name))
|
||||
.object;
|
||||
|
||||
let blob = hex::decode(bin_runtime).expect("bin-runtime shold be hex encoded");
|
||||
|
||||
EVM_BLOB_CACHE.lock().unwrap().insert(id, blob.clone());
|
||||
|
||||
blob
|
||||
}
|
||||
|
||||
/// Compile the blob of `contract_name` found in given `source_code`.
|
||||
pub fn compile_blob_with_options(
|
||||
contract_name: &str,
|
||||
source_code: &str,
|
||||
solc_optimizer_enabled: bool,
|
||||
pipeline: revive_solidity::SolcPipeline,
|
||||
) -> Vec<u8> {
|
||||
let id = CompiledBlobId {
|
||||
contract_name: contract_name.to_owned(),
|
||||
solc_optimizer_enabled,
|
||||
pipeline,
|
||||
};
|
||||
|
||||
if let Some(blob) = PVM_BLOB_CACHE.lock().unwrap().get(&id) {
|
||||
return blob.clone();
|
||||
}
|
||||
|
||||
let file_name = "contract.sol";
|
||||
let contracts = revive_solidity::test_utils::build_solidity_with_options(
|
||||
[(file_name.into(), source_code.into())].into(),
|
||||
Default::default(),
|
||||
None,
|
||||
pipeline,
|
||||
revive_llvm_context::OptimizerSettings::cycles(),
|
||||
solc_optimizer_enabled,
|
||||
)
|
||||
.expect("source should compile")
|
||||
.contracts
|
||||
.expect("source should contain at least one contract");
|
||||
|
||||
let bytecode = contracts[file_name][contract_name]
|
||||
.evm
|
||||
.as_ref()
|
||||
.expect("source should produce EVM output")
|
||||
.bytecode
|
||||
.as_ref()
|
||||
.expect("source should produce assembly text")
|
||||
.object
|
||||
.as_str();
|
||||
let blob = hex::decode(bytecode).expect("hex encoding should always be valid");
|
||||
|
||||
PVM_BLOB_CACHE.lock().unwrap().insert(id, blob.clone());
|
||||
|
||||
blob
|
||||
}
|
||||
|
||||
pub fn assert_success(contract: &Contract, differential: bool) -> (State, CallOutput) {
|
||||
let (state, output) = contract.execute();
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
if differential {
|
||||
let evm =
|
||||
revive_differential::prepare(contract.evm_runtime.clone(), contract.calldata.clone());
|
||||
let (evm_output, evm_log) = revive_differential::execute(evm);
|
||||
|
||||
assert_eq!(output.data.clone(), evm_output);
|
||||
assert_eq!(output.events.len(), evm_log.len());
|
||||
assert_eq!(
|
||||
output.events,
|
||||
evm_log
|
||||
.iter()
|
||||
.map(|log| Event {
|
||||
address: Address::from_slice(log.address.as_bytes()),
|
||||
data: log.data.clone(),
|
||||
topics: log
|
||||
.topics
|
||||
.iter()
|
||||
.map(|topic| U256::from_be_bytes(topic.0))
|
||||
.collect(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
(state, output)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+375
-553
@@ -1,464 +1,437 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use alloy_primitives::{keccak256, Address, FixedBytes, B256, I256, U256};
|
||||
use alloy_sol_types::{sol, SolCall, SolValue};
|
||||
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
|
||||
use sha1::Digest;
|
||||
use alloy_primitives::*;
|
||||
use revive_runner::*;
|
||||
use SpecsAction::*;
|
||||
|
||||
use crate::{
|
||||
assert_success,
|
||||
cases::Contract,
|
||||
mock_runtime::{self, ReturnFlags, State, Transaction},
|
||||
};
|
||||
use crate::cases::Contract;
|
||||
|
||||
#[test]
|
||||
fn fibonacci() {
|
||||
let parameter = 6;
|
||||
/// Parameters:
|
||||
/// - The function name of the test
|
||||
/// - The contract name to fill in empty code based on the file path
|
||||
/// - The contract source file
|
||||
macro_rules! test_spec {
|
||||
($test_name:ident, $contract_name:literal, $source_file:literal) => {
|
||||
#[test]
|
||||
fn $test_name() {
|
||||
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("should always exist");
|
||||
let path = format!("{manifest_dir}/../integration/contracts/{}", $source_file);
|
||||
Specs::from_comment($contract_name, &path).remove(0).run();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
for contract in [
|
||||
Contract::fib_recursive(parameter),
|
||||
Contract::fib_iterative(parameter),
|
||||
Contract::fib_binet(parameter),
|
||||
] {
|
||||
let (_, output) = assert_success(&contract, true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::from(8);
|
||||
assert_eq!(received, expected);
|
||||
test_spec!(baseline, "Baseline", "Baseline.sol");
|
||||
test_spec!(flipper, "Flipper", "flipper.sol");
|
||||
test_spec!(fibonacci_recursive, "FibonacciRecursive", "Fibonacci.sol");
|
||||
test_spec!(fibonacci_iterative, "FibonacciIterative", "Fibonacci.sol");
|
||||
test_spec!(fibonacci_binet, "FibonacciBinet", "Fibonacci.sol");
|
||||
test_spec!(hash_keccak_256, "TestSha3", "Crypto.sol");
|
||||
test_spec!(erc20, "ERC20", "ERC20.sol");
|
||||
test_spec!(computation, "Computation", "Computation.sol");
|
||||
test_spec!(msize, "MSize", "MSize.sol");
|
||||
test_spec!(sha1, "SHA1", "SHA1.sol");
|
||||
test_spec!(block, "Block", "Block.sol");
|
||||
test_spec!(mcopy, "MCopy", "MCopy.sol");
|
||||
test_spec!(events, "Events", "Events.sol");
|
||||
test_spec!(storage, "Storage", "Storage.sol");
|
||||
test_spec!(mstore8, "MStore8", "MStore8.sol");
|
||||
test_spec!(address, "Context", "Context.sol");
|
||||
test_spec!(balance, "Value", "Value.sol");
|
||||
test_spec!(create, "CreateB", "Create.sol");
|
||||
test_spec!(call, "Caller", "Call.sol");
|
||||
test_spec!(transfer, "Transfer", "Transfer.sol");
|
||||
test_spec!(return_data_oob, "ReturnDataOob", "ReturnDataOob.sol");
|
||||
test_spec!(immutables, "Immutables", "Immutables.sol");
|
||||
test_spec!(transaction, "Transaction", "Transaction.sol");
|
||||
|
||||
fn instantiate(path: &str, contract: &str) -> Vec<SpecsAction> {
|
||||
vec![Instantiate {
|
||||
origin: TestAddress::Alice,
|
||||
value: 0,
|
||||
gas_limit: Some(GAS_LIMIT),
|
||||
storage_deposit_limit: None,
|
||||
code: Code::Solidity {
|
||||
path: Some(path.into()),
|
||||
contract: contract.to_string(),
|
||||
solc_optimizer: None,
|
||||
pipeline: None,
|
||||
},
|
||||
data: vec![],
|
||||
salt: OptionalHex::default(),
|
||||
}]
|
||||
}
|
||||
|
||||
fn run_differential(actions: Vec<SpecsAction>) {
|
||||
Specs {
|
||||
differential: true,
|
||||
actions,
|
||||
..Default::default()
|
||||
}
|
||||
.run();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipper() {
|
||||
let (state, address) = State::new_deployed(Contract::flipper_constructor(true));
|
||||
fn bitwise_byte() {
|
||||
let mut actions = instantiate("contracts/Bitwise.sol", "Bitwise");
|
||||
|
||||
let contract = Contract::flipper();
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.calldata(contract.calldata.clone())
|
||||
.callee(address)
|
||||
.call();
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
state.assert_storage_key(address, U256::ZERO, U256::ZERO);
|
||||
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.calldata(contract.calldata)
|
||||
.callee(address)
|
||||
.call();
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
state.assert_storage_key(address, U256::ZERO, U256::from(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_keccak_256() {
|
||||
sol!(
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
contract TestSha3 {
|
||||
function test(string memory _pre) external payable returns (bytes32);
|
||||
}
|
||||
);
|
||||
let source = r#"contract TestSha3 {
|
||||
function test(string memory _pre) external payable returns (bytes32 hash) {
|
||||
hash = keccak256(bytes(_pre));
|
||||
}
|
||||
}"#;
|
||||
let code = crate::compile_blob("TestSha3", source);
|
||||
|
||||
let param = "hello";
|
||||
let input = TestSha3::testCall::new((param.to_string(),)).abi_encode();
|
||||
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&code)
|
||||
.calldata(input)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
let expected = keccak256(param.as_bytes());
|
||||
let received = FixedBytes::<32>::from_slice(&output.data);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erc20() {
|
||||
let _ = crate::compile_blob("ERC20", include_str!("../contracts/ERC20.sol"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangle_number() {
|
||||
let (_, output) = assert_success(&Contract::triangle_number(13), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::try_from(91).unwrap();
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_product() {
|
||||
let (_, output) = assert_success(&Contract::odd_product(5), true);
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = I256::try_from(945i64).unwrap();
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msize_plain() {
|
||||
sol!(
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
contract MSize {
|
||||
function mSize() public pure returns (uint);
|
||||
}
|
||||
);
|
||||
let code = crate::compile_blob_with_options(
|
||||
"MSize",
|
||||
include_str!("../contracts/MSize.sol"),
|
||||
false,
|
||||
revive_solidity::SolcPipeline::EVMLA,
|
||||
);
|
||||
|
||||
let input = MSize::mSizeCall::new(()).abi_encode();
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.calldata(input)
|
||||
.with_default_account(&code)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
// Solidity always stores the "free memory pointer" (32 byte int) at offset 64.
|
||||
let expected = U256::try_from(64 + 32).unwrap();
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transferred_value() {
|
||||
sol!(
|
||||
contract Value {
|
||||
function value() public payable returns (uint);
|
||||
}
|
||||
);
|
||||
let code = crate::compile_blob("Value", include_str!("../contracts/Value.sol"));
|
||||
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.calldata(Value::valueCall::SELECTOR.to_vec())
|
||||
.callvalue(U256::from(123))
|
||||
.with_default_account(&code)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
let expected = I256::try_from(123).unwrap();
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msize_non_word_sized_access() {
|
||||
sol!(
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
contract MSize {
|
||||
function mStore100() public pure returns (uint);
|
||||
}
|
||||
);
|
||||
let code = crate::compile_blob_with_options(
|
||||
"MSize",
|
||||
include_str!("../contracts/MSize.sol"),
|
||||
false,
|
||||
revive_solidity::SolcPipeline::Yul,
|
||||
);
|
||||
|
||||
let input = MSize::mStore100Call::new(()).abi_encode();
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&code)
|
||||
.calldata(input)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
// https://docs.zksync.io/build/developer-reference/differences-with-ethereum.html#mstore-mload
|
||||
// "Unlike EVM, where the memory growth is in words, on zkEVM the memory growth is counted in bytes."
|
||||
// "For example, if you write mstore(100, 0) the msize on zkEVM will be 132, but on the EVM it will be 160."
|
||||
let expected = U256::try_from(132).unwrap();
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mstore8() {
|
||||
for (received, expected) in [
|
||||
(U256::MIN, U256::MIN),
|
||||
(
|
||||
U256::from(1),
|
||||
U256::from_str_radix(
|
||||
"452312848583266388373324160190187140051835877600158453279131187530910662656",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(2),
|
||||
U256::from_str_radix(
|
||||
"904625697166532776746648320380374280103671755200316906558262375061821325312",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(255),
|
||||
U256::from_str_radix(
|
||||
"115339776388732929035197660848497720713218148788040405586178452820382218977280",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(U256::from(256), U256::from(0)),
|
||||
(
|
||||
U256::from(257),
|
||||
U256::from_str_radix(
|
||||
"452312848583266388373324160190187140051835877600158453279131187530910662656",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(258),
|
||||
U256::from_str_radix(
|
||||
"904625697166532776746648320380374280103671755200316906558262375061821325312",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(123456789),
|
||||
U256::from_str_radix(
|
||||
"9498569820248594155839807363993929941088553429603327518861754938149123915776",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::MAX,
|
||||
U256::from_str_radix(
|
||||
"115339776388732929035197660848497720713218148788040405586178452820382218977280",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(parameter, expected)| {
|
||||
let (_, output) = assert_success(&Contract::mstore8(*parameter), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *expected)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
let de_bruijn_sequence =
|
||||
hex::decode("4060503824160d0784426150b864361d0f88c4a27148ac5a2f198d46e391d8f4").unwrap();
|
||||
let value = U256::from_be_bytes::<32>(de_bruijn_sequence.clone().try_into().unwrap());
|
||||
for input in de_bruijn_sequence
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, _)| Contract::bitwise_byte(U256::from(index), value).calldata)
|
||||
.chain([
|
||||
Contract::bitwise_byte(U256::ZERO, U256::ZERO).calldata,
|
||||
Contract::bitwise_byte(U256::ZERO, U256::MAX).calldata,
|
||||
Contract::bitwise_byte(U256::MAX, U256::ZERO).calldata,
|
||||
Contract::bitwise_byte(U256::from_str("18446744073709551619").unwrap(), U256::MAX)
|
||||
.calldata,
|
||||
])
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: input,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha1() {
|
||||
let pre = vec![0xffu8; 512];
|
||||
let mut hasher = sha1::Sha1::new();
|
||||
hasher.update(&pre);
|
||||
let hash = hasher.finalize();
|
||||
|
||||
let (_, output) = assert_success(&Contract::sha1(pre), true);
|
||||
let expected = FixedBytes::<20>::from_slice(&hash[..]);
|
||||
let received = FixedBytes::<20>::from_slice(&output.data[..20]);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_number() {
|
||||
let (_, output) = assert_success(&Contract::block_number(), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::from(mock_runtime::State::BLOCK_NUMBER);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_timestamp() {
|
||||
let (_, output) = assert_success(&Contract::block_timestamp(), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::from(mock_runtime::State::BLOCK_TIMESTAMP);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address() {
|
||||
let contract = Contract::context_address();
|
||||
let (_, output) = assert_success(&contract, true);
|
||||
let received = Address::from_slice(&output.data[12..]);
|
||||
let expected = Transaction::default_address();
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caller() {
|
||||
let (_, output) = assert_success(&Contract::context_caller(), true);
|
||||
let received = Address::from_slice(&output.data[12..]);
|
||||
let expected = Transaction::default_address();
|
||||
assert_eq!(received, expected);
|
||||
run_differential(actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_division() {
|
||||
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||
|
||||
let one = U256::from(1);
|
||||
let two = U256::from(2);
|
||||
let five = U256::from(5);
|
||||
for (received, expected) in [
|
||||
(five, five, one),
|
||||
(five, one, five),
|
||||
(U256::ZERO, U256::MAX, U256::ZERO),
|
||||
(five, two, two),
|
||||
(one, U256::ZERO, U256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_div(*n, *d), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected)
|
||||
for (n, d) in [
|
||||
(five, five),
|
||||
(five, one),
|
||||
(U256::ZERO, U256::MAX),
|
||||
(five, two),
|
||||
(one, U256::ZERO),
|
||||
] {
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::division_arithmetics_div(n, d).calldata,
|
||||
})
|
||||
}
|
||||
|
||||
run_differential(actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_division() {
|
||||
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||
|
||||
let one = I256::try_from(1).unwrap();
|
||||
let two = I256::try_from(2).unwrap();
|
||||
let minus_two = I256::try_from(-2).unwrap();
|
||||
let five = I256::try_from(5).unwrap();
|
||||
let minus_five = I256::try_from(-5).unwrap();
|
||||
for (received, expected) in [
|
||||
(five, five, one),
|
||||
(five, one, five),
|
||||
(I256::ZERO, I256::MAX, I256::ZERO),
|
||||
(I256::ZERO, I256::MINUS_ONE, I256::ZERO),
|
||||
(five, two, two),
|
||||
(five, I256::MINUS_ONE, minus_five),
|
||||
(I256::MINUS_ONE, minus_two, I256::ZERO),
|
||||
(minus_five, minus_five, one),
|
||||
(minus_five, two, minus_two),
|
||||
(I256::MINUS_ONE, I256::MIN, I256::ZERO),
|
||||
(one, I256::ZERO, I256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_sdiv(*n, *d), true);
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
for (n, d) in [
|
||||
(five, five),
|
||||
(five, one),
|
||||
(I256::ZERO, I256::MAX),
|
||||
(I256::ZERO, I256::MINUS_ONE),
|
||||
(five, two),
|
||||
(five, I256::MINUS_ONE),
|
||||
(I256::MINUS_ONE, minus_two),
|
||||
(minus_five, minus_five),
|
||||
(minus_five, two),
|
||||
(I256::MINUS_ONE, I256::MIN),
|
||||
(one, I256::ZERO),
|
||||
] {
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::division_arithmetics_sdiv(n, d).calldata,
|
||||
})
|
||||
}
|
||||
|
||||
run_differential(actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_remainder() {
|
||||
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||
|
||||
let one = U256::from(1);
|
||||
let two = U256::from(2);
|
||||
let five = U256::from(5);
|
||||
for (received, expected) in [
|
||||
(five, five, U256::ZERO),
|
||||
(five, one, U256::ZERO),
|
||||
(U256::ZERO, U256::MAX, U256::ZERO),
|
||||
(U256::MAX, U256::MAX, U256::ZERO),
|
||||
(five, two, one),
|
||||
(two, five, two),
|
||||
(U256::MAX, U256::ZERO, U256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_mod(*n, *d), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
for (n, d) in [
|
||||
(five, five),
|
||||
(five, one),
|
||||
(U256::ZERO, U256::MAX),
|
||||
(U256::MAX, U256::MAX),
|
||||
(five, two),
|
||||
(two, five),
|
||||
(U256::MAX, U256::ZERO),
|
||||
] {
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::division_arithmetics_mod(n, d).calldata,
|
||||
})
|
||||
}
|
||||
|
||||
run_differential(actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_remainder() {
|
||||
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||
|
||||
let one = I256::try_from(1).unwrap();
|
||||
let two = I256::try_from(2).unwrap();
|
||||
let minus_two = I256::try_from(-2).unwrap();
|
||||
let five = I256::try_from(5).unwrap();
|
||||
let minus_five = I256::try_from(-5).unwrap();
|
||||
for (received, expected) in [
|
||||
(five, five, I256::ZERO),
|
||||
(five, one, I256::ZERO),
|
||||
(I256::ZERO, I256::MAX, I256::ZERO),
|
||||
(I256::MAX, I256::MAX, I256::ZERO),
|
||||
(five, two, one),
|
||||
(two, five, two),
|
||||
(five, minus_five, I256::ZERO),
|
||||
(five, I256::MINUS_ONE, I256::ZERO),
|
||||
(five, minus_two, one),
|
||||
(minus_five, two, I256::MINUS_ONE),
|
||||
(minus_two, five, minus_two),
|
||||
(minus_five, minus_five, I256::ZERO),
|
||||
(minus_five, I256::MINUS_ONE, I256::ZERO),
|
||||
(minus_five, minus_two, I256::MINUS_ONE),
|
||||
(minus_two, minus_five, minus_two),
|
||||
(I256::MIN, I256::MINUS_ONE, I256::ZERO),
|
||||
(I256::ZERO, I256::ZERO, I256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_smod(*n, *d), true);
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
for (n, d) in [
|
||||
(five, five),
|
||||
(five, one),
|
||||
(I256::ZERO, I256::MAX),
|
||||
(I256::MAX, I256::MAX),
|
||||
(five, two),
|
||||
(two, five),
|
||||
(five, minus_five),
|
||||
(five, I256::MINUS_ONE),
|
||||
(five, minus_two),
|
||||
(minus_five, two),
|
||||
(minus_two, five),
|
||||
(minus_five, minus_five),
|
||||
(minus_five, I256::MINUS_ONE),
|
||||
(minus_five, minus_two),
|
||||
(minus_two, minus_five),
|
||||
(I256::MIN, I256::MINUS_ONE),
|
||||
(I256::ZERO, I256::ZERO),
|
||||
] {
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::division_arithmetics_smod(n, d).calldata,
|
||||
})
|
||||
}
|
||||
|
||||
run_differential(actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn events() {
|
||||
assert_success(&Contract::event(U256::ZERO), true);
|
||||
assert_success(&Contract::event(U256::from(123)), true);
|
||||
fn ext_code_hash() {
|
||||
let mut actions = instantiate("contracts/ExtCode.sol", "ExtCode");
|
||||
|
||||
// First do contract instantiation to figure out address and code hash
|
||||
let results = Specs {
|
||||
actions: actions.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
.run();
|
||||
let (addr, code_hash) = match results.first().cloned() {
|
||||
Some(CallResult::Instantiate {
|
||||
result, code_hash, ..
|
||||
}) => (result.result.unwrap().addr, code_hash),
|
||||
_ => panic!("instantiate contract failed"),
|
||||
};
|
||||
|
||||
// code hash of itself
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::code_hash().calldata,
|
||||
});
|
||||
actions.push(VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from(code_hash.as_bytes().to_vec()),
|
||||
gas_consumed: None,
|
||||
}));
|
||||
|
||||
// code hash for a given contract address
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::ext_code_hash(Address::from(addr.to_fixed_bytes())).calldata,
|
||||
});
|
||||
actions.push(VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from(code_hash.as_bytes().to_vec()),
|
||||
gas_consumed: None,
|
||||
}));
|
||||
|
||||
// EOA returns fixed hash
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::ext_code_hash(Address::from(CHARLIE.to_fixed_bytes())).calldata,
|
||||
});
|
||||
actions.push(VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from(
|
||||
hex!("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").to_vec(),
|
||||
),
|
||||
gas_consumed: None,
|
||||
}));
|
||||
|
||||
// non-existing account
|
||||
actions.push(Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::ext_code_hash(Address::from([8u8; 20])).calldata,
|
||||
});
|
||||
actions.push(VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from([0u8; 32].to_vec()),
|
||||
gas_consumed: None,
|
||||
}));
|
||||
|
||||
Specs {
|
||||
actions,
|
||||
..Default::default()
|
||||
}
|
||||
.run();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create2() {
|
||||
let mut state = State::default();
|
||||
let contract_a = Contract::create_a();
|
||||
state.upload_code(&contract_a.pvm_runtime);
|
||||
fn ext_code_size() {
|
||||
let alice = Address::from(ALICE.0);
|
||||
let own_address = alice.create(0);
|
||||
let baseline_address = alice.create2([0u8; 32], keccak256(Contract::baseline().pvm_runtime));
|
||||
|
||||
let contract = Contract::create_b();
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata)
|
||||
.call();
|
||||
let own_code_size = U256::from(
|
||||
Contract::ext_code_size(Default::default())
|
||||
.pvm_runtime
|
||||
.len(),
|
||||
);
|
||||
let baseline_code_size = U256::from(Contract::baseline().pvm_runtime.len());
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
assert_eq!(state.accounts().len(), 2);
|
||||
|
||||
for address in state.accounts().keys() {
|
||||
if *address != Transaction::default_address() {
|
||||
let derived_address = Transaction::default_address().create2(
|
||||
B256::from(U256::from(1)),
|
||||
keccak256(&contract_a.pvm_runtime).0,
|
||||
);
|
||||
assert_eq!(*address, derived_address);
|
||||
}
|
||||
Specs {
|
||||
actions: vec![
|
||||
// Instantiate the test contract
|
||||
instantiate("contracts/ExtCode.sol", "ExtCode").remove(0),
|
||||
// Instantiate the baseline contract
|
||||
Instantiate {
|
||||
origin: TestAddress::Alice,
|
||||
value: 0,
|
||||
gas_limit: Some(GAS_LIMIT),
|
||||
storage_deposit_limit: None,
|
||||
code: Code::Solidity {
|
||||
path: Some("contracts/Baseline.sol".into()),
|
||||
contract: "Baseline".to_string(),
|
||||
solc_optimizer: None,
|
||||
pipeline: None,
|
||||
},
|
||||
data: vec![],
|
||||
salt: OptionalHex::from([0; 32]),
|
||||
},
|
||||
// Alice is not a contract and returns a code size of 0
|
||||
Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::ext_code_size(alice).calldata,
|
||||
},
|
||||
VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from([0u8; 32].to_vec()),
|
||||
gas_consumed: None,
|
||||
}),
|
||||
// Unknown address returns a code size of 0
|
||||
Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::ext_code_size(Address::from([0xff; 20])).calldata,
|
||||
},
|
||||
VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from([0u8; 32].to_vec()),
|
||||
gas_consumed: None,
|
||||
}),
|
||||
// Own address via extcodesize returns own code size
|
||||
Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::ext_code_size(own_address).calldata,
|
||||
},
|
||||
VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from(own_code_size.to_be_bytes::<32>().to_vec()),
|
||||
gas_consumed: None,
|
||||
}),
|
||||
// Own address via codesize returns own code size
|
||||
Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::code_size().calldata,
|
||||
},
|
||||
VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from(own_code_size.to_be_bytes::<32>().to_vec()),
|
||||
gas_consumed: None,
|
||||
}),
|
||||
// Baseline address returns the baseline code size
|
||||
Call {
|
||||
origin: TestAddress::Alice,
|
||||
dest: TestAddress::Instantiated(0),
|
||||
value: 0,
|
||||
gas_limit: None,
|
||||
storage_deposit_limit: None,
|
||||
data: Contract::ext_code_size(baseline_address).calldata,
|
||||
},
|
||||
VerifyCall(VerifyCallExpectation {
|
||||
success: true,
|
||||
output: OptionalHex::from(baseline_code_size.to_be_bytes::<32>().to_vec()),
|
||||
gas_consumed: None,
|
||||
}),
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
.run();
|
||||
}
|
||||
|
||||
/*
|
||||
// These test were implement for the mock-runtime and need to be ported yet.
|
||||
|
||||
#[test]
|
||||
fn create2_failure() {
|
||||
let mut state = State::default();
|
||||
@@ -484,155 +457,4 @@ fn create2_failure() {
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Revert);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_with_value() {
|
||||
let mut state = State::default();
|
||||
state.upload_code(&Contract::create_a().pvm_runtime);
|
||||
let amount = U256::from(123);
|
||||
|
||||
let contract = Contract::create_b();
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.callvalue(amount)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
assert_eq!(state.accounts().len(), 2);
|
||||
|
||||
for (address, account) in state.accounts() {
|
||||
if *address == Transaction::default_address() {
|
||||
assert_eq!(account.value, U256::ZERO);
|
||||
} else {
|
||||
assert_eq!(account.value, amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_code_size() {
|
||||
let contract = Contract::ext_code_size(Transaction::default_address());
|
||||
let (_, output) = assert_success(&contract, false);
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
let expected = U256::from(contract.pvm_runtime.len());
|
||||
assert_eq!(received, expected);
|
||||
|
||||
let contract = Contract::ext_code_size(Default::default());
|
||||
let (_, output) = assert_success(&contract, false);
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
let expected = U256::ZERO;
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_size() {
|
||||
let contract = Contract::code_size();
|
||||
let (_, output) = assert_success(&contract, false);
|
||||
let expected = U256::from(contract.pvm_runtime.len());
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
assert_eq!(expected, received);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_transfer() {
|
||||
// Succeeds in remix (shanghai) but traps the interpreter
|
||||
let (state, _) = assert_success(&Contract::call_value_transfer(Default::default()), false);
|
||||
|
||||
assert_eq!(state.accounts().len(), 2);
|
||||
assert!(state.accounts().get(&Address::default()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echo() {
|
||||
let (state, address) = State::new_deployed(Contract::call_constructor());
|
||||
|
||||
let expected = vec![1, 2, 3, 4, 5];
|
||||
let contract = Contract::call_call(address, expected.clone());
|
||||
let (_, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
let received = alloy_primitives::Bytes::abi_decode(&output.data, true)
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
|
||||
assert_eq!(expected, received);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcopy() {
|
||||
let expected = vec![1, 2, 3];
|
||||
|
||||
let (_, output) = assert_success(&Contract::memcpy(expected.clone()), false);
|
||||
|
||||
let received = alloy_primitives::Bytes::abi_decode(&output.data, true)
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
|
||||
assert_eq!(expected, received);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance() {
|
||||
let (_, output) = assert_success(&Contract::value_balance_of(Default::default()), false);
|
||||
|
||||
let expected = U256::ZERO;
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
assert_eq!(expected, received);
|
||||
|
||||
let expected = U256::from(54589);
|
||||
let (mut state, address) = State::new_deployed(Contract::value_balance_of(Default::default()));
|
||||
state.accounts_mut().get_mut(&address).unwrap().value = expected;
|
||||
|
||||
let contract = Contract::value_balance_of(address);
|
||||
let (_, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata)
|
||||
.call();
|
||||
|
||||
assert_eq!(ReturnFlags::Success, output.flags);
|
||||
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
assert_eq!(expected, received)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitwise_byte() {
|
||||
assert_success(&Contract::bitwise_byte(U256::ZERO, U256::ZERO), true);
|
||||
assert_success(&Contract::bitwise_byte(U256::ZERO, U256::MAX), true);
|
||||
assert_success(&Contract::bitwise_byte(U256::MAX, U256::ZERO), true);
|
||||
assert_success(
|
||||
&Contract::bitwise_byte(U256::from_str("18446744073709551619").unwrap(), U256::MAX),
|
||||
true,
|
||||
);
|
||||
|
||||
let de_bruijn_sequence =
|
||||
hex::decode("4060503824160d0784426150b864361d0f88c4a27148ac5a2f198d46e391d8f4").unwrap();
|
||||
let value = U256::from_be_bytes::<32>(de_bruijn_sequence.clone().try_into().unwrap());
|
||||
|
||||
for (index, byte) in de_bruijn_sequence.iter().enumerate() {
|
||||
let (_, output) = assert_success(&Contract::bitwise_byte(U256::from(index), value), true);
|
||||
let expected = U256::from(*byte as i32);
|
||||
let received = U256::abi_decode(&output.data, true).unwrap();
|
||||
assert_eq!(expected, received)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transient_storage() {
|
||||
let expected = U256::MAX;
|
||||
let (state, output) = assert_success(&Contract::storage_transient(expected), false);
|
||||
let received = U256::abi_decode(&output.data, true).unwrap();
|
||||
assert_eq!(expected, received);
|
||||
|
||||
assert!(state
|
||||
.accounts()
|
||||
.values()
|
||||
.all(|account| account.storage.is_empty()));
|
||||
}
|
||||
*/
|
||||
|
||||
@@ -32,6 +32,7 @@ fn invoke_lld(cmd_args: &[&str]) -> bool {
|
||||
fn polkavm_linker<T: AsRef<[u8]>>(code: T) -> anyhow::Result<Vec<u8>> {
|
||||
let mut config = polkavm_linker::Config::default();
|
||||
config.set_strip(true);
|
||||
config.set_optimize(true);
|
||||
|
||||
polkavm_linker::program_from_elf(config, code.as_ref())
|
||||
.map_err(|reason| anyhow::anyhow!("polkavm linker failed: {}", reason))
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
[package]
|
||||
name = "revive-llvm-context"
|
||||
version = "1.4.1"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors = [
|
||||
"Oleksandr Zarudnyi <a.zarudnyy@matterlabs.dev>",
|
||||
"Cyrill Leutwiler <cyrill@parity.io>",
|
||||
]
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
description = "Shared front end code of the revive PolkaVM compilers"
|
||||
|
||||
[lib]
|
||||
@@ -32,10 +33,8 @@ inkwell = { workspace = true }
|
||||
polkavm-disassembler = { workspace = true }
|
||||
polkavm-common = { workspace = true }
|
||||
|
||||
zkevm_opcode_defs = { git = "https://github.com/matter-labs/era-zkevm_opcode_defs", branch = "v1.4.1" }
|
||||
revive-common = { path = "../common" }
|
||||
|
||||
pallet-contracts-pvm-llapi = { path = "../pallet-contracts-pvm-llapi" }
|
||||
revive-linker = { path = "../linker" }
|
||||
revive-builtins = { path = "../builtins" }
|
||||
revive-stdlib = { path = "../stdlib" }
|
||||
revive-common = { workspace = true }
|
||||
revive-runtime-api = { workspace = true }
|
||||
revive-linker = { workspace = true }
|
||||
revive-builtins = { workspace = true }
|
||||
revive-stdlib = { workspace = true }
|
||||
|
||||
@@ -27,9 +27,11 @@ pub use self::polkavm::context::function::llvm_runtime::LLVMRuntime as PolkaVMLL
|
||||
pub use self::polkavm::context::function::r#return::Return as PolkaVMFunctionReturn;
|
||||
pub use self::polkavm::context::function::runtime::deploy_code::DeployCode as PolkaVMDeployCodeFunction;
|
||||
pub use self::polkavm::context::function::runtime::entry::Entry as PolkaVMEntryFunction;
|
||||
pub use self::polkavm::context::function::runtime::immutable_data_load::ImmutableDataLoad as PolkaVMImmutableDataLoadFunction;
|
||||
pub use self::polkavm::context::function::runtime::runtime_code::RuntimeCode as PolkaVMRuntimeCodeFunction;
|
||||
pub use self::polkavm::context::function::runtime::FUNCTION_DEPLOY_CODE as PolkaVMFunctionDeployCode;
|
||||
pub use self::polkavm::context::function::runtime::FUNCTION_ENTRY as PolkaVMFunctionEntry;
|
||||
pub use self::polkavm::context::function::runtime::FUNCTION_LOAD_IMMUTABLE_DATA as PolkaVMFunctionImmutableDataLoad;
|
||||
pub use self::polkavm::context::function::runtime::FUNCTION_RUNTIME_CODE as PolkaVMFunctionRuntimeCode;
|
||||
pub use self::polkavm::context::function::yul_data::YulData as PolkaVMFunctionYulData;
|
||||
pub use self::polkavm::context::function::Function as PolkaVMFunction;
|
||||
|
||||
@@ -21,8 +21,6 @@ pub struct Settings {
|
||||
|
||||
/// Fallback to optimizing for size if the bytecode is too large.
|
||||
pub is_fallback_to_size_enabled: bool,
|
||||
/// Whether the system request memoization is disabled.
|
||||
pub is_system_request_memoization_disabled: bool,
|
||||
|
||||
/// Whether the LLVM `verify each` option is enabled.
|
||||
pub is_verify_each_enabled: bool,
|
||||
@@ -43,7 +41,6 @@ impl Settings {
|
||||
level_back_end,
|
||||
|
||||
is_fallback_to_size_enabled: false,
|
||||
is_system_request_memoization_disabled: false,
|
||||
|
||||
is_verify_each_enabled: false,
|
||||
is_debug_logging_enabled: false,
|
||||
@@ -65,7 +62,6 @@ impl Settings {
|
||||
level_back_end,
|
||||
|
||||
is_fallback_to_size_enabled: false,
|
||||
is_system_request_memoization_disabled: false,
|
||||
|
||||
is_verify_each_enabled,
|
||||
is_debug_logging_enabled,
|
||||
@@ -206,20 +202,10 @@ impl Settings {
|
||||
self.is_fallback_to_size_enabled = true;
|
||||
}
|
||||
|
||||
/// Disables the system request memoization.
|
||||
pub fn disable_system_request_memoization(&mut self) {
|
||||
self.is_system_request_memoization_disabled = true;
|
||||
}
|
||||
|
||||
/// Whether the fallback to optimizing for size is enabled.
|
||||
pub fn is_fallback_to_size_enabled(&self) -> bool {
|
||||
self.is_fallback_to_size_enabled
|
||||
}
|
||||
|
||||
/// Whether the system request memoization is disabled.
|
||||
pub fn is_system_request_memoization_disabled(&self) -> bool {
|
||||
self.is_system_request_memoization_disabled
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Settings {
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
//! The LLVM context constants.
|
||||
|
||||
/// Runtime API methods.
|
||||
pub mod runtime_api;
|
||||
|
||||
/// The LLVM framework version.
|
||||
pub const LLVM_VERSION: semver::Version = semver::Version::new(18, 1, 4);
|
||||
|
||||
/// The PolkaVM version.
|
||||
pub const ZKEVM_VERSION: semver::Version = semver::Version::new(1, 3, 2);
|
||||
|
||||
/// The register width sized type
|
||||
pub static XLEN: usize = revive_common::BIT_LENGTH_X32;
|
||||
|
||||
@@ -21,55 +15,9 @@ pub static GLOBAL_CALLDATA_POINTER: &str = "ptr_calldata";
|
||||
/// The calldata size global variable name.
|
||||
pub static GLOBAL_CALLDATA_SIZE: &str = "calldatasize";
|
||||
|
||||
/// The return data pointer global variable name.
|
||||
pub static GLOBAL_RETURN_DATA_POINTER: &str = "ptr_return_data";
|
||||
|
||||
/// The return data size pointer global variable name.
|
||||
pub static GLOBAL_RETURN_DATA_SIZE: &str = "returndatasize";
|
||||
|
||||
/// The call flags global variable name.
|
||||
pub static GLOBAL_CALL_FLAGS: &str = "call_flags";
|
||||
|
||||
/// The extra ABI data global variable name.
|
||||
pub static GLOBAL_EXTRA_ABI_DATA: &str = "extra_abi_data";
|
||||
|
||||
/// The constant array global variable name prefix.
|
||||
pub static GLOBAL_CONST_ARRAY_PREFIX: &str = "const_array_";
|
||||
|
||||
/// The global verbatim getter identifier prefix.
|
||||
pub static GLOBAL_VERBATIM_GETTER_PREFIX: &str = "get_global::";
|
||||
|
||||
/// The static word size.
|
||||
pub static GLOBAL_I256_SIZE: &str = "i256_size";
|
||||
|
||||
/// The static value size.
|
||||
pub static GLOBAL_I160_SIZE: &str = "i160_size";
|
||||
|
||||
/// The static i64 size.
|
||||
pub static GLOBAL_I64_SIZE: &str = "i64_size";
|
||||
|
||||
/// The external call data offset in the auxiliary heap.
|
||||
pub const HEAP_AUX_OFFSET_EXTERNAL_CALL: u64 = 0;
|
||||
|
||||
/// The constructor return data offset in the auxiliary heap.
|
||||
pub const HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA: u64 =
|
||||
8 * (revive_common::BYTE_LENGTH_WORD as u64);
|
||||
|
||||
/// The number of the extra ABI data arguments.
|
||||
pub const EXTRA_ABI_DATA_SIZE: usize = 0;
|
||||
|
||||
/// The `create` method deployer signature.
|
||||
pub static DEPLOYER_SIGNATURE_CREATE: &str = "create(bytes32,bytes32,bytes)";
|
||||
|
||||
/// The `create2` method deployer signature.
|
||||
pub static DEPLOYER_SIGNATURE_CREATE2: &str = "create2(bytes32,bytes32,bytes)";
|
||||
|
||||
/// The absence of system call bit.
|
||||
pub const NO_SYSTEM_CALL_BIT: bool = false;
|
||||
|
||||
/// The system call bit.
|
||||
pub const SYSTEM_CALL_BIT: bool = true;
|
||||
|
||||
/// The deployer call header size that consists of:
|
||||
/// - bytecode hash (32 bytes)
|
||||
pub const DEPLOYER_CALL_HEADER_SIZE: usize = revive_common::BYTE_LENGTH_WORD;
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
//! Runtime API import and export symbols.
|
||||
|
||||
pub mod exports {
|
||||
/// The contract deploy export.
|
||||
pub static CALL: &str = "call";
|
||||
|
||||
/// The contract call export.
|
||||
pub static DEPLOY: &str = "deploy";
|
||||
|
||||
/// All exported symbols.
|
||||
/// Useful for configuring common attributes and linkage.
|
||||
pub static EXPORTS: [&str; 2] = [CALL, DEPLOY];
|
||||
}
|
||||
|
||||
pub mod imports {
|
||||
pub static ADDRESS: &str = "address";
|
||||
|
||||
pub static BALANCE: &str = "balance";
|
||||
|
||||
pub static BLOCK_NUMBER: &str = "block_number";
|
||||
|
||||
pub static CALL: &str = "seal_call";
|
||||
|
||||
pub static CALLER: &str = "caller";
|
||||
|
||||
pub static CODE_SIZE: &str = "code_size";
|
||||
|
||||
pub static DEPOSIT_EVENT: &str = "deposit_event";
|
||||
|
||||
pub static GET_STORAGE: &str = "get_storage";
|
||||
|
||||
pub static HASH_KECCAK_256: &str = "hash_keccak_256";
|
||||
|
||||
pub static INPUT: &str = "input";
|
||||
|
||||
pub static INSTANTIATE: &str = "instantiate";
|
||||
|
||||
pub static NOW: &str = "now";
|
||||
|
||||
pub static RETURN: &str = "seal_return";
|
||||
|
||||
pub static RETURNDATACOPY: &str = "returndatacopy";
|
||||
|
||||
pub static SET_STORAGE: &str = "set_storage";
|
||||
|
||||
pub static VALUE_TRANSFERRED: &str = "value_transferred";
|
||||
|
||||
/// All imported runtime API symbols.
|
||||
/// Useful for configuring common attributes and linkage.
|
||||
pub static IMPORTS: [&str; 16] = [
|
||||
ADDRESS,
|
||||
BALANCE,
|
||||
BLOCK_NUMBER,
|
||||
CALL,
|
||||
CALLER,
|
||||
CODE_SIZE,
|
||||
DEPOSIT_EVENT,
|
||||
GET_STORAGE,
|
||||
HASH_KECCAK_256,
|
||||
INPUT,
|
||||
INSTANTIATE,
|
||||
NOW,
|
||||
RETURN,
|
||||
RETURNDATACOPY,
|
||||
SET_STORAGE,
|
||||
VALUE_TRANSFERRED,
|
||||
];
|
||||
}
|
||||
|
||||
/// PolkaVM __sbrk API symbol to extend the heap memory.
|
||||
pub static SBRK: &str = "__sbrk";
|
||||
@@ -11,15 +11,6 @@ use crate::polkavm::context::function::Function;
|
||||
/// The functions are automatically linked to the LLVM implementations if the signatures match.
|
||||
#[derive(Debug)]
|
||||
pub struct LLVMRuntime<'ctx> {
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub shl: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub shr: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub sar: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub byte: FunctionDeclaration<'ctx>,
|
||||
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub add_mod: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
@@ -31,32 +22,9 @@ pub struct LLVMRuntime<'ctx> {
|
||||
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub sha3: FunctionDeclaration<'ctx>,
|
||||
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub r#return: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub revert: FunctionDeclaration<'ctx>,
|
||||
}
|
||||
|
||||
impl<'ctx> LLVMRuntime<'ctx> {
|
||||
/// The LLVM personality function name.
|
||||
pub const FUNCTION_PERSONALITY: &'static str = "__personality";
|
||||
|
||||
/// The LLVM exception throwing function name.
|
||||
pub const FUNCTION_CXA_THROW: &'static str = "__cxa_throw";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SHL: &'static str = "__shl";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SHR: &'static str = "__shr";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SAR: &'static str = "__sar";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_BYTE: &'static str = "__byte";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_ADDMOD: &'static str = "__addmod";
|
||||
|
||||
@@ -72,121 +40,12 @@ impl<'ctx> LLVMRuntime<'ctx> {
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SHA3: &'static str = "__sha3";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SYSTEM_REQUEST: &'static str = "__system_request";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_FARCALL: &'static str = "__farcall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_STATICCALL: &'static str = "__staticcall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_DELEGATECALL: &'static str = "__delegatecall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_MIMICCALL: &'static str = "__mimiccall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_FARCALL_BYREF: &'static str = "__farcall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_STATICCALL_BYREF: &'static str = "__staticcall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_DELEGATECALL_BYREF: &'static str = "__delegatecall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_MIMICCALL_BYREF: &'static str = "__mimiccall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_RETURN: &'static str = "__return";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_REVERT: &'static str = "__revert";
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
module: &inkwell::module::Module<'ctx>,
|
||||
optimizer: &Optimizer,
|
||||
) -> Self {
|
||||
let shl = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_SHL,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, shl, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, shl);
|
||||
|
||||
let shr = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_SHR,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, shr, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, shr);
|
||||
|
||||
let sar = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_SAR,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, sar, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, sar);
|
||||
|
||||
let byte = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_BYTE,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, byte, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, byte);
|
||||
|
||||
let add_mod =
|
||||
Self::define(module, Self::FUNCTION_ADDMOD).expect("should be declared in stdlib");
|
||||
Function::set_default_attributes(llvm, add_mod, optimizer);
|
||||
@@ -236,54 +95,13 @@ impl<'ctx> LLVMRuntime<'ctx> {
|
||||
false,
|
||||
);
|
||||
|
||||
let r#return = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_RETURN,
|
||||
llvm.void_type().fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
3
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, r#return, optimizer);
|
||||
let revert = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_REVERT,
|
||||
llvm.void_type().fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
3
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, revert, optimizer);
|
||||
|
||||
Self {
|
||||
shl,
|
||||
shr,
|
||||
sar,
|
||||
byte,
|
||||
|
||||
add_mod,
|
||||
mul_mod,
|
||||
exp,
|
||||
sign_extend,
|
||||
|
||||
sha3,
|
||||
|
||||
r#return,
|
||||
revert,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,12 +48,6 @@ pub struct Function<'ctx> {
|
||||
}
|
||||
|
||||
impl<'ctx> Function<'ctx> {
|
||||
/// The near call ABI function prefix.
|
||||
pub const ZKSYNC_NEAR_CALL_ABI_PREFIX: &'static str = "ZKSYNC_NEAR_CALL";
|
||||
|
||||
/// The near call ABI exception handler name.
|
||||
pub const ZKSYNC_NEAR_CALL_ABI_EXCEPTION_HANDLER: &'static str = "ZKSYNC_CATCH_NEAR_CALL";
|
||||
|
||||
/// The stack hashmap default capacity.
|
||||
const STACK_HASHMAP_INITIAL_CAPACITY: usize = 64;
|
||||
|
||||
@@ -91,13 +85,8 @@ impl<'ctx> Function<'ctx> {
|
||||
|| (name.starts_with("__")
|
||||
&& name != self::runtime::FUNCTION_ENTRY
|
||||
&& name != self::runtime::FUNCTION_DEPLOY_CODE
|
||||
&& name != self::runtime::FUNCTION_RUNTIME_CODE)
|
||||
}
|
||||
|
||||
/// Checks whether the function is related to the near call ABI.
|
||||
pub fn is_near_call_abi(name: &str) -> bool {
|
||||
name.starts_with(Self::ZKSYNC_NEAR_CALL_ABI_PREFIX)
|
||||
|| name == Self::ZKSYNC_NEAR_CALL_ABI_EXCEPTION_HANDLER
|
||||
&& name != self::runtime::FUNCTION_RUNTIME_CODE
|
||||
&& name != self::runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
|
||||
}
|
||||
|
||||
/// Returns the LLVM function declaration.
|
||||
|
||||
@@ -42,8 +42,7 @@ where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
let function_type =
|
||||
context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false);
|
||||
let function_type = context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0);
|
||||
context.add_function(
|
||||
runtime::FUNCTION_DEPLOY_CODE,
|
||||
function_type,
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
//! The entry function.
|
||||
|
||||
use inkwell::types::BasicType;
|
||||
use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::function::runtime;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::r#const::*;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm::WriteLLVM;
|
||||
|
||||
@@ -20,14 +18,8 @@ impl Entry {
|
||||
/// The call flags argument index.
|
||||
pub const ARGUMENT_INDEX_CALL_FLAGS: usize = 0;
|
||||
|
||||
/// The number of mandatory arguments.
|
||||
pub const MANDATORY_ARGUMENTS_COUNT: usize = 2;
|
||||
|
||||
/// Reserve 1mb for calldata.
|
||||
pub const MAX_CALLDATA_SIZE: usize = 1024 * 1024;
|
||||
|
||||
/// Reserve 1mb for returndata.
|
||||
pub const MAX_RETURNDATA_SIZE: usize = 1024 * 1024;
|
||||
/// Reserve 1kb for calldata.
|
||||
pub const MAX_CALLDATA_SIZE: usize = 1024;
|
||||
|
||||
/// Initializes the global variables.
|
||||
/// The pointers are not initialized, because it's not possible to create a null pointer.
|
||||
@@ -43,14 +35,6 @@ impl Entry {
|
||||
calldata_type.get_undef(),
|
||||
);
|
||||
|
||||
let returndata_type = context.array_type(context.byte_type(), Self::MAX_RETURNDATA_SIZE);
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_RETURN_DATA_POINTER,
|
||||
returndata_type,
|
||||
AddressSpace::Stack,
|
||||
returndata_type.get_undef(),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER,
|
||||
context.llvm().ptr_type(AddressSpace::Heap.into()),
|
||||
@@ -61,7 +45,10 @@ impl Entry {
|
||||
context
|
||||
.get_global(crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER)?
|
||||
.into(),
|
||||
context.build_sbrk(context.integer_const(crate::polkavm::XLEN, 0))?,
|
||||
context.build_sbrk(
|
||||
context.xlen_type().const_zero(),
|
||||
context.xlen_type().const_zero(),
|
||||
)?,
|
||||
)?;
|
||||
|
||||
context.set_global(
|
||||
@@ -70,12 +57,6 @@ impl Entry {
|
||||
AddressSpace::Stack,
|
||||
context.word_undef(),
|
||||
);
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_RETURN_DATA_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.xlen_type().const_zero().as_basic_value_enum(),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_CALL_FLAGS,
|
||||
@@ -84,44 +65,6 @@ impl Entry {
|
||||
context.word_const(0),
|
||||
);
|
||||
|
||||
let extra_abi_data_type = context.array_type(
|
||||
context.word_type().as_basic_type_enum(),
|
||||
crate::polkavm::EXTRA_ABI_DATA_SIZE,
|
||||
);
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_EXTRA_ABI_DATA,
|
||||
extra_abi_data_type,
|
||||
AddressSpace::Stack,
|
||||
extra_abi_data_type.const_zero(),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_I256_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.integer_const(
|
||||
crate::polkavm::XLEN,
|
||||
revive_common::BYTE_LENGTH_X64 as u64 * 4,
|
||||
),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_I160_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.integer_const(
|
||||
crate::polkavm::XLEN,
|
||||
revive_common::BYTE_LENGTH_X64 as u64 * 2 + revive_common::BYTE_LENGTH_X32 as u64,
|
||||
),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_I64_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.integer_const(crate::polkavm::XLEN, revive_common::BYTE_LENGTH_X64 as u64),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -141,7 +84,7 @@ impl Entry {
|
||||
"input_pointer_casted",
|
||||
)?;
|
||||
|
||||
let length_pointer = context.build_alloca(context.xlen_type(), "len_ptr");
|
||||
let length_pointer = context.build_alloca_at_entry(context.xlen_type(), "len_ptr");
|
||||
let length_pointer_casted = context.builder.build_ptr_to_int(
|
||||
length_pointer.value,
|
||||
context.xlen_type(),
|
||||
@@ -153,7 +96,7 @@ impl Entry {
|
||||
context.integer_const(crate::polkavm::XLEN, Self::MAX_CALLDATA_SIZE as u64),
|
||||
)?;
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::INPUT,
|
||||
revive_runtime_api::polkavm_imports::INPUT,
|
||||
&[input_pointer_casted.into(), length_pointer_casted.into()],
|
||||
);
|
||||
|
||||
@@ -232,12 +175,25 @@ where
|
||||
{
|
||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
let entry_arguments = vec![context.bool_type().as_basic_type_enum()];
|
||||
let entry_function_type = context.function_type(entry_arguments, 0, false);
|
||||
context.add_function(runtime::FUNCTION_ENTRY, entry_function_type, 0, None)?;
|
||||
let entry_function_type = context.function_type(entry_arguments, 0);
|
||||
context.add_function(
|
||||
runtime::FUNCTION_ENTRY,
|
||||
entry_function_type,
|
||||
0,
|
||||
Some(inkwell::module::Linkage::External),
|
||||
)?;
|
||||
|
||||
for symbol in runtime_api::exports::EXPORTS {
|
||||
context.declare_extern_function(symbol)?;
|
||||
}
|
||||
context.declare_global(
|
||||
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER,
|
||||
context.word_type().array_type(0),
|
||||
AddressSpace::Stack,
|
||||
);
|
||||
|
||||
context.declare_global(
|
||||
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -258,26 +214,6 @@ where
|
||||
true,
|
||||
);
|
||||
|
||||
context.set_current_function(runtime_api::exports::DEPLOY)?;
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
|
||||
assert!(context
|
||||
.build_call(entry, &[context.bool_const(true).into()], "entry_deploy")
|
||||
.is_none());
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().return_block);
|
||||
context.build_unreachable();
|
||||
|
||||
context.set_current_function(runtime_api::exports::CALL)?;
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
|
||||
assert!(context
|
||||
.build_call(entry, &[context.bool_const(false).into()], "entry_call")
|
||||
.is_none());
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().return_block);
|
||||
context.build_unreachable();
|
||||
|
||||
context.set_current_function(runtime::FUNCTION_ENTRY)?;
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! The immutable data runtime function.
|
||||
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::function::runtime;
|
||||
use crate::polkavm::context::pointer::Pointer;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm::WriteLLVM;
|
||||
|
||||
/// A function for requesting the immutable data from the runtime.
|
||||
/// This is a special function that is only used by the front-end generated code.
|
||||
///
|
||||
/// The runtime API is called lazily and subsequent calls are no-ops.
|
||||
///
|
||||
/// The bytes written is asserted to match the expected length.
|
||||
/// This should never fail; the length is known.
|
||||
/// However, this is a one time assertion, hence worth it.
|
||||
#[derive(Debug)]
|
||||
pub struct ImmutableDataLoad;
|
||||
|
||||
impl<D> WriteLLVM<D> for ImmutableDataLoad
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
context.add_function(
|
||||
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
|
||||
context.void_type().fn_type(Default::default(), false),
|
||||
0,
|
||||
Some(inkwell::module::Linkage::Private),
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn into_llvm(self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
context.set_current_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)?;
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
|
||||
let immutable_data_size_pointer = context
|
||||
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
let immutable_data_size = context.build_load(
|
||||
Pointer::new(
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
immutable_data_size_pointer,
|
||||
),
|
||||
"immutable_data_size_load",
|
||||
)?;
|
||||
|
||||
let load_immutable_data_block = context.append_basic_block("load_immutables_block");
|
||||
let return_block = context.current_function().borrow().return_block();
|
||||
let immutable_data_size_is_zero = context.builder().build_int_compare(
|
||||
inkwell::IntPredicate::EQ,
|
||||
context.xlen_type().const_zero(),
|
||||
immutable_data_size.into_int_value(),
|
||||
"immutable_data_size_is_zero",
|
||||
)?;
|
||||
context.build_conditional_branch(
|
||||
immutable_data_size_is_zero,
|
||||
return_block,
|
||||
load_immutable_data_block,
|
||||
)?;
|
||||
|
||||
context.set_basic_block(load_immutable_data_block);
|
||||
let output_pointer = context
|
||||
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::GET_IMMUTABLE_DATA,
|
||||
&[
|
||||
context
|
||||
.builder()
|
||||
.build_ptr_to_int(output_pointer, context.xlen_type(), "ptr_to_xlen")?
|
||||
.into(),
|
||||
context
|
||||
.builder()
|
||||
.build_ptr_to_int(
|
||||
immutable_data_size_pointer,
|
||||
context.xlen_type(),
|
||||
"ptr_to_xlen",
|
||||
)?
|
||||
.into(),
|
||||
],
|
||||
);
|
||||
let bytes_written = context.builder().build_load(
|
||||
context.xlen_type(),
|
||||
immutable_data_size_pointer,
|
||||
"bytes_written",
|
||||
)?;
|
||||
context.builder().build_store(
|
||||
immutable_data_size_pointer,
|
||||
context.xlen_type().const_zero(),
|
||||
)?;
|
||||
let overflow_block = context.append_basic_block("immutable_data_overflow");
|
||||
let is_overflow = context.builder().build_int_compare(
|
||||
inkwell::IntPredicate::UGT,
|
||||
immutable_data_size.into_int_value(),
|
||||
bytes_written.into_int_value(),
|
||||
"is_overflow",
|
||||
)?;
|
||||
context.build_conditional_branch(is_overflow, overflow_block, return_block)?;
|
||||
|
||||
context.set_basic_block(overflow_block);
|
||||
context.build_call(context.intrinsics().trap, &[], "invalid_trap");
|
||||
context.build_unreachable();
|
||||
|
||||
context.set_basic_block(return_block);
|
||||
context.build_return(None);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub mod deploy_code;
|
||||
pub mod entry;
|
||||
pub mod immutable_data_load;
|
||||
pub mod runtime_code;
|
||||
|
||||
/// The main entry function name.
|
||||
@@ -12,3 +13,6 @@ pub const FUNCTION_DEPLOY_CODE: &str = "__deploy";
|
||||
|
||||
/// The runtime code function name.
|
||||
pub const FUNCTION_RUNTIME_CODE: &str = "__runtime";
|
||||
|
||||
/// The immutable data load function name.
|
||||
pub const FUNCTION_LOAD_IMMUTABLE_DATA: &str = "__immutable_data_load";
|
||||
|
||||
@@ -42,8 +42,7 @@ where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
let function_type =
|
||||
context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false);
|
||||
let function_type = context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0);
|
||||
context.add_function(
|
||||
runtime::FUNCTION_RUNTIME_CODE,
|
||||
function_type,
|
||||
|
||||
@@ -51,4 +51,31 @@ impl<'ctx> Global<'ctx> {
|
||||
|
||||
global
|
||||
}
|
||||
|
||||
/// Construct an external global.
|
||||
pub fn declare<D, T>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
r#type: T,
|
||||
address_space: AddressSpace,
|
||||
name: &str,
|
||||
) -> Self
|
||||
where
|
||||
D: PolkaVMDependency + Clone,
|
||||
T: BasicType<'ctx>,
|
||||
{
|
||||
let r#type = r#type.as_basic_type_enum();
|
||||
|
||||
let value = context
|
||||
.module()
|
||||
.add_global(r#type, Some(address_space.into()), name);
|
||||
let global = Self { r#type, value };
|
||||
|
||||
global.value.set_linkage(inkwell::module::Linkage::External);
|
||||
global
|
||||
.value
|
||||
.set_visibility(inkwell::GlobalVisibility::Default);
|
||||
global.value.set_externally_initialized(true);
|
||||
|
||||
global
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ use inkwell::values::BasicValue;
|
||||
|
||||
use crate::optimizer::settings::Settings as OptimizerSettings;
|
||||
use crate::optimizer::Optimizer;
|
||||
use crate::polkavm::r#const::*;
|
||||
use crate::polkavm::DebugConfig;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::target_machine::target::Target;
|
||||
@@ -124,29 +123,19 @@ where
|
||||
.expect("the stdlib module should be linkable");
|
||||
}
|
||||
|
||||
/// Link in the PolkaVM guest module, containing imported and exported functions,
|
||||
/// Link in the PolkaVM imports module, containing imported functions,
|
||||
/// and marking them as external (they need to be relocatable as too).
|
||||
fn link_polkavm_guest_module(
|
||||
fn link_polkavm_imports(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
module: &inkwell::module::Module<'ctx>,
|
||||
) {
|
||||
module
|
||||
.link_in_module(
|
||||
pallet_contracts_pvm_llapi::polkavm_guest::module(llvm, "polkavm_guest").unwrap(),
|
||||
revive_runtime_api::polkavm_imports::module(llvm, "polkavm_imports").unwrap(),
|
||||
)
|
||||
.expect("the PolkaVM guest API module should be linkable");
|
||||
.expect("the PolkaVM imports module should be linkable");
|
||||
|
||||
for export in runtime_api::exports::EXPORTS {
|
||||
module
|
||||
.get_function(export)
|
||||
.expect("should be declared")
|
||||
.add_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
llvm.create_enum_attribute(Attribute::NoReturn as u32, 0),
|
||||
);
|
||||
}
|
||||
|
||||
for import in runtime_api::imports::IMPORTS {
|
||||
for import in revive_runtime_api::polkavm_imports::IMPORTS {
|
||||
module
|
||||
.get_function(import)
|
||||
.expect("should be declared")
|
||||
@@ -154,6 +143,36 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn link_polkavm_exports(&self, contract_path: &str) -> anyhow::Result<()> {
|
||||
let exports = revive_runtime_api::polkavm_exports::module(self.llvm(), "polkavm_exports")
|
||||
.map_err(|error| {
|
||||
anyhow::anyhow!(
|
||||
"The contract `{}` exports module loading error: {}",
|
||||
contract_path,
|
||||
error
|
||||
)
|
||||
})?;
|
||||
self.module.link_in_module(exports).map_err(|error| {
|
||||
anyhow::anyhow!(
|
||||
"The contract `{}` exports module linking error: {}",
|
||||
contract_path,
|
||||
error
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn link_immutable_data(&self, contract_path: &str) -> anyhow::Result<()> {
|
||||
let size = self.solidity().immutables_size() as u32;
|
||||
let exports = revive_runtime_api::immutable_data::module(self.llvm(), size);
|
||||
self.module.link_in_module(exports).map_err(|error| {
|
||||
anyhow::anyhow!(
|
||||
"The contract `{}` immutable data module linking error: {}",
|
||||
contract_path,
|
||||
error
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Configure the PolkaVM minimum stack size.
|
||||
fn set_polkavm_stack_size(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
@@ -161,7 +180,7 @@ where
|
||||
size: u32,
|
||||
) {
|
||||
module
|
||||
.link_in_module(pallet_contracts_pvm_llapi::polkavm_guest::min_stack_size(
|
||||
.link_in_module(revive_runtime_api::calling_convention::min_stack_size(
|
||||
llvm,
|
||||
"polkavm_stack_size",
|
||||
size,
|
||||
@@ -191,7 +210,7 @@ where
|
||||
debug_config: Option<DebugConfig>,
|
||||
) -> Self {
|
||||
Self::link_stdlib_module(llvm, &module);
|
||||
Self::link_polkavm_guest_module(llvm, &module);
|
||||
Self::link_polkavm_imports(llvm, &module);
|
||||
Self::set_polkavm_stack_size(llvm, &module, Self::POLKAVM_STACK_SIZE);
|
||||
Self::set_module_flags(llvm, &module);
|
||||
|
||||
@@ -230,6 +249,9 @@ where
|
||||
) -> anyhow::Result<Build> {
|
||||
let module_clone = self.module.clone();
|
||||
|
||||
self.link_polkavm_exports(contract_path)?;
|
||||
self.link_immutable_data(contract_path)?;
|
||||
|
||||
let target_machine = TargetMachine::new(Target::PVM, self.optimizer.settings())?;
|
||||
target_machine.set_target_data(self.module());
|
||||
|
||||
@@ -371,6 +393,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Declare an external global.
|
||||
pub fn declare_global<T>(&mut self, name: &str, r#type: T, address_space: AddressSpace)
|
||||
where
|
||||
T: BasicType<'ctx> + Clone + Copy,
|
||||
{
|
||||
let global = Global::declare(self, r#type, address_space, name);
|
||||
self.globals.insert(name.to_owned(), global);
|
||||
}
|
||||
|
||||
/// Returns the LLVM intrinsics collection reference.
|
||||
pub fn intrinsics(&self) -> &Intrinsics<'ctx> {
|
||||
&self.intrinsics
|
||||
@@ -381,47 +412,14 @@ where
|
||||
&self.llvm_runtime
|
||||
}
|
||||
|
||||
/// Declare a function already existing in the module.
|
||||
pub fn declare_extern_function(
|
||||
&mut self,
|
||||
name: &str,
|
||||
) -> anyhow::Result<Rc<RefCell<Function<'ctx>>>> {
|
||||
let function = self.module().get_function(name).ok_or_else(|| {
|
||||
anyhow::anyhow!("Failed to activate an undeclared function `{}`", name)
|
||||
})?;
|
||||
|
||||
let basic_block = self.llvm.append_basic_block(function, name);
|
||||
let declaration = FunctionDeclaration::new(
|
||||
self.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false),
|
||||
function,
|
||||
);
|
||||
let function = Function::new(
|
||||
name.to_owned(),
|
||||
declaration,
|
||||
FunctionReturn::None,
|
||||
basic_block,
|
||||
basic_block,
|
||||
);
|
||||
Function::set_default_attributes(self.llvm, function.declaration(), &self.optimizer);
|
||||
|
||||
let function = Rc::new(RefCell::new(function));
|
||||
self.functions.insert(name.to_string(), function.clone());
|
||||
|
||||
Ok(function)
|
||||
}
|
||||
|
||||
/// Appends a function to the current module.
|
||||
pub fn add_function(
|
||||
&mut self,
|
||||
name: &str,
|
||||
r#type: inkwell::types::FunctionType<'ctx>,
|
||||
return_values_length: usize,
|
||||
mut linkage: Option<inkwell::module::Linkage>,
|
||||
linkage: Option<inkwell::module::Linkage>,
|
||||
) -> anyhow::Result<Rc<RefCell<Function<'ctx>>>> {
|
||||
if Function::is_near_call_abi(name) && self.is_system_mode() {
|
||||
linkage = Some(inkwell::module::Linkage::External);
|
||||
}
|
||||
|
||||
let value = self.module().add_function(name, r#type, linkage);
|
||||
|
||||
let entry_block = self.llvm.append_basic_block(value, "entry");
|
||||
@@ -434,12 +432,6 @@ where
|
||||
let pointer = self.build_alloca(self.word_type(), "return_pointer");
|
||||
FunctionReturn::primitive(pointer)
|
||||
}
|
||||
size if name.starts_with(Function::ZKSYNC_NEAR_CALL_ABI_PREFIX) => {
|
||||
let first_argument = value.get_first_param().expect("Always exists");
|
||||
let r#type = self.structure_type(vec![self.word_type(); size].as_slice());
|
||||
let pointer = first_argument.into_pointer_value();
|
||||
FunctionReturn::compound(Pointer::new(r#type, AddressSpace::Stack, pointer), size)
|
||||
}
|
||||
size => {
|
||||
self.set_basic_block(entry_block);
|
||||
let pointer = self.build_alloca(
|
||||
@@ -460,10 +452,6 @@ where
|
||||
return_block,
|
||||
);
|
||||
Function::set_default_attributes(self.llvm, function.declaration(), &self.optimizer);
|
||||
if Function::is_near_call_abi(function.name()) && self.is_system_mode() {
|
||||
Function::set_exception_handler_attributes(self.llvm, function.declaration());
|
||||
}
|
||||
|
||||
let function = Rc::new(RefCell::new(function));
|
||||
self.functions.insert(name.to_string(), function.clone());
|
||||
|
||||
@@ -524,10 +512,6 @@ where
|
||||
manager,
|
||||
name,
|
||||
self.optimizer.settings().to_owned(),
|
||||
self.yul_data
|
||||
.as_ref()
|
||||
.map(|data| data.is_system_mode())
|
||||
.unwrap_or_default(),
|
||||
self.include_metadata_hash,
|
||||
self.debug_config.clone(),
|
||||
)
|
||||
@@ -585,59 +569,70 @@ where
|
||||
self.builder.get_insert_block().expect("Always exists")
|
||||
}
|
||||
|
||||
/// Builds a stack allocation instruction.
|
||||
/// Sets the alignment to 128 bits.
|
||||
/// Builds an aligned stack allocation at the function entry.
|
||||
pub fn build_alloca_at_entry<T: BasicType<'ctx> + Clone + Copy>(
|
||||
&self,
|
||||
r#type: T,
|
||||
name: &str,
|
||||
) -> Pointer<'ctx> {
|
||||
let current_block = self.basic_block();
|
||||
let entry_block = self.current_function().borrow().entry_block();
|
||||
|
||||
match entry_block.get_first_instruction() {
|
||||
Some(instruction) => self.builder().position_before(&instruction),
|
||||
None => self.builder().position_at_end(entry_block),
|
||||
}
|
||||
|
||||
let pointer = self.build_alloca(r#type, name);
|
||||
self.set_basic_block(current_block);
|
||||
pointer
|
||||
}
|
||||
|
||||
/// Builds an aligned stack allocation at the current position.
|
||||
/// Use this if [`build_alloca_at_entry`] might change program semantics.
|
||||
/// Otherwise, alloca should always be built at the function prelude!
|
||||
pub fn build_alloca<T: BasicType<'ctx> + Clone + Copy>(
|
||||
&self,
|
||||
r#type: T,
|
||||
name: &str,
|
||||
) -> Pointer<'ctx> {
|
||||
let pointer = self.builder.build_alloca(r#type, name).unwrap();
|
||||
self.basic_block()
|
||||
.get_last_instruction()
|
||||
.expect("Always exists")
|
||||
pointer
|
||||
.as_instruction()
|
||||
.unwrap()
|
||||
.set_alignment(revive_common::BYTE_LENGTH_STACK_ALIGN as u32)
|
||||
.expect("Alignment is valid");
|
||||
|
||||
Pointer::new(r#type, AddressSpace::Stack, pointer)
|
||||
}
|
||||
|
||||
/// Allocate an int of size `bit_length` on the stack.
|
||||
/// Returns the allocation pointer and the length pointer.
|
||||
///
|
||||
/// Useful helper for passing runtime API parameters on the stack.
|
||||
pub fn build_stack_parameter(
|
||||
/// Truncate `address` to the ethereum address length and store it as bytes on the stack.
|
||||
/// The stack allocation will be at the function entry. Returns the stack pointer.
|
||||
/// This helper should be used when passing address arguments to the runtime, ensuring correct size and endianness.
|
||||
pub fn build_address_argument_store(
|
||||
&self,
|
||||
bit_length: usize,
|
||||
name: &str,
|
||||
) -> (Pointer<'ctx>, Pointer<'ctx>) {
|
||||
let buffer_pointer = self.build_alloca(self.integer_type(bit_length), name);
|
||||
let symbol = match bit_length {
|
||||
revive_common::BIT_LENGTH_WORD => GLOBAL_I256_SIZE,
|
||||
revive_common::BIT_LENGTH_ETH_ADDRESS => GLOBAL_I160_SIZE,
|
||||
revive_common::BIT_LENGTH_BLOCK_NUMBER => GLOBAL_I64_SIZE,
|
||||
_ => panic!("invalid stack parameter bit width: {bit_length}"),
|
||||
};
|
||||
let length_pointer = self.get_global(symbol).expect("should be declared");
|
||||
(buffer_pointer, length_pointer.into())
|
||||
address: inkwell::values::IntValue<'ctx>,
|
||||
) -> anyhow::Result<Pointer<'ctx>> {
|
||||
let address_type = self.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS);
|
||||
let address_pointer = self.build_alloca_at_entry(address_type, "address_pointer");
|
||||
let address_truncated =
|
||||
self.builder()
|
||||
.build_int_truncate(address, address_type, "address_truncated")?;
|
||||
let address_swapped = self.build_byte_swap(address_truncated.into())?;
|
||||
self.build_store(address_pointer, address_swapped)?;
|
||||
Ok(address_pointer)
|
||||
}
|
||||
|
||||
/// Load the integer at given pointer and zero extend it to the VM word size.
|
||||
pub fn build_load_word(
|
||||
/// Load the address at given pointer and zero extend it to the VM word size.
|
||||
pub fn build_load_address(
|
||||
&self,
|
||||
pointer: Pointer<'ctx>,
|
||||
bit_length: usize,
|
||||
name: &str,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>> {
|
||||
let value = self.build_load(
|
||||
pointer.cast(self.integer_type(bit_length)),
|
||||
&format!("load_{name}"),
|
||||
)?;
|
||||
let value_extended = self.builder().build_int_z_extend(
|
||||
value.into_int_value(),
|
||||
self.word_type(),
|
||||
&format!("zext_{name}"),
|
||||
)?;
|
||||
Ok(value_extended.as_basic_value_enum())
|
||||
let address = self.build_byte_swap(self.build_load(pointer, "address_pointer")?)?;
|
||||
Ok(self
|
||||
.builder()
|
||||
.build_int_z_extend(address.into_int_value(), self.word_type(), "address_zext")?
|
||||
.into())
|
||||
}
|
||||
|
||||
/// Builds a stack load instruction.
|
||||
@@ -674,31 +669,25 @@ where
|
||||
self.build_byte_swap(value)
|
||||
}
|
||||
AddressSpace::Storage | AddressSpace::TransientStorage => {
|
||||
let storage_key_value = self.builder().build_ptr_to_int(
|
||||
pointer.value,
|
||||
self.word_type(),
|
||||
"storage_ptr_to_int",
|
||||
)?;
|
||||
let storage_key_pointer = self.build_alloca(self.word_type(), "storage_key");
|
||||
let storage_key_pointer_casted = self.builder().build_ptr_to_int(
|
||||
storage_key_pointer.value,
|
||||
self.xlen_type(),
|
||||
"storage_key_pointer_casted",
|
||||
)?;
|
||||
self.builder()
|
||||
.build_store(storage_key_pointer.value, storage_key_value)?;
|
||||
let storage_value_pointer =
|
||||
self.build_alloca(self.word_type(), "storage_value_pointer");
|
||||
self.build_store(storage_value_pointer, self.word_const(0))?;
|
||||
|
||||
let (storage_value_pointer, storage_value_length_pointer) = self
|
||||
.build_stack_parameter(revive_common::BIT_LENGTH_WORD, "storage_value_pointer");
|
||||
let storage_value_length_pointer =
|
||||
self.build_alloca(self.xlen_type(), "storage_value_length_pointer");
|
||||
self.build_store(
|
||||
storage_value_length_pointer,
|
||||
self.word_const(revive_common::BIT_LENGTH_WORD as u64),
|
||||
)?;
|
||||
|
||||
let transient = pointer.address_space == AddressSpace::TransientStorage;
|
||||
|
||||
self.build_runtime_call(
|
||||
runtime_api::imports::GET_STORAGE,
|
||||
revive_runtime_api::polkavm_imports::GET_STORAGE,
|
||||
&[
|
||||
self.xlen_type().const_int(transient as u64, false).into(),
|
||||
storage_key_pointer_casted.into(),
|
||||
self.integer_const(crate::polkavm::XLEN, 32).into(),
|
||||
pointer.to_int(self).into(),
|
||||
self.xlen_type().const_all_ones().into(),
|
||||
storage_value_pointer.to_int(self).into(),
|
||||
storage_value_length_pointer.to_int(self).into(),
|
||||
],
|
||||
@@ -766,18 +755,6 @@ where
|
||||
self.word_type().as_basic_type_enum()
|
||||
);
|
||||
|
||||
let storage_key_value = self.builder().build_ptr_to_int(
|
||||
pointer.value,
|
||||
self.word_type(),
|
||||
"storage_ptr_to_int",
|
||||
)?;
|
||||
let storage_key_pointer = self.build_alloca(self.word_type(), "storage_key");
|
||||
let storage_key_pointer_casted = self.builder().build_ptr_to_int(
|
||||
storage_key_pointer.value,
|
||||
self.xlen_type(),
|
||||
"storage_key_pointer_casted",
|
||||
)?;
|
||||
|
||||
let storage_value_pointer = self.build_alloca(self.word_type(), "storage_value");
|
||||
let storage_value_pointer_casted = self.builder().build_ptr_to_int(
|
||||
storage_value_pointer.value,
|
||||
@@ -785,19 +762,17 @@ where
|
||||
"storage_value_pointer_casted",
|
||||
)?;
|
||||
|
||||
self.builder()
|
||||
.build_store(storage_key_pointer.value, storage_key_value)?;
|
||||
self.builder()
|
||||
.build_store(storage_value_pointer.value, value)?;
|
||||
|
||||
let transient = pointer.address_space == AddressSpace::TransientStorage;
|
||||
|
||||
self.build_runtime_call(
|
||||
runtime_api::imports::SET_STORAGE,
|
||||
revive_runtime_api::polkavm_imports::SET_STORAGE,
|
||||
&[
|
||||
self.xlen_type().const_int(transient as u64, false).into(),
|
||||
storage_key_pointer_casted.into(),
|
||||
self.integer_const(crate::polkavm::XLEN, 32).into(),
|
||||
pointer.to_int(self).into(),
|
||||
self.xlen_type().const_all_ones().into(),
|
||||
storage_value_pointer_casted.into(),
|
||||
self.integer_const(crate::polkavm::XLEN, 32).into(),
|
||||
],
|
||||
@@ -905,13 +880,29 @@ where
|
||||
.copied()
|
||||
.map(inkwell::values::BasicMetadataValueEnum::from)
|
||||
.collect::<Vec<_>>(),
|
||||
&format!("runtime API call {name}"),
|
||||
&format!("runtime_api_{name}_return_value"),
|
||||
)
|
||||
.unwrap()
|
||||
.try_as_basic_value()
|
||||
.left()
|
||||
}
|
||||
|
||||
/// Builds a call to the runtime API `import`, where `import` is a "getter" API.
|
||||
/// This means that the supplied API method just writes back a single word.
|
||||
/// `import` is thus expect to have a single parameter, the 32 bytes output buffer,
|
||||
/// and no return value.
|
||||
pub fn build_runtime_call_to_getter(
|
||||
&self,
|
||||
import: &'static str,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let pointer = self.build_alloca_at_entry(self.word_type(), &format!("{import}_output"));
|
||||
self.build_runtime_call(import, &[pointer.to_int(self).into()]);
|
||||
self.build_load(pointer, import)
|
||||
}
|
||||
|
||||
/// Builds a call.
|
||||
pub fn build_call(
|
||||
&self,
|
||||
@@ -1012,7 +1003,7 @@ where
|
||||
)?;
|
||||
|
||||
self.build_runtime_call(
|
||||
runtime_api::imports::RETURN,
|
||||
revive_runtime_api::polkavm_imports::RETURN,
|
||||
&[flags.into(), offset_pointer.into(), length_pointer.into()],
|
||||
);
|
||||
self.build_unreachable();
|
||||
@@ -1070,16 +1061,20 @@ where
|
||||
Ok(truncated)
|
||||
}
|
||||
|
||||
/// Build a call to PolkaVM `sbrk` for extending the heap by `size`.
|
||||
/// Build a call to PolkaVM `sbrk` for extending the heap from offset by `size`.
|
||||
/// The allocation is aligned to 32 bytes.
|
||||
///
|
||||
/// This emulates the EVM linear memory until the runtime supports metered memory.
|
||||
pub fn build_sbrk(
|
||||
&self,
|
||||
offset: inkwell::values::IntValue<'ctx>,
|
||||
size: inkwell::values::IntValue<'ctx>,
|
||||
) -> anyhow::Result<inkwell::values::PointerValue<'ctx>> {
|
||||
Ok(self
|
||||
.builder()
|
||||
.build_call(
|
||||
self.runtime_api_method(runtime_api::SBRK),
|
||||
&[size.into()],
|
||||
self.runtime_api_method(revive_runtime_api::polkavm_imports::SBRK),
|
||||
&[offset.into(), size.into()],
|
||||
"call_sbrk",
|
||||
)?
|
||||
.try_as_basic_value()
|
||||
@@ -1088,14 +1083,29 @@ where
|
||||
.into_pointer_value())
|
||||
}
|
||||
|
||||
/// Call PolkaVM `sbrk` for extending the heap by `size`,
|
||||
/// Build a call to PolkaVM `msize` for querying the linear memory size.
|
||||
pub fn build_msize(&self) -> anyhow::Result<inkwell::values::IntValue<'ctx>> {
|
||||
Ok(self
|
||||
.builder()
|
||||
.build_call(
|
||||
self.runtime_api_method(revive_runtime_api::polkavm_imports::MEMORY_SIZE),
|
||||
&[],
|
||||
"call_msize",
|
||||
)?
|
||||
.try_as_basic_value()
|
||||
.left()
|
||||
.expect("sbrk returns an int")
|
||||
.into_int_value())
|
||||
}
|
||||
|
||||
/// Call PolkaVM `sbrk` for extending the heap by `offset` + `size`,
|
||||
/// trapping the contract if the call failed.
|
||||
/// Returns the end of memory pointer.
|
||||
pub fn build_heap_alloc(
|
||||
&self,
|
||||
offset: inkwell::values::IntValue<'ctx>,
|
||||
size: inkwell::values::IntValue<'ctx>,
|
||||
) -> anyhow::Result<inkwell::values::PointerValue<'ctx>> {
|
||||
let end_of_memory = self.build_sbrk(size)?;
|
||||
) -> anyhow::Result<()> {
|
||||
let end_of_memory = self.build_sbrk(offset, size)?;
|
||||
let return_is_nil = self.builder().build_int_compare(
|
||||
inkwell::IntPredicate::EQ,
|
||||
end_of_memory,
|
||||
@@ -1113,7 +1123,7 @@ where
|
||||
|
||||
self.set_basic_block(continue_block);
|
||||
|
||||
Ok(end_of_memory)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a pointer to `offset` into the heap, allocating
|
||||
@@ -1128,40 +1138,12 @@ where
|
||||
assert_eq!(offset.get_type(), self.xlen_type());
|
||||
assert_eq!(length.get_type(), self.xlen_type());
|
||||
|
||||
self.build_heap_alloc(offset, length)?;
|
||||
|
||||
let heap_start = self
|
||||
.get_global(crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
let heap_end = self.build_sbrk(self.integer_const(crate::polkavm::XLEN, 0))?;
|
||||
let value_end = self.build_gep(
|
||||
Pointer::new(self.byte_type(), AddressSpace::Stack, heap_start),
|
||||
&[self.builder().build_int_nuw_add(offset, length, "end")?],
|
||||
self.byte_type(),
|
||||
"heap_end_gep",
|
||||
);
|
||||
let is_out_of_bounds = self.builder().build_int_compare(
|
||||
inkwell::IntPredicate::UGT,
|
||||
value_end.value,
|
||||
heap_end,
|
||||
"is_value_overflowing_heap",
|
||||
)?;
|
||||
|
||||
let out_of_bounds_block = self.append_basic_block("heap_offset_out_of_bounds");
|
||||
let heap_offset_block = self.append_basic_block("build_heap_pointer");
|
||||
self.build_conditional_branch(is_out_of_bounds, out_of_bounds_block, heap_offset_block)?;
|
||||
|
||||
self.set_basic_block(out_of_bounds_block);
|
||||
let size = self.builder().build_int_nuw_sub(
|
||||
self.builder()
|
||||
.build_ptr_to_int(value_end.value, self.xlen_type(), "value_end")?,
|
||||
self.builder()
|
||||
.build_ptr_to_int(heap_end, self.xlen_type(), "heap_end")?,
|
||||
"heap_alloc_size",
|
||||
)?;
|
||||
self.build_heap_alloc(size)?;
|
||||
self.build_unconditional_branch(heap_offset_block);
|
||||
|
||||
self.set_basic_block(heap_offset_block);
|
||||
Ok(self.build_gep(
|
||||
Pointer::new(self.byte_type(), AddressSpace::Stack, heap_start),
|
||||
&[offset],
|
||||
@@ -1233,7 +1215,7 @@ where
|
||||
self.llvm.custom_width_int_type(crate::polkavm::XLEN as u32)
|
||||
}
|
||||
|
||||
/// Returns the register witdh sized type.
|
||||
/// Returns the sentinel pointer value.
|
||||
pub fn sentinel_pointer(&self) -> Pointer<'ctx> {
|
||||
let sentinel_pointer = self
|
||||
.xlen_type()
|
||||
@@ -1282,12 +1264,11 @@ where
|
||||
&self,
|
||||
argument_types: Vec<T>,
|
||||
return_values_size: usize,
|
||||
is_near_call_abi: bool,
|
||||
) -> inkwell::types::FunctionType<'ctx>
|
||||
where
|
||||
T: BasicType<'ctx>,
|
||||
{
|
||||
let mut argument_types: Vec<inkwell::types::BasicMetadataTypeEnum> = argument_types
|
||||
let argument_types: Vec<inkwell::types::BasicMetadataTypeEnum> = argument_types
|
||||
.as_slice()
|
||||
.iter()
|
||||
.map(T::as_basic_type_enum)
|
||||
@@ -1299,11 +1280,6 @@ where
|
||||
.void_type()
|
||||
.fn_type(argument_types.as_slice(), false),
|
||||
1 => self.word_type().fn_type(argument_types.as_slice(), false),
|
||||
_size if is_near_call_abi && self.is_system_mode() => {
|
||||
let return_type = self.llvm().ptr_type(AddressSpace::Stack.into());
|
||||
argument_types.insert(0, return_type.as_basic_type_enum().into());
|
||||
return_type.fn_type(argument_types.as_slice(), false)
|
||||
}
|
||||
size => self
|
||||
.structure_type(vec![self.word_type().as_basic_type_enum(); size].as_slice())
|
||||
.fn_type(argument_types.as_slice(), false),
|
||||
@@ -1496,12 +1472,4 @@ where
|
||||
anyhow::bail!("The immutable size data is not available");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the system mode is enabled.
|
||||
pub fn is_system_mode(&self) -> bool {
|
||||
self.yul_data
|
||||
.as_ref()
|
||||
.map(|data| data.is_system_mode())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ impl SolidityData {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Returns the current number of immutables values in the contract.
|
||||
/// Returns the current size of immutable values in the contract.
|
||||
pub fn immutables_size(&self) -> usize {
|
||||
self.immutables.len() * revive_common::BYTE_LENGTH_WORD
|
||||
}
|
||||
|
||||
@@ -8,28 +8,12 @@ use num::Zero;
|
||||
/// Describes some data that is only relevant to Yul.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct YulData {
|
||||
/// The system mode flag.
|
||||
/// The call simulations only work if this mode is enabled.
|
||||
is_system_mode: bool,
|
||||
/// The list of constant arrays in the code section.
|
||||
/// It is a temporary storage used until the finalization method is called.
|
||||
const_arrays: BTreeMap<u8, Vec<num::BigUint>>,
|
||||
}
|
||||
|
||||
impl YulData {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(is_system_mode: bool) -> Self {
|
||||
Self {
|
||||
is_system_mode,
|
||||
const_arrays: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the system mode is enabled.
|
||||
pub fn is_system_mode(&self) -> bool {
|
||||
self.is_system_mode
|
||||
}
|
||||
|
||||
/// Declares a temporary constant array representation.
|
||||
pub fn const_array_declare(&mut self, index: u8, size: u16) -> anyhow::Result<()> {
|
||||
if self.const_arrays.contains_key(&index) {
|
||||
|
||||
@@ -5,18 +5,15 @@ use inkwell::values::BasicValue;
|
||||
use crate::polkavm::context::argument::Argument;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
static STATIC_CALL_FLAG: u32 = 0b0001_0000;
|
||||
const STATIC_CALL_FLAG: u32 = 0b0001_0000;
|
||||
const REENTRANT_CALL_FLAG: u32 = 0b0000_1000;
|
||||
|
||||
/// Translates a contract call.
|
||||
///
|
||||
/// If the `simulation_address` is specified, the call is
|
||||
/// substituted with another instruction according to the specification.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn call<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
gas: inkwell::values::IntValue<'ctx>,
|
||||
_gas: inkwell::values::IntValue<'ctx>,
|
||||
address: inkwell::values::IntValue<'ctx>,
|
||||
value: Option<inkwell::values::IntValue<'ctx>>,
|
||||
input_offset: inkwell::values::IntValue<'ctx>,
|
||||
@@ -29,59 +26,64 @@ pub fn call<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let address_pointer = context.build_alloca(context.word_type(), "address_ptr");
|
||||
context.build_store(address_pointer, address)?;
|
||||
let address_pointer = context.build_address_argument_store(address)?;
|
||||
|
||||
let value_pointer = if let Some(value) = value {
|
||||
let value_pointer = context.build_alloca(context.value_type(), "value");
|
||||
context.build_store(value_pointer, value)?;
|
||||
value_pointer
|
||||
} else {
|
||||
context.sentinel_pointer()
|
||||
};
|
||||
let value = value.unwrap_or_else(|| context.word_const(0));
|
||||
let value_pointer = context.build_alloca_at_entry(context.word_type(), "value_pointer");
|
||||
context.build_store(value_pointer, value)?;
|
||||
|
||||
let input_offset = context.safe_truncate_int_to_xlen(input_offset)?;
|
||||
let input_length = context.safe_truncate_int_to_xlen(input_length)?;
|
||||
let output_offset = context.safe_truncate_int_to_xlen(output_offset)?;
|
||||
let output_length = context.safe_truncate_int_to_xlen(output_length)?;
|
||||
|
||||
let gas = context
|
||||
// TODO: What to supply here? Is there a weight to gas?
|
||||
let _gas = context
|
||||
.builder()
|
||||
.build_int_truncate(gas, context.integer_type(64), "gas")?;
|
||||
|
||||
let flags = if static_call { STATIC_CALL_FLAG } else { 0 };
|
||||
.build_int_truncate(_gas, context.integer_type(64), "gas")?;
|
||||
|
||||
let input_pointer = context.build_heap_gep(input_offset, input_length)?;
|
||||
let output_pointer = context.build_heap_gep(output_offset, output_length)?;
|
||||
|
||||
let output_length_pointer = context.get_global(crate::polkavm::GLOBAL_RETURN_DATA_SIZE)?;
|
||||
context.build_store(output_length_pointer.into(), output_length)?;
|
||||
let output_length_pointer = context.build_alloca_at_entry(context.xlen_type(), "output_length");
|
||||
context.build_store(output_length_pointer, output_length)?;
|
||||
|
||||
let argument_pointer = pallet_contracts_pvm_llapi::calling_convention::Spill::new(
|
||||
let flags = if static_call {
|
||||
REENTRANT_CALL_FLAG | STATIC_CALL_FLAG
|
||||
} else {
|
||||
REENTRANT_CALL_FLAG
|
||||
};
|
||||
let flags = context.xlen_type().const_int(flags as u64, false);
|
||||
|
||||
let argument_type = revive_runtime_api::calling_convention::call(context.llvm());
|
||||
let argument_pointer = context.build_alloca_at_entry(argument_type, "call_arguments");
|
||||
let arguments = &[
|
||||
flags.as_basic_value_enum(),
|
||||
address_pointer.value.as_basic_value_enum(),
|
||||
context.integer_const(64, 0).as_basic_value_enum(),
|
||||
context.integer_const(64, 0).as_basic_value_enum(),
|
||||
context.sentinel_pointer().value.as_basic_value_enum(),
|
||||
value_pointer.value.as_basic_value_enum(),
|
||||
input_pointer.value.as_basic_value_enum(),
|
||||
input_length.as_basic_value_enum(),
|
||||
output_pointer.value.as_basic_value_enum(),
|
||||
output_length_pointer.value.as_basic_value_enum(),
|
||||
];
|
||||
revive_runtime_api::calling_convention::spill(
|
||||
context.builder(),
|
||||
pallet_contracts_pvm_llapi::calling_convention::call(context.llvm()),
|
||||
"call_arguments",
|
||||
)?
|
||||
.next(context.xlen_type().const_int(flags as u64, false))?
|
||||
.next(address_pointer.value)?
|
||||
.next(gas)?
|
||||
.skip()
|
||||
.next(context.sentinel_pointer().value)?
|
||||
.next(value_pointer.value)?
|
||||
.next(input_pointer.value)?
|
||||
.next(input_length)?
|
||||
.next(output_pointer.value)?
|
||||
.next(output_length_pointer.value)?
|
||||
.done();
|
||||
argument_pointer.value,
|
||||
argument_type,
|
||||
arguments,
|
||||
)?;
|
||||
|
||||
let name = runtime_api::imports::CALL;
|
||||
let arguments = context.builder().build_ptr_to_int(
|
||||
argument_pointer,
|
||||
let name = revive_runtime_api::polkavm_imports::CALL;
|
||||
let argument_pointer = context.builder().build_ptr_to_int(
|
||||
argument_pointer.value,
|
||||
context.xlen_type(),
|
||||
"argument_pointer",
|
||||
"call_argument_pointer",
|
||||
)?;
|
||||
let success = context
|
||||
.build_runtime_call(name, &[arguments.into()])
|
||||
.build_runtime_call(name, &[argument_pointer.into()])
|
||||
.unwrap_or_else(|| panic!("{name} should return a value"))
|
||||
.into_int_value();
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
/// Translates the `gas_limit` instruction.
|
||||
pub fn gas_limit<'ctx, D>(
|
||||
@@ -28,22 +27,29 @@ where
|
||||
|
||||
/// Translates the `tx.origin` instruction.
|
||||
pub fn origin<'ctx, D>(
|
||||
_context: &mut Context<'ctx, D>,
|
||||
context: &mut Context<'ctx, D>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
todo!()
|
||||
let address_type = context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS);
|
||||
let address_pointer = context.build_alloca_at_entry(address_type, "origin_address");
|
||||
context.build_store(address_pointer, address_type.const_zero())?;
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::ORIGIN,
|
||||
&[address_pointer.to_int(context).into()],
|
||||
);
|
||||
context.build_load_address(address_pointer)
|
||||
}
|
||||
|
||||
/// Translates the `chain_id` instruction.
|
||||
pub fn chain_id<'ctx, D>(
|
||||
_context: &mut Context<'ctx, D>,
|
||||
context: &mut Context<'ctx, D>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
todo!()
|
||||
context.build_runtime_call_to_getter(revive_runtime_api::polkavm_imports::CHAIN_ID)
|
||||
}
|
||||
|
||||
/// Translates the `block_number` instruction.
|
||||
@@ -53,22 +59,7 @@ pub fn block_number<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let (output_pointer, output_length_pointer) = context.build_stack_parameter(
|
||||
revive_common::BIT_LENGTH_BLOCK_NUMBER,
|
||||
"block_timestamp_output",
|
||||
);
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::BLOCK_NUMBER,
|
||||
&[
|
||||
output_pointer.to_int(context).into(),
|
||||
output_length_pointer.to_int(context).into(),
|
||||
],
|
||||
);
|
||||
context.build_load_word(
|
||||
output_pointer,
|
||||
revive_common::BIT_LENGTH_BLOCK_NUMBER,
|
||||
"block_number",
|
||||
)
|
||||
context.build_runtime_call_to_getter(revive_runtime_api::polkavm_imports::BLOCK_NUMBER)
|
||||
}
|
||||
|
||||
/// Translates the `block_timestamp` instruction.
|
||||
@@ -78,22 +69,7 @@ pub fn block_timestamp<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let (output_pointer, output_length_pointer) = context.build_stack_parameter(
|
||||
revive_common::BIT_LENGTH_BLOCK_TIMESTAMP,
|
||||
"block_timestamp_output",
|
||||
);
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::NOW,
|
||||
&[
|
||||
output_pointer.to_int(context).into(),
|
||||
output_length_pointer.to_int(context).into(),
|
||||
],
|
||||
);
|
||||
context.build_load_word(
|
||||
output_pointer,
|
||||
revive_common::BIT_LENGTH_BLOCK_TIMESTAMP,
|
||||
"block_timestamp",
|
||||
)
|
||||
context.build_runtime_call_to_getter(revive_runtime_api::polkavm_imports::NOW)
|
||||
}
|
||||
|
||||
/// Translates the `block_hash` instruction.
|
||||
@@ -137,33 +113,6 @@ where
|
||||
Ok(context.word_const(0).as_basic_value_enum())
|
||||
}
|
||||
|
||||
/// Translates the `msize` instruction.
|
||||
pub fn msize<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let heap_end = context.build_sbrk(context.xlen_type().const_zero())?;
|
||||
let heap_start = context
|
||||
.get_global(crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
let heap_size = context.builder().build_int_nuw_sub(
|
||||
context
|
||||
.builder()
|
||||
.build_ptr_to_int(heap_end, context.xlen_type(), "heap_end")?,
|
||||
context
|
||||
.builder()
|
||||
.build_ptr_to_int(heap_start, context.xlen_type(), "heap_start")?,
|
||||
"heap_size",
|
||||
)?;
|
||||
Ok(context
|
||||
.builder()
|
||||
.build_int_z_extend(heap_size, context.word_type(), "heap_size_extended")?
|
||||
.as_basic_value_enum())
|
||||
}
|
||||
|
||||
/// Translates the `address` instruction.
|
||||
pub fn address<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
@@ -171,20 +120,15 @@ pub fn address<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let (output_pointer, output_length_pointer) =
|
||||
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "address_output");
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::ADDRESS,
|
||||
&[
|
||||
output_pointer.to_int(context).into(),
|
||||
output_length_pointer.to_int(context).into(),
|
||||
],
|
||||
let pointer = context.build_alloca_at_entry(
|
||||
context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS),
|
||||
"address_output",
|
||||
);
|
||||
let value = context.build_byte_swap(context.build_load(output_pointer, "address")?)?;
|
||||
Ok(context
|
||||
.builder()
|
||||
.build_int_z_extend(value.into_int_value(), context.word_type(), "address_zext")?
|
||||
.into())
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::ADDRESS,
|
||||
&[pointer.to_int(context).into()],
|
||||
);
|
||||
context.build_load_address(pointer)
|
||||
}
|
||||
|
||||
/// Translates the `caller` instruction.
|
||||
@@ -194,18 +138,13 @@ pub fn caller<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let (output_pointer, output_length_pointer) =
|
||||
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "caller_output");
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::CALLER,
|
||||
&[
|
||||
output_pointer.to_int(context).into(),
|
||||
output_length_pointer.to_int(context).into(),
|
||||
],
|
||||
let pointer = context.build_alloca_at_entry(
|
||||
context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS),
|
||||
"address_output",
|
||||
);
|
||||
let value = context.build_byte_swap(context.build_load(output_pointer, "caller")?)?;
|
||||
Ok(context
|
||||
.builder()
|
||||
.build_int_z_extend(value.into_int_value(), context.word_type(), "caller_zext")?
|
||||
.into())
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::CALLER,
|
||||
&[pointer.to_int(context).into()],
|
||||
);
|
||||
context.build_load_address(pointer)
|
||||
}
|
||||
|
||||
@@ -7,28 +7,15 @@ use crate::polkavm::context::argument::Argument;
|
||||
use crate::polkavm::context::code_type::CodeType;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
/// Translates the contract `create` instruction.
|
||||
/// The instruction is simulated by a call to a system contract.
|
||||
/// Translates the contract `create` and `create2` instruction.
|
||||
///
|
||||
/// A `salt` value of `None` is equivalent to `create1`.
|
||||
pub fn create<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
value: inkwell::values::IntValue<'ctx>,
|
||||
input_offset: inkwell::values::IntValue<'ctx>,
|
||||
input_length: inkwell::values::IntValue<'ctx>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
self::create2(context, value, input_offset, input_length, None)
|
||||
}
|
||||
|
||||
/// Translates the contract `create2` instruction.
|
||||
pub fn create2<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
value: inkwell::values::IntValue<'ctx>,
|
||||
input_offset: inkwell::values::IntValue<'ctx>,
|
||||
input_length: inkwell::values::IntValue<'ctx>,
|
||||
salt: Option<inkwell::values::IntValue<'ctx>>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
@@ -37,9 +24,6 @@ where
|
||||
let input_offset = context.safe_truncate_int_to_xlen(input_offset)?;
|
||||
let input_length = context.safe_truncate_int_to_xlen(input_length)?;
|
||||
|
||||
let value_pointer = context.build_alloca(context.value_type(), "value");
|
||||
context.build_store(value_pointer, value)?;
|
||||
|
||||
let code_hash_pointer = context.build_heap_gep(input_offset, input_length)?;
|
||||
|
||||
let input_data_pointer = context.build_gep(
|
||||
@@ -48,53 +32,68 @@ where
|
||||
.xlen_type()
|
||||
.const_int(revive_common::BYTE_LENGTH_WORD as u64, false)],
|
||||
context.byte_type(),
|
||||
"value_ptr_parameter_offset",
|
||||
"input_ptr_parameter_offset",
|
||||
);
|
||||
|
||||
let salt_pointer = context.build_alloca(context.word_type(), "salt");
|
||||
context.build_store(salt_pointer, salt.unwrap_or_else(|| context.word_const(0)))?;
|
||||
let value_pointer = context.build_alloca_at_entry(context.value_type(), "transferred_value");
|
||||
context.build_store(value_pointer, value)?;
|
||||
|
||||
let (address_pointer, address_length_pointer) =
|
||||
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "address_pointer");
|
||||
let salt_pointer = match salt {
|
||||
Some(salt) => {
|
||||
let salt_pointer = context.build_alloca_at_entry(context.word_type(), "salt_pointer");
|
||||
context.build_store(salt_pointer, salt)?;
|
||||
salt_pointer
|
||||
}
|
||||
None => context.sentinel_pointer(),
|
||||
};
|
||||
|
||||
let address_pointer = context.build_alloca_at_entry(
|
||||
context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS),
|
||||
"address_pointer",
|
||||
);
|
||||
context.build_store(address_pointer, context.word_const(0))?;
|
||||
|
||||
let argument_pointer = pallet_contracts_pvm_llapi::calling_convention::Spill::new(
|
||||
let argument_type = revive_runtime_api::calling_convention::instantiate(context.llvm());
|
||||
let argument_pointer = context.build_alloca_at_entry(argument_type, "instantiate_arguments");
|
||||
let arguments = &[
|
||||
code_hash_pointer.value.as_basic_value_enum(),
|
||||
context.integer_const(64, 0).as_basic_value_enum(),
|
||||
context.integer_const(64, 0).as_basic_value_enum(),
|
||||
context.sentinel_pointer().value.as_basic_value_enum(),
|
||||
value_pointer.value.as_basic_value_enum(),
|
||||
input_data_pointer.value.as_basic_value_enum(),
|
||||
input_length.as_basic_value_enum(),
|
||||
address_pointer.value.as_basic_value_enum(),
|
||||
context.sentinel_pointer().value.as_basic_value_enum(),
|
||||
context.sentinel_pointer().value.as_basic_value_enum(),
|
||||
salt_pointer.value.as_basic_value_enum(),
|
||||
];
|
||||
revive_runtime_api::calling_convention::spill(
|
||||
context.builder(),
|
||||
pallet_contracts_pvm_llapi::calling_convention::instantiate(context.llvm()),
|
||||
"create2_arguments",
|
||||
)?
|
||||
.next(code_hash_pointer.value)?
|
||||
.skip()
|
||||
.skip()
|
||||
.next(context.sentinel_pointer().value)?
|
||||
.next(value_pointer.value)?
|
||||
.next(input_data_pointer.value)?
|
||||
.next(input_length)?
|
||||
.next(address_pointer.value)?
|
||||
.next(address_length_pointer.value)?
|
||||
.next(context.sentinel_pointer().value)?
|
||||
.next(context.sentinel_pointer().value)?
|
||||
.next(salt_pointer.value)?
|
||||
.next(
|
||||
context
|
||||
.xlen_type()
|
||||
.const_int(revive_common::BYTE_LENGTH_WORD as u64, false),
|
||||
)?
|
||||
.done();
|
||||
argument_pointer.value,
|
||||
argument_type,
|
||||
arguments,
|
||||
)?;
|
||||
|
||||
let argument_pointer = context.builder().build_ptr_to_int(
|
||||
argument_pointer.value,
|
||||
context.xlen_type(),
|
||||
"instantiate_argument_pointer",
|
||||
)?;
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::INSTANTIATE,
|
||||
&[context
|
||||
.builder()
|
||||
.build_ptr_to_int(argument_pointer, context.xlen_type(), "argument_pointer")?
|
||||
.into()],
|
||||
revive_runtime_api::polkavm_imports::INSTANTIATE,
|
||||
&[argument_pointer.into()],
|
||||
);
|
||||
|
||||
context.build_load_word(
|
||||
address_pointer,
|
||||
revive_common::BIT_LENGTH_ETH_ADDRESS,
|
||||
"address",
|
||||
)
|
||||
let address = context.build_byte_swap(context.build_load(address_pointer, "address")?)?;
|
||||
Ok(context
|
||||
.builder()
|
||||
.build_int_z_extend(
|
||||
address.into_int_value(),
|
||||
context.word_type(),
|
||||
"address_zext",
|
||||
)?
|
||||
.into())
|
||||
}
|
||||
|
||||
/// Translates the contract hash instruction, which is actually used to set the hash of the contract
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
/// Translates the `sha3` instruction.
|
||||
pub fn sha3<'ctx, D>(
|
||||
@@ -19,7 +18,7 @@ where
|
||||
let output_pointer = context.build_alloca(context.word_type(), "output_pointer");
|
||||
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::HASH_KECCAK_256,
|
||||
revive_runtime_api::polkavm_imports::HASH_KECCAK_256,
|
||||
&[
|
||||
input_pointer.to_int(context).into(),
|
||||
length_casted.into(),
|
||||
|
||||
@@ -4,7 +4,6 @@ use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
/// Translates the `gas` instruction.
|
||||
pub fn gas<'ctx, D>(
|
||||
@@ -23,20 +22,13 @@ pub fn value<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let (output_pointer, output_length_pointer) =
|
||||
context.build_stack_parameter(revive_common::BIT_LENGTH_VALUE, "value_transferred_output");
|
||||
let output_pointer = context.build_alloca(context.value_type(), "value_transferred");
|
||||
context.build_store(output_pointer, context.word_const(0))?;
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::VALUE_TRANSFERRED,
|
||||
&[
|
||||
output_pointer.to_int(context).into(),
|
||||
output_length_pointer.to_int(context).into(),
|
||||
],
|
||||
revive_runtime_api::polkavm_imports::VALUE_TRANSFERRED,
|
||||
&[output_pointer.to_int(context).into()],
|
||||
);
|
||||
context.build_load_word(
|
||||
output_pointer,
|
||||
revive_common::BIT_LENGTH_VALUE,
|
||||
"value_transferred",
|
||||
)
|
||||
context.build_load(output_pointer, "value_transferred")
|
||||
}
|
||||
|
||||
/// Translates the `balance` instructions.
|
||||
@@ -47,24 +39,40 @@ pub fn balance<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let balance_pointer = context.build_alloca(context.word_type(), "balance_pointer");
|
||||
let address_pointer = context.build_alloca(context.word_type(), "address_pointer");
|
||||
context.build_store(address_pointer, address)?;
|
||||
let address_pointer = context.build_address_argument_store(address)?;
|
||||
|
||||
let balance_pointer = context.build_alloca(context.word_type(), "balance_pointer");
|
||||
let balance = context.builder().build_ptr_to_int(
|
||||
balance_pointer.value,
|
||||
context.xlen_type(),
|
||||
"balance",
|
||||
)?;
|
||||
let address = context.builder().build_ptr_to_int(
|
||||
address_pointer.value,
|
||||
context.xlen_type(),
|
||||
"address",
|
||||
)?;
|
||||
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::BALANCE,
|
||||
&[address.into(), balance.into()],
|
||||
revive_runtime_api::polkavm_imports::BALANCE_OF,
|
||||
&[address_pointer.to_int(context).into(), balance.into()],
|
||||
);
|
||||
|
||||
context.build_load(balance_pointer, "balance")
|
||||
}
|
||||
|
||||
/// Translates the `selfbalance` instructions.
|
||||
pub fn self_balance<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let balance_pointer = context.build_alloca(context.word_type(), "balance_pointer");
|
||||
let balance = context.builder().build_ptr_to_int(
|
||||
balance_pointer.value,
|
||||
context.xlen_type(),
|
||||
"balance",
|
||||
)?;
|
||||
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::BALANCE,
|
||||
&[balance.into()],
|
||||
);
|
||||
|
||||
context.build_load(balance_pointer, "balance")
|
||||
|
||||
@@ -4,7 +4,6 @@ use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
/// Translates a log or event call.
|
||||
///
|
||||
@@ -43,6 +42,7 @@ where
|
||||
context.byte_type().array_type(topics_buffer_size as u32),
|
||||
"topics_buffer",
|
||||
);
|
||||
|
||||
for (n, topic) in topics.iter().enumerate() {
|
||||
let topic_buffer_offset = context
|
||||
.xlen_type()
|
||||
@@ -57,6 +57,7 @@ where
|
||||
context.build_byte_swap(topic.as_basic_value_enum())?,
|
||||
)?;
|
||||
}
|
||||
|
||||
[
|
||||
context
|
||||
.builder()
|
||||
@@ -68,14 +69,17 @@ where
|
||||
.as_basic_value_enum(),
|
||||
context
|
||||
.xlen_type()
|
||||
.const_int(topics_buffer_size as u64, false)
|
||||
.const_int(topics.len() as u64, false)
|
||||
.as_basic_value_enum(),
|
||||
input_pointer.as_basic_value_enum(),
|
||||
input_length.as_basic_value_enum(),
|
||||
]
|
||||
};
|
||||
|
||||
let _ = context.build_runtime_call(runtime_api::imports::DEPOSIT_EVENT, &arguments);
|
||||
let _ = context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::DEPOSIT_EVENT,
|
||||
&arguments,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
//! Translates the external code operations.
|
||||
|
||||
use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
/// Translates the `extcodesize` instruction if `address` is `Some`.
|
||||
/// Otherwise, translates the `codesize` instruction.
|
||||
@@ -15,41 +12,52 @@ pub fn size<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let address_pointer = match address {
|
||||
Some(address) => {
|
||||
let address_pointer = context.build_alloca(context.word_type(), "value");
|
||||
context.build_store(address_pointer, address)?;
|
||||
address_pointer
|
||||
}
|
||||
None => context.sentinel_pointer(),
|
||||
let address = match address {
|
||||
Some(address) => address,
|
||||
None => super::context::address(context)?.into_int_value(),
|
||||
};
|
||||
|
||||
let address_pointer_casted = context.builder().build_ptr_to_int(
|
||||
address_pointer.value,
|
||||
context.xlen_type(),
|
||||
"address_pointer",
|
||||
)?;
|
||||
let value = context
|
||||
.build_runtime_call(
|
||||
runtime_api::imports::CODE_SIZE,
|
||||
&[address_pointer_casted.into()],
|
||||
)
|
||||
.unwrap_or_else(|| panic!("{} should return a value", runtime_api::imports::CODE_SIZE))
|
||||
.into_int_value();
|
||||
let address_pointer = context.build_address_argument_store(address)?;
|
||||
let output_pointer = context.build_alloca_at_entry(context.word_type(), "output_pointer");
|
||||
|
||||
Ok(context
|
||||
.builder()
|
||||
.build_int_z_extend(value, context.word_type(), "extcodesize")?
|
||||
.as_basic_value_enum())
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::CODE_SIZE,
|
||||
&[
|
||||
address_pointer.to_int(context).into(),
|
||||
output_pointer.to_int(context).into(),
|
||||
],
|
||||
);
|
||||
|
||||
context.build_load(output_pointer, "code_size")
|
||||
}
|
||||
|
||||
/// Translates the `extcodehash` instruction.
|
||||
pub fn hash<'ctx, D>(
|
||||
_context: &mut Context<'ctx, D>,
|
||||
_address: inkwell::values::IntValue<'ctx>,
|
||||
context: &mut Context<'ctx, D>,
|
||||
address: inkwell::values::IntValue<'ctx>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
todo!()
|
||||
let address_type = context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS);
|
||||
let address_pointer = context.build_alloca_at_entry(address_type, "address_pointer");
|
||||
let address_truncated =
|
||||
context
|
||||
.builder()
|
||||
.build_int_truncate(address, address_type, "address_truncated")?;
|
||||
let address_swapped = context.build_byte_swap(address_truncated.into())?;
|
||||
context.build_store(address_pointer, address_swapped)?;
|
||||
|
||||
let extcodehash_pointer =
|
||||
context.build_alloca_at_entry(context.word_type(), "extcodehash_pointer");
|
||||
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::CODE_HASH,
|
||||
&[
|
||||
address_pointer.to_int(context).into(),
|
||||
extcodehash_pointer.to_int(context).into(),
|
||||
],
|
||||
);
|
||||
|
||||
context.build_byte_swap(context.build_load(extcodehash_pointer, "extcodehash_value")?)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
//! Translates the contract immutable operations.
|
||||
|
||||
use inkwell::types::BasicType;
|
||||
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::code_type::CodeType;
|
||||
use crate::polkavm::context::function::runtime;
|
||||
use crate::polkavm::context::pointer::Pointer;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
|
||||
/// Translates the contract immutable load.
|
||||
/// In the deploy code the values are read from the auxiliary heap.
|
||||
/// In the runtime code they are requested from the system contract.
|
||||
///
|
||||
/// In deploy code the values are read from the stack.
|
||||
///
|
||||
/// In runtime code they are loaded lazily with the `get_immutable_data` syscall.
|
||||
pub fn load<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
index: inkwell::values::IntValue<'ctx>,
|
||||
@@ -20,38 +25,27 @@ where
|
||||
None => {
|
||||
anyhow::bail!("Immutables are not available if the contract part is undefined");
|
||||
}
|
||||
Some(CodeType::Deploy) => {
|
||||
let index_double = context.builder().build_int_mul(
|
||||
index,
|
||||
context.word_const(2),
|
||||
"immutable_load_index_double",
|
||||
)?;
|
||||
let offset_absolute = context.builder().build_int_add(
|
||||
index_double,
|
||||
context.word_const(
|
||||
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA
|
||||
+ (3 * revive_common::BYTE_LENGTH_WORD) as u64,
|
||||
),
|
||||
"immutable_offset_absolute",
|
||||
)?;
|
||||
let immutable_pointer = Pointer::new_with_offset(
|
||||
context,
|
||||
AddressSpace::default(),
|
||||
context.word_type(),
|
||||
offset_absolute,
|
||||
"immutable_pointer",
|
||||
);
|
||||
context.build_load(immutable_pointer, "immutable_value")
|
||||
}
|
||||
Some(CodeType::Deploy) => load_from_memory(context, index),
|
||||
Some(CodeType::Runtime) => {
|
||||
todo!()
|
||||
context.build_call(
|
||||
context
|
||||
.get_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
|
||||
.expect("is always declared for runtime code")
|
||||
.borrow()
|
||||
.declaration(),
|
||||
&[],
|
||||
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
|
||||
);
|
||||
load_from_memory(context, index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates the contract immutable store.
|
||||
/// In the deploy code the values are written to the auxiliary heap at the predefined offset,
|
||||
/// being prepared for returning to the system contract for saving.
|
||||
///
|
||||
/// In deploy code the values are written to the stack at the predefined offset,
|
||||
/// being prepared for storing them using the `set_immutable_data` syscall.
|
||||
///
|
||||
/// Ignored in the runtime code.
|
||||
pub fn store<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
@@ -66,46 +60,48 @@ where
|
||||
anyhow::bail!("Immutables are not available if the contract part is undefined");
|
||||
}
|
||||
Some(CodeType::Deploy) => {
|
||||
let index_double = context.builder().build_int_mul(
|
||||
index,
|
||||
context.word_const(2),
|
||||
"immutable_load_index_double",
|
||||
)?;
|
||||
let index_offset_absolute = context.builder().build_int_add(
|
||||
index_double,
|
||||
context.word_const(
|
||||
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA
|
||||
+ (2 * revive_common::BYTE_LENGTH_WORD) as u64,
|
||||
let immutable_data_pointer = context
|
||||
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
let immutable_pointer = context.build_gep(
|
||||
Pointer::new(
|
||||
context.word_type(),
|
||||
AddressSpace::Stack,
|
||||
immutable_data_pointer,
|
||||
),
|
||||
"index_offset_absolute",
|
||||
)?;
|
||||
let index_offset_pointer = Pointer::new_with_offset(
|
||||
context,
|
||||
AddressSpace::default(),
|
||||
context.word_type(),
|
||||
index_offset_absolute,
|
||||
"immutable_index_pointer",
|
||||
&[index],
|
||||
context.word_type().as_basic_type_enum(),
|
||||
"immutable_variable_pointer",
|
||||
);
|
||||
context.build_store(index_offset_pointer, index)?;
|
||||
|
||||
let value_offset_absolute = context.builder().build_int_add(
|
||||
index_offset_absolute,
|
||||
context.word_const(revive_common::BYTE_LENGTH_WORD as u64),
|
||||
"value_offset_absolute",
|
||||
)?;
|
||||
let value_offset_pointer = Pointer::new_with_offset(
|
||||
context,
|
||||
AddressSpace::default(),
|
||||
context.word_type(),
|
||||
value_offset_absolute,
|
||||
"immutable_value_pointer",
|
||||
);
|
||||
context.build_store(value_offset_pointer, value)?;
|
||||
|
||||
Ok(())
|
||||
context.build_store(immutable_pointer, value)
|
||||
}
|
||||
Some(CodeType::Runtime) => {
|
||||
anyhow::bail!("Immutable writes are not available in the runtime code");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_from_memory<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
index: inkwell::values::IntValue<'ctx>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let immutable_data_pointer = context
|
||||
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
let immutable_pointer = context.build_gep(
|
||||
Pointer::new(
|
||||
context.word_type(),
|
||||
AddressSpace::Stack,
|
||||
immutable_data_pointer,
|
||||
),
|
||||
&[index],
|
||||
context.word_type().as_basic_type_enum(),
|
||||
"immutable_variable_pointer",
|
||||
);
|
||||
context.build_load(immutable_pointer, "immutable_value")
|
||||
}
|
||||
|
||||
@@ -1,10 +1,29 @@
|
||||
//! Translates the heap memory operations.
|
||||
|
||||
use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::pointer::Pointer;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
|
||||
/// Translates the `msize` instruction.
|
||||
pub fn msize<'ctx, D>(
|
||||
context: &mut Context<'ctx, D>,
|
||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
Ok(context
|
||||
.builder()
|
||||
.build_int_z_extend(
|
||||
context.build_msize()?,
|
||||
context.word_type(),
|
||||
"heap_size_extended",
|
||||
)?
|
||||
.as_basic_value_enum())
|
||||
}
|
||||
|
||||
/// Translates the `mload` instruction.
|
||||
/// Uses the main heap.
|
||||
pub fn load<'ctx, D>(
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! Translates the transaction return operations.
|
||||
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::code_type::CodeType;
|
||||
use crate::polkavm::context::pointer::Pointer;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
|
||||
@@ -12,8 +15,60 @@ pub fn r#return<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
if context.code_type().is_none() {
|
||||
anyhow::bail!("Return is not available if the contract part is undefined");
|
||||
match context.code_type() {
|
||||
None => anyhow::bail!("Return is not available if the contract part is undefined"),
|
||||
Some(CodeType::Deploy) => {
|
||||
let immutable_data_size_pointer = context
|
||||
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
let immutable_data_size = context.build_load(
|
||||
Pointer::new(
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
immutable_data_size_pointer,
|
||||
),
|
||||
"immutable_data_size_load",
|
||||
)?;
|
||||
|
||||
let write_immutable_data_block = context.append_basic_block("write_immutables_block");
|
||||
let join_return_block = context.append_basic_block("join_return_block");
|
||||
let immutable_data_size_is_zero = context.builder().build_int_compare(
|
||||
inkwell::IntPredicate::EQ,
|
||||
context.xlen_type().const_zero(),
|
||||
immutable_data_size.into_int_value(),
|
||||
"immutable_data_size_is_zero",
|
||||
)?;
|
||||
context.build_conditional_branch(
|
||||
immutable_data_size_is_zero,
|
||||
join_return_block,
|
||||
write_immutable_data_block,
|
||||
)?;
|
||||
|
||||
context.set_basic_block(write_immutable_data_block);
|
||||
let immutable_data_pointer = context
|
||||
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::SET_IMMUTABLE_DATA,
|
||||
&[
|
||||
context
|
||||
.builder()
|
||||
.build_ptr_to_int(
|
||||
immutable_data_pointer,
|
||||
context.xlen_type(),
|
||||
"immutable_data_pointer_to_xlen",
|
||||
)?
|
||||
.into(),
|
||||
immutable_data_size,
|
||||
],
|
||||
);
|
||||
context.build_unconditional_branch(join_return_block);
|
||||
|
||||
context.set_basic_block(join_return_block);
|
||||
}
|
||||
Some(CodeType::Runtime) => {}
|
||||
}
|
||||
|
||||
context.build_exit(
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
//! Translates the return data instructions.
|
||||
|
||||
use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm_const::runtime_api;
|
||||
|
||||
/// Translates the return data size.
|
||||
pub fn size<'ctx, D>(
|
||||
@@ -13,13 +10,17 @@ pub fn size<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let value = context
|
||||
.get_global_value(crate::polkavm::GLOBAL_RETURN_DATA_SIZE)?
|
||||
.into_int_value();
|
||||
Ok(context
|
||||
.builder()
|
||||
.build_int_z_extend(value, context.word_type(), "calldatasize_extended")?
|
||||
.as_basic_value_enum())
|
||||
let output_pointer = context.build_alloca_at_entry(context.word_type(), "return_data_size");
|
||||
let output_pointer_parameter = context.builder().build_ptr_to_int(
|
||||
output_pointer.value,
|
||||
context.xlen_type(),
|
||||
"return_data_copy_output_pointer",
|
||||
)?;
|
||||
context.build_runtime_call(
|
||||
revive_runtime_api::polkavm_imports::RETURNDATASIZE,
|
||||
&[output_pointer_parameter.into()],
|
||||
);
|
||||
context.build_load(output_pointer, "return_data_size_load")
|
||||
}
|
||||
|
||||
/// Translates the return data copy, trapping if
|
||||
@@ -39,16 +40,49 @@ where
|
||||
let destination_offset = context.safe_truncate_int_to_xlen(destination_offset)?;
|
||||
let size = context.safe_truncate_int_to_xlen(size)?;
|
||||
|
||||
let destination_offset = context.builder().build_ptr_to_int(
|
||||
let output_pointer = context.builder().build_ptr_to_int(
|
||||
context.build_heap_gep(destination_offset, size)?.value,
|
||||
context.xlen_type(),
|
||||
"destination_offset",
|
||||
"return_data_copy_output_pointer",
|
||||
)?;
|
||||
|
||||
let output_length_pointer = context.build_alloca_at_entry(
|
||||
context.xlen_type(),
|
||||
"return_data_copy_output_length_pointer",
|
||||
);
|
||||
context.build_store(output_length_pointer, size)?;
|
||||
let output_length_pointer_int = context.builder().build_ptr_to_int(
|
||||
output_length_pointer.value,
|
||||
context.xlen_type(),
|
||||
"return_data_copy_output_length_pointer_int",
|
||||
)?;
|
||||
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::RETURNDATACOPY,
|
||||
&[destination_offset.into(), source_offset.into(), size.into()],
|
||||
revive_runtime_api::polkavm_imports::RETURNDATACOPY,
|
||||
&[
|
||||
output_pointer.into(),
|
||||
output_length_pointer_int.into(),
|
||||
source_offset.into(),
|
||||
],
|
||||
);
|
||||
|
||||
// Trap on OOB (will be different in EOF code)
|
||||
let overflow_block = context.append_basic_block("return_data_overflow");
|
||||
let non_overflow_block = context.append_basic_block("return_data_non_overflow");
|
||||
let is_overflow = context.builder().build_int_compare(
|
||||
inkwell::IntPredicate::UGT,
|
||||
size,
|
||||
context
|
||||
.build_load(output_length_pointer, "bytes_written")?
|
||||
.into_int_value(),
|
||||
"is_overflow",
|
||||
)?;
|
||||
context.build_conditional_branch(is_overflow, overflow_block, non_overflow_block)?;
|
||||
|
||||
context.set_basic_block(overflow_block);
|
||||
context.build_call(context.intrinsics().trap, &[], "invalid_trap");
|
||||
context.build_unreachable();
|
||||
|
||||
context.set_basic_block(non_overflow_block);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Translates the storage operations.
|
||||
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::pointer::Pointer;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
|
||||
@@ -13,14 +12,10 @@ pub fn load<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let position_pointer = Pointer::new_with_offset(
|
||||
context,
|
||||
AddressSpace::Storage,
|
||||
context.word_type(),
|
||||
position,
|
||||
"storage_load_position_pointer",
|
||||
);
|
||||
context.build_load(position_pointer, "storage_load_value")
|
||||
let mut slot_ptr = context.build_alloca_at_entry(context.word_type(), "slot_pointer");
|
||||
slot_ptr.address_space = AddressSpace::Storage;
|
||||
context.builder().build_store(slot_ptr.value, position)?;
|
||||
context.build_load(slot_ptr, "storage_load_value")
|
||||
}
|
||||
|
||||
/// Translates the storage store.
|
||||
@@ -32,14 +27,10 @@ pub fn store<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let position_pointer = Pointer::new_with_offset(
|
||||
context,
|
||||
AddressSpace::Storage,
|
||||
context.word_type(),
|
||||
position,
|
||||
"storage_store_position_pointer",
|
||||
);
|
||||
context.build_store(position_pointer, value)?;
|
||||
let mut slot_ptr = context.build_alloca_at_entry(context.word_type(), "slot_pointer");
|
||||
slot_ptr.address_space = AddressSpace::Storage;
|
||||
context.builder().build_store(slot_ptr.value, position)?;
|
||||
context.build_store(slot_ptr, value)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -51,14 +42,10 @@ pub fn transient_load<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let position_pointer = Pointer::new_with_offset(
|
||||
context,
|
||||
AddressSpace::TransientStorage,
|
||||
context.word_type(),
|
||||
position,
|
||||
"transient_storage_load_position_pointer",
|
||||
);
|
||||
context.build_load(position_pointer, "transient_storage_load_value")
|
||||
let mut slot_ptr = context.build_alloca_at_entry(context.word_type(), "slot_pointer");
|
||||
slot_ptr.address_space = AddressSpace::TransientStorage;
|
||||
context.builder().build_store(slot_ptr.value, position)?;
|
||||
context.build_load(slot_ptr, "transient_storage_load_value")
|
||||
}
|
||||
|
||||
/// Translates the transient storage store.
|
||||
@@ -70,13 +57,9 @@ pub fn transient_store<'ctx, D>(
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let position_pointer = Pointer::new_with_offset(
|
||||
context,
|
||||
AddressSpace::TransientStorage,
|
||||
context.word_type(),
|
||||
position,
|
||||
"transient_storage_store_position_pointer",
|
||||
);
|
||||
context.build_store(position_pointer, value)?;
|
||||
let mut slot_ptr = context.build_alloca_at_entry(context.word_type(), "slot_pointer");
|
||||
slot_ptr.address_space = AddressSpace::TransientStorage;
|
||||
context.builder().build_store(slot_ptr.value, position)?;
|
||||
context.build_store(slot_ptr, value)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -97,7 +97,6 @@ pub trait Dependency {
|
||||
dependency: Self,
|
||||
path: &str,
|
||||
optimizer_settings: OptimizerSettings,
|
||||
is_system_mode: bool,
|
||||
include_metadata_hash: bool,
|
||||
debug_config: Option<DebugConfig>,
|
||||
) -> anyhow::Result<String>;
|
||||
@@ -118,7 +117,6 @@ impl Dependency for DummyDependency {
|
||||
_dependency: Self,
|
||||
_path: &str,
|
||||
_optimizer_settings: OptimizerSettings,
|
||||
_is_system_mode: bool,
|
||||
_include_metadata_hash: bool,
|
||||
_debug_config: Option<DebugConfig>,
|
||||
) -> anyhow::Result<String> {
|
||||
|
||||
@@ -39,9 +39,9 @@ impl TargetMachine {
|
||||
|
||||
/// LLVM target features.
|
||||
#[cfg(feature = "riscv-zbb")]
|
||||
pub const VM_FEATURES: &'static str = "+zbb,+e,+m";
|
||||
pub const VM_FEATURES: &'static str = "+zbb,+a,+e,+m,+c,+fast-unaligned-access,+xtheadcondmov";
|
||||
#[cfg(not(feature = "riscv-zbb"))]
|
||||
pub const VM_FEATURES: &'static str = "+e,+m";
|
||||
pub const VM_FEATURES: &'static str = "+a,+e,+m,+c,+fast-unaligned-access,+xtheadcondmov";
|
||||
|
||||
/// A shortcut constructor.
|
||||
/// A separate instance for every optimization level is created.
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
[package]
|
||||
name = "pallet-contracts-pvm-llapi"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[features]
|
||||
riscv-64 = []
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] }
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod calling_convention;
|
||||
pub mod polkavm_guest;
|
||||
@@ -1,134 +0,0 @@
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "polkavm_guest.h"
|
||||
|
||||
|
||||
// Missing builtins
|
||||
|
||||
void * memset(void *b, int c, size_t len) {
|
||||
uint8_t *dest = b;
|
||||
while (len-- > 0) *dest++ = c;
|
||||
return b;
|
||||
}
|
||||
|
||||
void * memcpy(void *dst, const void *_src, size_t len) {
|
||||
uint8_t *dest = dst;
|
||||
const uint8_t *src = _src;
|
||||
|
||||
while (len--) *dest++ = *src++;
|
||||
|
||||
return dst;
|
||||
}
|
||||
|
||||
void * memmove(void *dst, const void *src, size_t n) {
|
||||
char *d = dst;
|
||||
const char *s = src;
|
||||
|
||||
if (d==s) return d;
|
||||
if ((uintptr_t)s-(uintptr_t)d-n <= -2*n) return memcpy(d, s, n);
|
||||
|
||||
if (d<s) {
|
||||
for (; n; n--) *d++ = *s++;
|
||||
} else {
|
||||
while (n) n--, d[n] = s[n];
|
||||
}
|
||||
|
||||
return dst;
|
||||
}
|
||||
|
||||
void * __sbrk(uint32_t size) {
|
||||
uint32_t address;
|
||||
__asm__ __volatile__(
|
||||
".insn r 0xb, 1, 0, %[dst], %[sz], zero"
|
||||
: [dst] "=r" (address)
|
||||
: [sz] "ir" (size)
|
||||
:
|
||||
);
|
||||
return (void *)address;
|
||||
}
|
||||
|
||||
// Exports
|
||||
|
||||
extern void call();
|
||||
POLKAVM_EXPORT(void, call)
|
||||
|
||||
extern void deploy();
|
||||
POLKAVM_EXPORT(void, deploy)
|
||||
|
||||
|
||||
// Imports
|
||||
|
||||
POLKAVM_IMPORT(void, input, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, seal_return, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, returndatacopy, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, value_transferred, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, set_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, get_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, clear_storage, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, contains_storage, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, take_storage, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, seal_call, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, delegate_call, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, instantiate, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, terminate, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, caller, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, is_contract, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, code_hash, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, code_size, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, own_code_hash, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, caller_is_origin)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, caller_is_root)
|
||||
|
||||
POLKAVM_IMPORT(void, address, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, weight_to_fee, uint64_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, gas_left, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, balance, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, now, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, minimum_balance, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, deposit_event, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, block_number, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, hash_sha2_256, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, hash_keccak_256, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, hash_blake2_256, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(void, hash_blake2_128, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, call_chain_extension, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, debug_message, uint32_t, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, set_code_hash, uint32_t)
|
||||
|
||||
POLKAVM_IMPORT(uint64_t, instantiation_nonce,)
|
||||
|
||||
POLKAVM_IMPORT(uint32_t, transfer, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||
@@ -1,54 +0,0 @@
|
||||
//! This crate vendors the [PolkaVM][0] C API and provides a LLVM module for interacting
|
||||
//! with the `pallet-contracts` runtime API.
|
||||
//! At present, the contracts pallet requires blobs to export `call` and `deploy`,
|
||||
//! and offers a bunch of [runtime API methods][1]. The provided [module] implements
|
||||
//! those exports and imports.
|
||||
//! [0]: [https://crates.io/crates/polkavm]
|
||||
//! [1]: [https://docs.rs/pallet-contracts/26.0.0/pallet_contracts/api_doc/index.html]
|
||||
|
||||
use inkwell::{context::Context, memory_buffer::MemoryBuffer, module::Module, support::LLVMString};
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/polkavm_guest.rs"));
|
||||
|
||||
/// Creates a LLVM module from the [BITCODE].
|
||||
/// The module does:
|
||||
/// - Export the `call` and `deploy` functions (which are named thereafter).
|
||||
/// - Import (most) `pallet-contracts` runtime API functions.
|
||||
/// Returns `Error` if the bitcode fails to parse, which should never happen.
|
||||
pub fn module<'context>(
|
||||
context: &'context Context,
|
||||
module_name: &str,
|
||||
) -> Result<Module<'context>, LLVMString> {
|
||||
let buf = MemoryBuffer::create_from_memory_range(BITCODE, module_name);
|
||||
Module::parse_bitcode_from_buffer(&buf, context)
|
||||
}
|
||||
|
||||
/// Creates a module that sets the PolkaVM minimum stack size to [`size`] if linked in.
|
||||
pub fn min_stack_size<'context>(
|
||||
context: &'context Context,
|
||||
module_name: &str,
|
||||
size: u32,
|
||||
) -> Module<'context> {
|
||||
let module = context.create_module(module_name);
|
||||
module.set_inline_assembly(&format!(
|
||||
".pushsection .polkavm_min_stack_size,\"\",@progbits
|
||||
.word {size}
|
||||
.popsection"
|
||||
));
|
||||
module
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::polkavm_guest;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
inkwell::targets::Target::initialize_riscv(&Default::default());
|
||||
let context = inkwell::context::Context::create();
|
||||
let module = polkavm_guest::module(&context, "polkavm_guest").unwrap();
|
||||
|
||||
assert!(module.get_function("call").is_some());
|
||||
assert!(module.get_function("deploy").is_some());
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,29 @@ version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
repository.authors = true
|
||||
descritption = "Execute revive contracts in a simulated blockchain runtime"
|
||||
authors.workspace = true
|
||||
description = "Execute revive contracts in a simulated blockchain runtime"
|
||||
|
||||
[features]
|
||||
default = ["solidity"]
|
||||
solidity = ["revive-solidity", "revive-differential"]
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
hex = { workspace = true, features = ["serde"] }
|
||||
codec = { workspace = true, default-features = false }
|
||||
scale-info = { workspace = true, default-features = false }
|
||||
polkadot-sdk = { workspace = true, features = ["experimental", "runtime"] }
|
||||
alloy-primitives = { workspace = true }
|
||||
polkadot-sdk.workspace = true
|
||||
polkadot-sdk.features = [
|
||||
"experimental",
|
||||
"runtime",
|
||||
"polkadot-runtime-common",
|
||||
"pallet-revive",
|
||||
"pallet-balances",
|
||||
"pallet-timestamp"
|
||||
]
|
||||
|
||||
revive-solidity = { workspace = true }
|
||||
revive-solidity = { workspace = true, optional = true }
|
||||
revive-differential = { workspace = true, optional = true }
|
||||
|
||||
Binary file not shown.
+163
-220
@@ -7,49 +7,74 @@
|
||||
//! ```rust
|
||||
//! use revive_runner::*;
|
||||
//! use SpecsAction::*;
|
||||
//! run_test(Specs {
|
||||
//! Specs {
|
||||
//! differential: false,
|
||||
//! balances: vec![(ALICE, 1_000_000_000)],
|
||||
//! actions: vec![Instantiate {
|
||||
//! origin: ALICE,
|
||||
//! origin: TestAddress::Alice,
|
||||
//! value: 0,
|
||||
//! gas_limit: Some(GAS_LIMIT),
|
||||
//! storage_deposit_limit: Some(DEPOSIT_LIMIT),
|
||||
//! code: Code::Bytes(include_bytes!("../fixtures/Baseline.pvm").to_vec()),
|
||||
//! data: vec![],
|
||||
//! salt: vec![],
|
||||
//! salt: Default::default(),
|
||||
//! }],
|
||||
//! })
|
||||
//! }
|
||||
//! .run();
|
||||
//! ```
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use hex::{FromHex, ToHex};
|
||||
use pallet_revive::{AddressMapper, ExecReturnValue, InstantiateReturnValue};
|
||||
use polkadot_sdk::*;
|
||||
use polkadot_sdk::{
|
||||
pallet_revive::{CollectEvents, ContractExecResult, ContractInstantiateResult, DebugInfo},
|
||||
pallet_revive::{CollectEvents, ContractResult, DebugInfo},
|
||||
polkadot_runtime_common::BuildStorage,
|
||||
polkadot_sdk_frame::testing_prelude::*,
|
||||
sp_core::{H160, H256},
|
||||
sp_keystore::{testing::MemoryKeystore, KeystoreExt},
|
||||
sp_runtime::AccountId32,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
mod runtime;
|
||||
use crate::runtime::*;
|
||||
pub use crate::specs::*;
|
||||
|
||||
pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]);
|
||||
pub const BOB: AccountId32 = AccountId32::new([2u8; 32]);
|
||||
pub const CHARLIE: AccountId32 = AccountId32::new([3u8; 32]);
|
||||
mod runtime;
|
||||
mod specs;
|
||||
|
||||
#[cfg(not(feature = "revive-solidity"))]
|
||||
pub(crate) const NO_SOLIDITY_FRONTEND: &str =
|
||||
"revive-runner was built without the solidity frontend; please enable the 'solidity' feature!";
|
||||
|
||||
/// The alice test account
|
||||
pub const ALICE: H160 = H160([1u8; 20]);
|
||||
/// The bob test account
|
||||
pub const BOB: H160 = H160([2u8; 20]);
|
||||
/// The charlie test account
|
||||
pub const CHARLIE: H160 = H160([3u8; 20]);
|
||||
/// Default gas limit
|
||||
pub const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024);
|
||||
/// Default deposit limit
|
||||
pub const DEPOSIT_LIMIT: Balance = 10_000_000;
|
||||
|
||||
/// Externalities builder
|
||||
#[derive(Default)]
|
||||
pub struct ExtBuilder {
|
||||
/// List of endowments at genesis
|
||||
balance_genesis_config: Vec<(AccountId, Balance)>,
|
||||
balance_genesis_config: Vec<(AccountId32, Balance)>,
|
||||
}
|
||||
|
||||
impl ExtBuilder {
|
||||
/// Set the balance of an account at genesis
|
||||
fn balance_genesis_config(mut self, value: Vec<(AccountId, Balance)>) -> Self {
|
||||
self.balance_genesis_config = value;
|
||||
self
|
||||
fn balance_genesis_config(self, value: Vec<(H160, Balance)>) -> Self {
|
||||
Self {
|
||||
balance_genesis_config: value
|
||||
.iter()
|
||||
.map(|(address, balance)| (AccountId::to_fallback_account_id(address), *balance))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the externalities
|
||||
@@ -71,28 +96,61 @@ impl ExtBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Default gas limit
|
||||
pub const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024);
|
||||
|
||||
/// Default deposit limit
|
||||
pub const DEPOSIT_LIMIT: Balance = 10_000_000;
|
||||
|
||||
/// Expectation for a call
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VerifyCallExpectation {
|
||||
/// When provided, the expected gas consumed
|
||||
gas_consumed: Option<Weight>,
|
||||
pub gas_consumed: Option<Weight>,
|
||||
/// When provided, the expected output
|
||||
output: Option<Vec<u8>>,
|
||||
#[serde(default, with = "hex")]
|
||||
pub output: OptionalHex<Vec<u8>>,
|
||||
///Expected call result
|
||||
success: bool,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct OptionalHex<T>(Option<T>);
|
||||
|
||||
impl<I: FromHex + AsRef<[u8]>> FromHex for OptionalHex<I> {
|
||||
type Error = <I as FromHex>::Error;
|
||||
|
||||
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
|
||||
let value = I::from_hex(hex)?;
|
||||
Ok(Self(Some(value)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: AsRef<[u8]>> ToHex for &OptionalHex<I> {
|
||||
fn encode_hex<T: std::iter::FromIterator<char>>(&self) -> T {
|
||||
match self.0.as_ref() {
|
||||
None => T::from_iter("".chars()),
|
||||
Some(data) => I::encode_hex::<T>(data),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_hex_upper<T: std::iter::FromIterator<char>>(&self) -> T {
|
||||
match self.0.as_ref() {
|
||||
None => T::from_iter("".chars()),
|
||||
Some(data) => I::encode_hex_upper(data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> From<T> for OptionalHex<T> {
|
||||
fn from(value: T) -> Self {
|
||||
if value.as_ref().is_empty() {
|
||||
OptionalHex(None)
|
||||
} else {
|
||||
OptionalHex(Some(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for VerifyCallExpectation {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
gas_consumed: None,
|
||||
output: None,
|
||||
output: OptionalHex(None),
|
||||
success: true,
|
||||
}
|
||||
}
|
||||
@@ -100,62 +158,87 @@ impl Default for VerifyCallExpectation {
|
||||
|
||||
impl VerifyCallExpectation {
|
||||
/// Verify that the expectations are met
|
||||
fn verify(self, result: CallResult) {
|
||||
dbg!(&result);
|
||||
assert_eq!(self.success, result.is_ok());
|
||||
fn verify(self, result: &CallResult) {
|
||||
assert_eq!(
|
||||
self.success,
|
||||
!result.did_revert(),
|
||||
"contract execution result mismatch: {result:?}"
|
||||
);
|
||||
|
||||
if let Some(gas_consumed) = self.gas_consumed {
|
||||
assert_eq!(gas_consumed, result.gas_consumed());
|
||||
}
|
||||
if let Some(output) = self.output {
|
||||
assert_eq!(output, result.output());
|
||||
|
||||
if let OptionalHex(Some(data)) = self.output {
|
||||
assert_eq!(data, result.output());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of a call
|
||||
#[derive(Debug)]
|
||||
enum CallResult {
|
||||
Exec(ContractExecResult<Balance, EventRecord>),
|
||||
Instantiate(ContractInstantiateResult<AccountId, Balance, EventRecord>),
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum CallResult {
|
||||
Exec {
|
||||
result: ContractResult<ExecReturnValue, Balance, EventRecord>,
|
||||
wall_time: Duration,
|
||||
},
|
||||
Instantiate {
|
||||
result: ContractResult<InstantiateReturnValue, Balance, EventRecord>,
|
||||
wall_time: Duration,
|
||||
code_hash: H256,
|
||||
},
|
||||
}
|
||||
|
||||
impl CallResult {
|
||||
/// Check if the call was successful
|
||||
fn is_ok(&self) -> bool {
|
||||
fn did_revert(&self) -> bool {
|
||||
match self {
|
||||
Self::Exec(res) => res.result.is_ok(),
|
||||
Self::Instantiate(res) => res.result.is_ok(),
|
||||
Self::Exec { result, .. } => result
|
||||
.result
|
||||
.as_ref()
|
||||
.map(|r| r.did_revert())
|
||||
.unwrap_or(true),
|
||||
Self::Instantiate { result, .. } => result
|
||||
.result
|
||||
.as_ref()
|
||||
.map(|r| r.result.did_revert())
|
||||
.unwrap_or(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the output of the call
|
||||
fn output(&self) -> Vec<u8> {
|
||||
match self {
|
||||
Self::Exec(res) => res
|
||||
Self::Exec { result, .. } => result
|
||||
.result
|
||||
.as_ref()
|
||||
.map(|r| r.data.clone())
|
||||
.unwrap_or_default(),
|
||||
Self::Instantiate(res) => res
|
||||
Self::Instantiate { result, .. } => result
|
||||
.result
|
||||
.as_ref()
|
||||
.map(|r| r.result.data.clone())
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the gas consumed by the call
|
||||
fn gas_consumed(&self) -> Weight {
|
||||
match self {
|
||||
Self::Exec(res) => res.gas_consumed,
|
||||
Self::Instantiate(res) => res.gas_consumed,
|
||||
Self::Exec { result, .. } => result.gas_consumed,
|
||||
Self::Instantiate { result, .. } => result.gas_consumed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum Code {
|
||||
#[cfg(feature = "revive-solidity")]
|
||||
/// Compile a single solidity source and use the blob of `contract`
|
||||
Solidity {
|
||||
path: std::path::PathBuf,
|
||||
path: Option<std::path::PathBuf>,
|
||||
solc_optimizer: Option<bool>,
|
||||
pipeline: Option<revive_solidity::SolcPipeline>,
|
||||
contract: String,
|
||||
},
|
||||
/// Read the contract blob from disk
|
||||
@@ -163,16 +246,36 @@ pub enum Code {
|
||||
/// A contract blob
|
||||
Bytes(Vec<u8>),
|
||||
/// Pre-existing contract hash
|
||||
Hash(Hash),
|
||||
Hash(crate::runtime::Hash),
|
||||
}
|
||||
|
||||
impl From<Code> for pallet_revive::Code<Hash> {
|
||||
impl Default for Code {
|
||||
fn default() -> Self {
|
||||
Self::Bytes(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Code> for pallet_revive::Code {
|
||||
fn from(val: Code) -> Self {
|
||||
match val {
|
||||
Code::Solidity { path, contract } => {
|
||||
pallet_revive::Code::Upload(revive_solidity::test_utils::compile_blob(
|
||||
contract.as_str(),
|
||||
std::fs::read_to_string(path).unwrap().as_str(),
|
||||
#[cfg(feature = "solidity")]
|
||||
Code::Solidity {
|
||||
path,
|
||||
contract,
|
||||
solc_optimizer,
|
||||
pipeline,
|
||||
} => {
|
||||
let Some(path) = path else {
|
||||
panic!("Solidity source of contract '{contract}' missing path");
|
||||
};
|
||||
let Ok(source_code) = std::fs::read_to_string(&path) else {
|
||||
panic!("Failed to reead source code from {}", path.display());
|
||||
};
|
||||
pallet_revive::Code::Upload(revive_solidity::test_utils::compile_blob_with_options(
|
||||
&contract,
|
||||
&source_code,
|
||||
solc_optimizer.unwrap_or(true),
|
||||
pipeline.unwrap_or(revive_solidity::SolcPipeline::Yul),
|
||||
))
|
||||
}
|
||||
Code::Path(path) => pallet_revive::Code::Upload(std::fs::read(path).unwrap()),
|
||||
@@ -182,201 +285,41 @@ impl From<Code> for pallet_revive::Code<Hash> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An action to perform in a contract test
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum SpecsAction {
|
||||
/// Instantiate a contract
|
||||
Instantiate {
|
||||
origin: AccountId,
|
||||
#[serde(default)]
|
||||
value: Balance,
|
||||
#[serde(default)]
|
||||
gas_limit: Option<Weight>,
|
||||
#[serde(default)]
|
||||
storage_deposit_limit: Option<Balance>,
|
||||
code: Code,
|
||||
#[serde(default)]
|
||||
data: Vec<u8>,
|
||||
#[serde(default)]
|
||||
salt: Vec<u8>,
|
||||
},
|
||||
/// Call a contract
|
||||
Call {
|
||||
origin: AccountId,
|
||||
dest: AccountId,
|
||||
#[serde(default)]
|
||||
value: Balance,
|
||||
#[serde(default)]
|
||||
gas_limit: Option<Weight>,
|
||||
#[serde(default)]
|
||||
storage_deposit_limit: Option<Balance>,
|
||||
#[serde(default)]
|
||||
data: Vec<u8>,
|
||||
},
|
||||
/// Verify the result of the last call, omitting this will simply ensure the last call was successful
|
||||
VerifyCall(VerifyCallExpectation),
|
||||
|
||||
/// Verify the balance of an account
|
||||
VerifyBalance {
|
||||
origin: AccountId,
|
||||
expected: Balance,
|
||||
},
|
||||
/// Verify the storage of a contract
|
||||
VerifyStorage {
|
||||
contract: AccountId,
|
||||
key: Vec<u8>,
|
||||
expected: Option<Vec<u8>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Specs for a contract test
|
||||
#[derive(Default, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Specs {
|
||||
/// List of endowments at genesis
|
||||
pub balances: Vec<(AccountId, Balance)>,
|
||||
/// List of actions to perform
|
||||
pub actions: Vec<SpecsAction>,
|
||||
}
|
||||
|
||||
impl Specs {
|
||||
/// Get the list of actions to perform
|
||||
/// A default [`SpecAction::VerifyCall`] is injected after each Instantiate or Call action when
|
||||
/// missing
|
||||
fn actions(&self) -> Vec<SpecsAction> {
|
||||
self.actions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(index, item)| {
|
||||
let next_item = self.actions.get(index + 1);
|
||||
if matches!(
|
||||
item,
|
||||
SpecsAction::Instantiate { .. } | SpecsAction::Call { .. }
|
||||
) && !matches!(next_item, Some(SpecsAction::VerifyCall(_)))
|
||||
{
|
||||
return vec![
|
||||
item.clone(),
|
||||
SpecsAction::VerifyCall(VerifyCallExpectation::default()),
|
||||
];
|
||||
}
|
||||
vec![item.clone()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a contract test
|
||||
/// The test takes a [`Specs`] and executes the actions in order
|
||||
pub fn run_test(specs: Specs) {
|
||||
ExtBuilder::default()
|
||||
.balance_genesis_config(specs.balances.clone())
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
use SpecsAction::*;
|
||||
|
||||
let mut res: Option<CallResult> = None;
|
||||
let actions = specs.actions();
|
||||
|
||||
for action in actions {
|
||||
match action {
|
||||
Instantiate {
|
||||
origin,
|
||||
value,
|
||||
gas_limit,
|
||||
storage_deposit_limit,
|
||||
code,
|
||||
data,
|
||||
salt,
|
||||
} => {
|
||||
res = Some(CallResult::Instantiate(Contracts::bare_instantiate(
|
||||
RuntimeOrigin::signed(origin),
|
||||
value,
|
||||
gas_limit.unwrap_or(GAS_LIMIT),
|
||||
storage_deposit_limit.unwrap_or(DEPOSIT_LIMIT),
|
||||
code.into(),
|
||||
data,
|
||||
salt,
|
||||
DebugInfo::Skip,
|
||||
CollectEvents::Skip,
|
||||
)));
|
||||
}
|
||||
Call {
|
||||
origin,
|
||||
dest,
|
||||
value,
|
||||
gas_limit,
|
||||
storage_deposit_limit,
|
||||
data,
|
||||
} => {
|
||||
res = Some(CallResult::Exec(Contracts::bare_call(
|
||||
RuntimeOrigin::signed(origin),
|
||||
dest,
|
||||
value,
|
||||
gas_limit.unwrap_or(GAS_LIMIT),
|
||||
storage_deposit_limit.unwrap_or(DEPOSIT_LIMIT),
|
||||
data,
|
||||
DebugInfo::Skip,
|
||||
CollectEvents::Skip,
|
||||
)));
|
||||
}
|
||||
VerifyCall(expectation) => {
|
||||
if let Some(res) = res.take() {
|
||||
expectation.verify(res);
|
||||
} else {
|
||||
panic!("No call to verify");
|
||||
}
|
||||
}
|
||||
VerifyBalance { origin, expected } => {
|
||||
assert_eq!(Balances::free_balance(&origin), expected);
|
||||
}
|
||||
VerifyStorage {
|
||||
contract,
|
||||
key,
|
||||
expected,
|
||||
} => {
|
||||
let Ok(storage) = Contracts::get_storage(contract, key) else {
|
||||
panic!("Error reading storage");
|
||||
};
|
||||
assert_eq!(storage, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::*;
|
||||
|
||||
#[test]
|
||||
fn instantiate_works() {
|
||||
use SpecsAction::*;
|
||||
run_test(Specs {
|
||||
use specs::SpecsAction::*;
|
||||
let specs = Specs {
|
||||
differential: false,
|
||||
balances: vec![(ALICE, 1_000_000_000)],
|
||||
actions: vec![Instantiate {
|
||||
origin: ALICE,
|
||||
origin: TestAddress::Alice,
|
||||
value: 0,
|
||||
gas_limit: Some(GAS_LIMIT),
|
||||
storage_deposit_limit: Some(DEPOSIT_LIMIT),
|
||||
code: Code::Bytes(include_bytes!("../fixtures/Baseline.pvm").to_vec()),
|
||||
data: vec![],
|
||||
salt: vec![],
|
||||
salt: OptionalHex::default(),
|
||||
}],
|
||||
})
|
||||
};
|
||||
specs.run();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instantiate_with_json() {
|
||||
let specs = serde_json::from_str::<Specs>(
|
||||
serde_json::from_str::<Specs>(
|
||||
r#"
|
||||
{
|
||||
"balances": [
|
||||
[ "5C62Ck4UrFPiBtoCmeSrgF7x9yv9mn38446dhCpsi2mLHiFT", 1000000000 ]
|
||||
[ "0101010101010101010101010101010101010101", 1000000000 ]
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"Instantiate": {
|
||||
"origin": "5C62Ck4UrFPiBtoCmeSrgF7x9yv9mn38446dhCpsi2mLHiFT",
|
||||
"origin": "Alice",
|
||||
"value": 0,
|
||||
"code": {
|
||||
"Path": "fixtures/Baseline.pvm"
|
||||
@@ -387,7 +330,7 @@ mod tests {
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
run_test(specs);
|
||||
.unwrap()
|
||||
.run();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use frame_support::runtime;
|
||||
|
||||
use pallet_revive::AccountId32Mapper;
|
||||
use polkadot_sdk::*;
|
||||
use polkadot_sdk::{
|
||||
polkadot_sdk_frame::{log, runtime::prelude::*},
|
||||
@@ -7,7 +8,7 @@ use polkadot_sdk::{
|
||||
};
|
||||
|
||||
pub type Balance = u128;
|
||||
pub type AccountId = AccountId32;
|
||||
pub type AccountId = pallet_revive::AccountId32Mapper<Runtime>;
|
||||
pub type Block = frame_system::mocking::MockBlock<Runtime>;
|
||||
pub type Hash = <Runtime as frame_system::Config>::Hash;
|
||||
pub type EventRecord =
|
||||
@@ -45,7 +46,7 @@ mod runtime {
|
||||
#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
|
||||
impl frame_system::Config for Runtime {
|
||||
type Block = Block;
|
||||
type AccountId = AccountId;
|
||||
type AccountId = AccountId32;
|
||||
type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
|
||||
}
|
||||
|
||||
@@ -74,11 +75,13 @@ impl pallet_revive::Config for Runtime {
|
||||
type ChainExtension = ();
|
||||
type DepositPerByte = DepositPerByte;
|
||||
type DepositPerItem = DepositPerItem;
|
||||
type AddressGenerator = pallet_revive::DefaultAddressGenerator;
|
||||
type AddressMapper = AccountId32Mapper<Self>;
|
||||
type RuntimeMemory = ConstU32<{ 512 * 1024 * 1024 }>;
|
||||
type PVFMemory = ConstU32<{ 1024 * 1024 * 1024 }>;
|
||||
type UnsafeUnstableInterface = UnstableInterface;
|
||||
type UploadOrigin = EnsureSigned<AccountId>;
|
||||
type InstantiateOrigin = EnsureSigned<AccountId>;
|
||||
type Migrations = ();
|
||||
type UploadOrigin = EnsureSigned<AccountId32>;
|
||||
type InstantiateOrigin = EnsureSigned<AccountId32>;
|
||||
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
|
||||
type Debug = ();
|
||||
type ChainId = ConstU64<420_420_420>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,539 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::*;
|
||||
use alloy_primitives::{keccak256, Address};
|
||||
#[cfg(feature = "revive-solidity")]
|
||||
use revive_differential::{Evm, EvmLog};
|
||||
#[cfg(feature = "revive-solidity")]
|
||||
use revive_solidity::test_utils::*;
|
||||
|
||||
const SPEC_MARKER_BEGIN: &str = "/* runner.json";
|
||||
const SPEC_MARKER_END: &str = "*/";
|
||||
|
||||
/// An action to perform in a contract test
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum SpecsAction {
|
||||
/// Instantiate a contract
|
||||
Instantiate {
|
||||
#[serde(default)]
|
||||
origin: TestAddress,
|
||||
#[serde(default)]
|
||||
value: Balance,
|
||||
#[serde(default)]
|
||||
gas_limit: Option<Weight>,
|
||||
#[serde(default)]
|
||||
storage_deposit_limit: Option<Balance>,
|
||||
#[serde(default)]
|
||||
code: Code,
|
||||
#[serde(default, with = "hex::serde")]
|
||||
data: Vec<u8>,
|
||||
#[serde(default, with = "hex::serde")]
|
||||
salt: OptionalHex<[u8; 32]>,
|
||||
},
|
||||
/// Upload contract code without calling the constructor
|
||||
Upload {
|
||||
#[serde(default)]
|
||||
origin: TestAddress,
|
||||
#[serde(default)]
|
||||
code: Code,
|
||||
#[serde(default)]
|
||||
storage_deposit_limit: Option<Balance>,
|
||||
},
|
||||
/// Call a contract
|
||||
Call {
|
||||
#[serde(default)]
|
||||
origin: TestAddress,
|
||||
dest: TestAddress,
|
||||
#[serde(default)]
|
||||
value: Balance,
|
||||
#[serde(default)]
|
||||
gas_limit: Option<Weight>,
|
||||
#[serde(default)]
|
||||
storage_deposit_limit: Option<Balance>,
|
||||
#[serde(default, with = "hex::serde")]
|
||||
data: Vec<u8>,
|
||||
},
|
||||
/// Verify the result of the last call, omitting this will simply ensure the last call was successful
|
||||
VerifyCall(VerifyCallExpectation),
|
||||
/// Verify the balance of an account
|
||||
VerifyBalance {
|
||||
origin: TestAddress,
|
||||
expected: Balance,
|
||||
},
|
||||
/// Verify the storage of a contract
|
||||
VerifyStorage {
|
||||
contract: TestAddress,
|
||||
#[serde(with = "hex::serde")]
|
||||
key: [u8; 32],
|
||||
#[serde(default, with = "hex::serde")]
|
||||
expected: [u8; 32],
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(feature = "solidity")]
|
||||
impl SpecsAction {
|
||||
/// Derive verification actions from the EVM output log
|
||||
pub fn derive_verification(
|
||||
log: &EvmLog,
|
||||
address_evm: Address,
|
||||
account_pvm: TestAddress,
|
||||
) -> Vec<Self> {
|
||||
let account = log
|
||||
.state_dump
|
||||
.accounts
|
||||
.get(&address_evm)
|
||||
.unwrap_or_else(|| panic!("account {address_evm} not in state dump"));
|
||||
|
||||
let mut actions = vec![
|
||||
Self::VerifyCall(VerifyCallExpectation {
|
||||
gas_consumed: None,
|
||||
success: log.output.run_success(),
|
||||
output: log.output.output.to_vec().into(),
|
||||
}),
|
||||
Self::VerifyBalance {
|
||||
origin: account_pvm.clone(),
|
||||
expected: account
|
||||
.balance
|
||||
.try_into()
|
||||
.expect("balance should fit into u128"),
|
||||
},
|
||||
];
|
||||
|
||||
let Some(storage) = &account.storage else {
|
||||
return actions;
|
||||
};
|
||||
|
||||
for (key, expected) in storage {
|
||||
let mut key = **key;
|
||||
let mut expected = **expected;
|
||||
key.reverse();
|
||||
expected.reverse();
|
||||
actions.push(Self::VerifyStorage {
|
||||
contract: account_pvm.clone(),
|
||||
key,
|
||||
expected,
|
||||
});
|
||||
}
|
||||
|
||||
actions
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub enum TestAddress {
|
||||
/// The ALICE account
|
||||
#[default]
|
||||
Alice,
|
||||
/// The BOB account
|
||||
Bob,
|
||||
/// The CHARLIE account
|
||||
Charlie,
|
||||
/// AccountID that was created during the nth call in this run.
|
||||
Instantiated(usize),
|
||||
/// Arbitrary AccountID
|
||||
AccountId(H160),
|
||||
}
|
||||
|
||||
impl TestAddress {
|
||||
fn to_eth_addr(&self, results: &[CallResult]) -> H160 {
|
||||
match self {
|
||||
TestAddress::Alice => ALICE,
|
||||
TestAddress::Bob => BOB,
|
||||
TestAddress::Charlie => CHARLIE,
|
||||
TestAddress::AccountId(account_id) => *account_id,
|
||||
TestAddress::Instantiated(n) => match results
|
||||
.get(*n)
|
||||
.expect("should provide valid index into call results")
|
||||
{
|
||||
CallResult::Exec { .. } => panic!("call #{n} should be an instantiation"),
|
||||
CallResult::Instantiate { result, .. } => {
|
||||
result.result.as_ref().expect("call #{n} reverted").addr
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn to_account_id(&self, results: &[CallResult]) -> AccountId32 {
|
||||
AccountId::to_account_id(&self.to_eth_addr(results))
|
||||
}
|
||||
}
|
||||
|
||||
/// Specs for a contract test
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Specs {
|
||||
/// Interpret EVM bytecode and assert output, storage and events
|
||||
#[serde(default)]
|
||||
pub differential: bool,
|
||||
/// List of endowments at genesis
|
||||
pub balances: Vec<(H160, Balance)>,
|
||||
/// List of actions to perform
|
||||
pub actions: Vec<SpecsAction>,
|
||||
}
|
||||
|
||||
impl Default for Specs {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
differential: false,
|
||||
balances: vec![
|
||||
(ALICE, 1_000_000_000),
|
||||
(BOB, 1_000_000_000),
|
||||
(CHARLIE, 1_000_000_000),
|
||||
],
|
||||
actions: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Specs {
|
||||
/// Get the list of actions to perform
|
||||
/// A default [`SpecAction::VerifyCall`] is injected after each Instantiate or Call action when
|
||||
/// missing and not in differential mode
|
||||
pub fn actions(&self) -> Vec<SpecsAction> {
|
||||
self.actions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(index, item)| {
|
||||
let next_item = self.actions.get(index + 1);
|
||||
if matches!(
|
||||
item,
|
||||
SpecsAction::Instantiate { .. } | SpecsAction::Call { .. }
|
||||
) && !matches!(next_item, Some(SpecsAction::VerifyCall { .. }))
|
||||
&& !self.differential
|
||||
{
|
||||
return vec![
|
||||
item.clone(),
|
||||
SpecsAction::VerifyCall(VerifyCallExpectation::default()),
|
||||
];
|
||||
}
|
||||
vec![item.clone()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Helper to allow not specifying the code bytes or path directly in the runner.json
|
||||
/// - Replace `Code::Bytes(bytes)` if `bytes` are empty: read `contract_file`
|
||||
/// - Replace `Code::Solidity{ path, ..}` if `path` is not provided: replace `path` with `contract_file`
|
||||
pub fn replace_empty_code(&mut self, contract_name: &str, contract_path: &str) {
|
||||
for action in self.actions.iter_mut() {
|
||||
let code = match action {
|
||||
SpecsAction::Instantiate { code, .. } | SpecsAction::Upload { code, .. } => code,
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
match code {
|
||||
#[cfg(feature = "revive-solidity")]
|
||||
Code::Bytes(bytes) if bytes.is_empty() => {
|
||||
let contract_source = match std::fs::read_to_string(contract_path) {
|
||||
Err(err) => panic!("unable to read {contract_path}: {err}"),
|
||||
Ok(solidity) => solidity,
|
||||
};
|
||||
*bytes = compile_blob(contract_name, &contract_source)
|
||||
}
|
||||
#[cfg(not(feature = "revive-solidity"))]
|
||||
Code::Bytes(_) => panic!("{NO_SOLIDITY_FRONTEND}"),
|
||||
#[cfg(feature = "revive-solidity")]
|
||||
Code::Solidity { path, .. } if path.is_none() => *path = Some(contract_path.into()),
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a contract test
|
||||
/// The test takes a [`Specs`] and executes the actions in order
|
||||
pub fn run(self) -> Vec<CallResult> {
|
||||
if self.differential {
|
||||
#[cfg(not(feature = "solidity"))]
|
||||
panic!("{NO_SOLIDITY_FRONTEND}");
|
||||
#[cfg(feature = "solidity")]
|
||||
self.run_on_evm()
|
||||
} else {
|
||||
self
|
||||
}
|
||||
.run_on_pallet()
|
||||
}
|
||||
|
||||
#[cfg(feature = "solidity")]
|
||||
fn run_on_evm(self) -> Self {
|
||||
let mut derived_specs = Self {
|
||||
actions: vec![],
|
||||
..self
|
||||
};
|
||||
|
||||
let mut evm = Evm::default();
|
||||
let mut deployed_accounts = vec![];
|
||||
|
||||
for action in self.actions {
|
||||
derived_specs.actions.push(action.clone());
|
||||
|
||||
use specs::SpecsAction::*;
|
||||
match action {
|
||||
Instantiate {
|
||||
origin,
|
||||
value,
|
||||
gas_limit,
|
||||
code,
|
||||
data,
|
||||
salt,
|
||||
..
|
||||
} => {
|
||||
let Code::Solidity {
|
||||
path: Some(path),
|
||||
solc_optimizer,
|
||||
pipeline,
|
||||
contract,
|
||||
} = code
|
||||
else {
|
||||
panic!("the differential runner requires Code::Solidity source");
|
||||
};
|
||||
assert_ne!(
|
||||
pipeline,
|
||||
Some(revive_solidity::SolcPipeline::EVMLA),
|
||||
"yul pipeline must be enabled in differential mode"
|
||||
);
|
||||
assert!(
|
||||
salt.0.is_none(),
|
||||
"salt is not supported in differential mode"
|
||||
);
|
||||
assert_eq!(
|
||||
origin,
|
||||
TestAddress::default(),
|
||||
"configuring the origin is not supported in differential mode"
|
||||
);
|
||||
|
||||
let deploy_code = match std::fs::read_to_string(&path) {
|
||||
Ok(solidity_source) => hex::encode(compile_evm_deploy_code(
|
||||
&contract,
|
||||
&solidity_source,
|
||||
solc_optimizer.unwrap_or(true),
|
||||
)),
|
||||
Err(err) => panic!(
|
||||
"failed to read solidity source\n . path: '{}'\n . error: {:?}",
|
||||
path.display(),
|
||||
err
|
||||
),
|
||||
};
|
||||
let mut vm = evm
|
||||
.code_blob(deploy_code.as_bytes().to_vec())
|
||||
.sender(origin.to_eth_addr(&[]).0.into())
|
||||
.deploy(true);
|
||||
if !data.is_empty() {
|
||||
vm = vm.input(data.into());
|
||||
}
|
||||
if value > 0 {
|
||||
vm = vm.value(value);
|
||||
}
|
||||
if let Some(gas) = gas_limit {
|
||||
vm = vm.gas(gas.ref_time());
|
||||
}
|
||||
let mut log = vm.run();
|
||||
log.output.output = Default::default(); // PVM will not have constructor output
|
||||
let deployed_account = log.account_deployed.expect("no account was created");
|
||||
let account_pvm = TestAddress::Instantiated(deployed_accounts.len());
|
||||
deployed_accounts.push(deployed_account);
|
||||
derived_specs
|
||||
.actions
|
||||
.append(&mut SpecsAction::derive_verification(
|
||||
&log,
|
||||
deployed_account,
|
||||
account_pvm,
|
||||
));
|
||||
evm = Evm::from_genesis(log.state_dump.into());
|
||||
}
|
||||
Call {
|
||||
origin,
|
||||
dest,
|
||||
value,
|
||||
gas_limit,
|
||||
data,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
origin,
|
||||
TestAddress::default(),
|
||||
"configuring the origin is not supported in differential mode"
|
||||
);
|
||||
let TestAddress::Instantiated(n) = dest else {
|
||||
panic!("the differential runner requires TestAccountId::Instantiated(n) as dest");
|
||||
};
|
||||
let address = deployed_accounts
|
||||
.get(n)
|
||||
.unwrap_or_else(|| panic!("no account at index {n} "));
|
||||
let mut vm = evm
|
||||
.receiver(*address)
|
||||
.sender(origin.to_eth_addr(&[]).0.into());
|
||||
if !data.is_empty() {
|
||||
vm = vm.input(data.into());
|
||||
}
|
||||
if value > 0 {
|
||||
vm = vm.value(value);
|
||||
}
|
||||
if let Some(gas) = gas_limit {
|
||||
vm = vm.gas(gas.ref_time());
|
||||
}
|
||||
|
||||
let log = vm.run();
|
||||
derived_specs
|
||||
.actions
|
||||
.append(&mut SpecsAction::derive_verification(&log, *address, dest));
|
||||
evm = Evm::from_genesis(log.state_dump.into());
|
||||
}
|
||||
Upload { .. } => continue,
|
||||
other => derived_specs.actions.push(other),
|
||||
}
|
||||
}
|
||||
|
||||
derived_specs
|
||||
}
|
||||
|
||||
fn run_on_pallet(self) -> Vec<CallResult> {
|
||||
let mut results = vec![];
|
||||
|
||||
ExtBuilder::default()
|
||||
.balance_genesis_config(self.balances.clone())
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
use specs::SpecsAction::*;
|
||||
|
||||
for action in self.actions() {
|
||||
match action {
|
||||
Instantiate {
|
||||
origin,
|
||||
value,
|
||||
gas_limit,
|
||||
storage_deposit_limit,
|
||||
code,
|
||||
data,
|
||||
salt,
|
||||
} => {
|
||||
let code: pallet_revive::Code = code.into();
|
||||
let code_hash = match code.clone() {
|
||||
pallet_revive::Code::Existing(code_hash) => code_hash,
|
||||
pallet_revive::Code::Upload(bytes) => {
|
||||
H256::from_slice(keccak256(&bytes).as_slice())
|
||||
}
|
||||
};
|
||||
let origin = RuntimeOrigin::signed(origin.to_account_id(&results));
|
||||
let time_start = Instant::now();
|
||||
let result = Contracts::bare_instantiate(
|
||||
origin,
|
||||
value,
|
||||
gas_limit.unwrap_or(GAS_LIMIT),
|
||||
storage_deposit_limit.unwrap_or(DEPOSIT_LIMIT),
|
||||
code,
|
||||
data,
|
||||
salt.0,
|
||||
DebugInfo::Skip,
|
||||
CollectEvents::Skip,
|
||||
);
|
||||
results.push(CallResult::Instantiate {
|
||||
result,
|
||||
wall_time: time_start.elapsed(),
|
||||
code_hash,
|
||||
})
|
||||
}
|
||||
Upload {
|
||||
origin,
|
||||
code,
|
||||
storage_deposit_limit,
|
||||
} => Contracts::upload_code(
|
||||
RuntimeOrigin::signed(origin.to_account_id(&results)),
|
||||
match pallet_revive::Code::from(code) {
|
||||
pallet_revive::Code::Existing(_) => continue,
|
||||
pallet_revive::Code::Upload(bytes) => bytes,
|
||||
},
|
||||
storage_deposit_limit.unwrap_or(DEPOSIT_LIMIT),
|
||||
)
|
||||
.unwrap_or_else(|error| panic!("code upload failed: {error:?}")),
|
||||
Call {
|
||||
origin,
|
||||
dest,
|
||||
value,
|
||||
gas_limit,
|
||||
storage_deposit_limit,
|
||||
data,
|
||||
} => {
|
||||
let time_start = Instant::now();
|
||||
let result = Contracts::bare_call(
|
||||
RuntimeOrigin::signed(origin.to_account_id(&results)),
|
||||
dest.to_eth_addr(&results),
|
||||
value,
|
||||
gas_limit.unwrap_or(GAS_LIMIT),
|
||||
storage_deposit_limit.unwrap_or(DEPOSIT_LIMIT),
|
||||
data,
|
||||
DebugInfo::Skip,
|
||||
CollectEvents::Skip,
|
||||
);
|
||||
results.push(CallResult::Exec {
|
||||
result,
|
||||
wall_time: time_start.elapsed(),
|
||||
});
|
||||
}
|
||||
VerifyCall(expectation) => {
|
||||
expectation.verify(results.last().expect("No call to verify"));
|
||||
}
|
||||
VerifyBalance { origin, expected } => {
|
||||
let balance = Balances::usable_balance(origin.to_account_id(&results));
|
||||
assert_eq!(balance, expected);
|
||||
}
|
||||
VerifyStorage {
|
||||
contract,
|
||||
key,
|
||||
expected,
|
||||
} => {
|
||||
let address = contract.to_eth_addr(&results);
|
||||
let Ok(value) = Contracts::get_storage(address, key) else {
|
||||
panic!("error reading storage for address {address}");
|
||||
};
|
||||
let Some(value) = value else {
|
||||
panic!("no value at {address} key 0x{}", hex::encode(key));
|
||||
};
|
||||
assert_eq!(value, expected, "at key 0x{}", hex::encode(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
pub fn from_comment(contract_name: &str, path: &str) -> Vec<Self> {
|
||||
let solidity = match std::fs::read_to_string(path) {
|
||||
Err(err) => panic!("unable to read {path}: {err}"),
|
||||
Ok(solidity) => solidity,
|
||||
};
|
||||
let mut json_string = String::with_capacity(solidity.len());
|
||||
let mut is_reading = false;
|
||||
let mut specs = Vec::new();
|
||||
|
||||
for line in solidity.lines() {
|
||||
if line.starts_with(SPEC_MARKER_BEGIN) {
|
||||
is_reading = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_reading {
|
||||
if line.starts_with(SPEC_MARKER_END) {
|
||||
match serde_json::from_str::<Specs>(&json_string) {
|
||||
Ok(mut spec) => {
|
||||
spec.replace_empty_code(contract_name, path);
|
||||
specs.push(spec);
|
||||
}
|
||||
Err(e) => panic!("invalid spec JSON: {e}"),
|
||||
}
|
||||
is_reading = false;
|
||||
json_string.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
json_string.push_str(line)
|
||||
}
|
||||
}
|
||||
|
||||
assert!(!specs.is_empty(), "source does not contain any test spec");
|
||||
|
||||
specs
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "revive-runtime-api"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
description = "Implements the low level runtime API bindings with pallet contracts"
|
||||
|
||||
[features]
|
||||
riscv-64 = []
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] }
|
||||
|
||||
revive-common = { workspace = true }
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user