mirror of
https://github.com/pezkuwichain/revive.git
synced 2026-06-14 20:21:07 +00:00
Compare commits
9 Commits
remix
...
pvm-link-bug
| Author | SHA1 | Date | |
|---|---|---|---|
| 454108d1f1 | |||
| afd9f26aed | |||
| 698e4c7812 | |||
| a413238464 | |||
| d47539159b | |||
| 393d90165e | |||
| 7c934e5ca1 | |||
| d2f76b645f | |||
| 41c8d4e955 |
@@ -31,7 +31,10 @@ jobs:
|
|||||||
echo "$(pwd)/llvm18/bin" >> $GITHUB_PATH
|
echo "$(pwd)/llvm18/bin" >> $GITHUB_PATH
|
||||||
|
|
||||||
- name: Install apt dependencies
|
- 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
|
- name: Format
|
||||||
run: make format
|
run: make format
|
||||||
@@ -44,3 +47,9 @@ jobs:
|
|||||||
|
|
||||||
- name: Test CLI
|
- name: Test CLI
|
||||||
run: make test-cli
|
run: make test-cli
|
||||||
|
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ github.job }}-resolc
|
||||||
|
path: ./target/release/resolc
|
||||||
|
retention-days: 1
|
||||||
|
|||||||
Generated
+507
-509
File diff suppressed because it is too large
Load Diff
+14
-13
@@ -21,7 +21,7 @@ revive-integration = { version = "0.1.0", path = "crates/integration" }
|
|||||||
revive-linker = { version = "0.1.0", path = "crates/linker" }
|
revive-linker = { version = "0.1.0", path = "crates/linker" }
|
||||||
lld-sys = { version = "0.1.0", path = "crates/lld-sys" }
|
lld-sys = { version = "0.1.0", path = "crates/lld-sys" }
|
||||||
revive-llvm-context = { version = "0.1.0", path = "crates/llvm-context" }
|
revive-llvm-context = { version = "0.1.0", path = "crates/llvm-context" }
|
||||||
pallet-contracts-pvm-llapi = { version = "0.1.0", path = "crates/pallet-contracts-pvm-llapi" }
|
revive-runtime-api = { version = "0.1.0", path = "crates/runtime-api" }
|
||||||
revive-runner = { version = "0.1.0", path = "crates/runner" }
|
revive-runner = { version = "0.1.0", path = "crates/runner" }
|
||||||
revive-solidity = { version = "0.1.0", path = "crates/solidity" }
|
revive-solidity = { version = "0.1.0", path = "crates/solidity" }
|
||||||
revive-stdlib = { version = "0.1.0", path = "crates/stdlib" }
|
revive-stdlib = { version = "0.1.0", path = "crates/stdlib" }
|
||||||
@@ -50,30 +50,31 @@ path-slash = "0.2"
|
|||||||
rayon = "1.8"
|
rayon = "1.8"
|
||||||
clap = { version = "4", default-features = false, features = ["derive"] }
|
clap = { version = "4", default-features = false, features = ["derive"] }
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
polkavm-common = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
polkavm-common = "0.10"
|
||||||
polkavm-linker = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
polkavm-linker = "0.10"
|
||||||
polkavm-disassembler = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
polkavm-disassembler = "0.10"
|
||||||
polkavm = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
polkavm = "0.10"
|
||||||
alloy-primitives = "0.6"
|
alloy-primitives = { version = "0.8", features = ["serde"] }
|
||||||
alloy-sol-types = "0.6"
|
alloy-sol-types = "0.8"
|
||||||
|
alloy-genesis = "0.3"
|
||||||
|
alloy-serde = "0.3"
|
||||||
env_logger = { version = "0.10.0", default-features = false }
|
env_logger = { version = "0.10.0", default-features = false }
|
||||||
serde_stacker = "0.1"
|
serde_stacker = "0.1"
|
||||||
criterion = { version = "0.5", features = ["html_reports"] }
|
criterion = { version = "0.5", features = ["html_reports"] }
|
||||||
log = { version = "0.4" }
|
log = { version = "0.4" }
|
||||||
|
|
||||||
|
# polkadot-sdk and friends
|
||||||
codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
|
codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
|
||||||
scale-info = { version = "2.11.1", default-features = false }
|
scale-info = { version = "2.11.1", default-features = false }
|
||||||
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "559fa1db0594a81d5dbf343613ba2f3fc16708da" }
|
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", branch = "pg/repro" }
|
||||||
|
|
||||||
# Benchmarking against EVM
|
|
||||||
primitive-types = { version = "0.12", features = ["codec"] }
|
|
||||||
evm-interpreter = { git = "https://github.com/xermicus/evm.git", branch = "separate-compilation" }
|
|
||||||
|
|
||||||
|
# llvm
|
||||||
[workspace.dependencies.inkwell]
|
[workspace.dependencies.inkwell]
|
||||||
version = "0.5"
|
version = "0.5"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["serde", "llvm18-0", "no-libffi-linking", "target-riscv"]
|
features = ["serde", "llvm18-0", "no-libffi-linking", "target-riscv"]
|
||||||
|
|
||||||
[profile.benchmark]
|
[profile.bench]
|
||||||
inherits = "release"
|
inherits = "release"
|
||||||
lto = true
|
lto = true
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
|
|||||||
@@ -26,23 +26,16 @@ test-workspace: install
|
|||||||
test-cli: install
|
test-cli: install
|
||||||
npm run test:cli
|
npm run test:cli
|
||||||
|
|
||||||
bench-prepare: install-bin
|
bench-pvm: install-bin
|
||||||
cargo criterion --bench prepare --features bench-evm,bench-pvm --message-format=json \
|
cargo criterion --bench execute --features bench-pvm-interpreter --message-format=json \
|
||||||
| criterion-table > crates/benchmarks/PREPARE.md
|
| criterion-table > crates/benchmarks/PVM.md
|
||||||
|
|
||||||
bench-execute: install-bin
|
bench-evm: install-bin
|
||||||
cargo criterion --bench execute --features bench-evm,bench-pvm --message-format=json \
|
cargo criterion --bench execute --features bench-evm --message-format=json \
|
||||||
| criterion-table > crates/benchmarks/EXECUTE.md
|
| criterion-table > crates/benchmarks/EVM.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: install-bin
|
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
|
| criterion-table > crates/benchmarks/BENCHMARKS.md
|
||||||
|
|
||||||
clippy:
|
clippy:
|
||||||
|
|||||||
@@ -35,4 +35,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.
|
Ensure that your branch passes `make test` locally when submitting a pull request.
|
||||||
|
|
||||||
## Design overview
|
## 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).
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|
||||||
|
|||||||
@@ -9,17 +9,16 @@ description = "revive compiler benchmarks"
|
|||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["bench-pvm-interpreter"]
|
default = ["bench-pvm-interpreter"]
|
||||||
bench-pvm-interpreter = []
|
bench-pvm-interpreter = ["revive-runner"]
|
||||||
bench-pvm = []
|
|
||||||
bench-evm = ["revive-differential"]
|
bench-evm = ["revive-differential"]
|
||||||
bench-extensive = []
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
hex = { workspace = true }
|
hex = { workspace = true }
|
||||||
polkavm = { workspace = true }
|
alloy-primitives = { workspace = true }
|
||||||
|
|
||||||
revive-integration = { workspace = true }
|
revive-integration = { workspace = true }
|
||||||
revive-differential = { workspace = true, optional = true }
|
revive-differential = { workspace = true, optional = true }
|
||||||
alloy-primitives = { workspace = true }
|
revive-runner = { workspace = true, optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
criterion = { workspace = true }
|
criterion = { workspace = true }
|
||||||
@@ -27,7 +26,3 @@ criterion = { workspace = true }
|
|||||||
[[bench]]
|
[[bench]]
|
||||||
name = "execute"
|
name = "execute"
|
||||||
harness = false
|
harness = false
|
||||||
|
|
||||||
[[bench]]
|
|
||||||
name = "prepare"
|
|
||||||
harness = false
|
|
||||||
|
|||||||
@@ -1,104 +1,42 @@
|
|||||||
|
#![cfg(any(feature = "bench-pvm-interpreter", feature = "bench-evm"))]
|
||||||
|
|
||||||
use alloy_primitives::U256;
|
use alloy_primitives::U256;
|
||||||
use criterion::{
|
use criterion::{
|
||||||
criterion_group, criterion_main, measurement::Measurement, BenchmarkGroup, BenchmarkId,
|
criterion_group, criterion_main,
|
||||||
Criterion,
|
measurement::{Measurement, WallTime},
|
||||||
|
BenchmarkGroup, BenchmarkId, Criterion,
|
||||||
};
|
};
|
||||||
use revive_integration::cases::Contract;
|
use revive_integration::cases::Contract;
|
||||||
|
|
||||||
fn bench<P, L, I, M>(mut group: BenchmarkGroup<'_, M>, parameters: &[P], labels: &[L], contract: I)
|
fn bench<P, L, I>(
|
||||||
where
|
mut group: BenchmarkGroup<'_, WallTime>,
|
||||||
|
parameters: &[P],
|
||||||
|
labels: &[L],
|
||||||
|
contract: I,
|
||||||
|
) where
|
||||||
P: Clone,
|
P: Clone,
|
||||||
L: std::fmt::Display,
|
L: std::fmt::Display,
|
||||||
I: Fn(P) -> Contract,
|
I: Fn(P) -> Contract,
|
||||||
M: Measurement,
|
|
||||||
{
|
{
|
||||||
assert_eq!(parameters.len(), labels.len());
|
assert_eq!(parameters.len(), labels.len());
|
||||||
|
|
||||||
|
group.sample_size(10);
|
||||||
|
|
||||||
for (p, l) in parameters.iter().zip(labels.iter()) {
|
for (p, l) in parameters.iter().zip(labels.iter()) {
|
||||||
|
let contract = contract(p.clone());
|
||||||
|
|
||||||
#[cfg(feature = "bench-evm")]
|
#[cfg(feature = "bench-evm")]
|
||||||
{
|
group.bench_with_input(BenchmarkId::new("EVM", l), p, |b, _| {
|
||||||
let contract = contract(p.clone());
|
let code = &contract.evm_runtime;
|
||||||
group.bench_with_input(BenchmarkId::new("EVM", l), p, move |b, _| {
|
let input = &contract.calldata;
|
||||||
b.iter(|| {
|
b.iter_custom(|iters| revive_benchmarks::measure_evm(code, input, iters));
|
||||||
revive_differential::execute(revive_differential::prepare(
|
|
||||||
contract.evm_runtime.clone(),
|
|
||||||
contract.calldata.clone(),
|
|
||||||
));
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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")]
|
#[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, _| {
|
group.bench_with_input(BenchmarkId::new("PVMInterpreter", l), p, |b, _| {
|
||||||
b.iter(|| {
|
let specs = revive_benchmarks::create_specs(&contract);
|
||||||
let (mut instance, export) = instantiate_module(&module, &engine);
|
b.iter_custom(|iters| revive_benchmarks::measure_pvm(&specs, iters));
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
group.finish();
|
group.finish();
|
||||||
@@ -108,14 +46,6 @@ fn group<'error, M>(c: &'error mut Criterion<M>, group_name: &str) -> BenchmarkG
|
|||||||
where
|
where
|
||||||
M: Measurement,
|
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);
|
return c.benchmark_group(group_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,33 +58,21 @@ fn bench_baseline(c: &mut Criterion) {
|
|||||||
|
|
||||||
fn bench_odd_product(c: &mut Criterion) {
|
fn bench_odd_product(c: &mut Criterion) {
|
||||||
let group = group(c, "OddPorduct");
|
let group = group(c, "OddPorduct");
|
||||||
#[cfg(feature = "bench-extensive")]
|
let parameters = &[10_000, 100_000, 300000];
|
||||||
let parameters = &[300000, 1200000, 12000000, 180000000, 720000000];
|
|
||||||
#[cfg(not(feature = "bench-extensive"))]
|
|
||||||
let parameters = &[10_000, 100_000];
|
|
||||||
|
|
||||||
bench(group, parameters, parameters, Contract::odd_product);
|
bench(group, parameters, parameters, Contract::odd_product);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bench_triangle_number(c: &mut Criterion) {
|
fn bench_triangle_number(c: &mut Criterion) {
|
||||||
let group = group(c, "TriangleNumber");
|
let group = group(c, "TriangleNumber");
|
||||||
#[cfg(feature = "bench-extensive")]
|
let parameters = &[10_000, 100_000, 360000];
|
||||||
let parameters = &[360000, 1440000, 14400000, 216000000, 864000000];
|
|
||||||
#[cfg(not(feature = "bench-extensive"))]
|
|
||||||
let parameters = &[10_000, 100_000];
|
|
||||||
|
|
||||||
bench(group, parameters, parameters, Contract::triangle_number);
|
bench(group, parameters, parameters, Contract::triangle_number);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bench_fibonacci_recurisve(c: &mut Criterion) {
|
fn bench_fibonacci_recurisve(c: &mut Criterion) {
|
||||||
let group = group(c, "FibonacciRecursive");
|
let group = group(c, "FibonacciRecursive");
|
||||||
#[cfg(feature = "bench-extensive")]
|
let parameters = [12, 16, 20, 24]
|
||||||
let parameters = [24, 27, 31, 36, 39]
|
|
||||||
.iter()
|
|
||||||
.map(|p| U256::from(*p))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
#[cfg(not(feature = "bench-extensive"))]
|
|
||||||
let parameters = [12, 16, 20]
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| U256::from(*p))
|
.map(|p| U256::from(*p))
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@@ -164,12 +82,6 @@ fn bench_fibonacci_recurisve(c: &mut Criterion) {
|
|||||||
|
|
||||||
fn bench_fibonacci_iterative(c: &mut Criterion) {
|
fn bench_fibonacci_iterative(c: &mut Criterion) {
|
||||||
let group = group(c, "FibonacciIterative");
|
let group = group(c, "FibonacciIterative");
|
||||||
#[cfg(feature = "bench-extensive")]
|
|
||||||
let parameters = [256, 162500, 650000, 6500000, 100000000, 400000000]
|
|
||||||
.iter()
|
|
||||||
.map(|p| U256::from(*p))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
#[cfg(not(feature = "bench-extensive"))]
|
|
||||||
let parameters = [64, 128, 256]
|
let parameters = [64, 128, 256]
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| U256::from(*p))
|
.map(|p| U256::from(*p))
|
||||||
@@ -193,7 +105,9 @@ fn bench_sha1(c: &mut Criterion) {
|
|||||||
let parameters = &[vec![0xff], vec![0xff; 64], vec![0xff; 512]];
|
let parameters = &[vec![0xff], vec![0xff; 64], vec![0xff; 512]];
|
||||||
let labels = parameters.iter().map(|p| p.len()).collect::<Vec<_>>();
|
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!(
|
criterion_group!(
|
||||||
|
|||||||
@@ -1,171 +0,0 @@
|
|||||||
use alloy_primitives::U256;
|
|
||||||
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(U256::ZERO).evm_runtime,
|
|
||||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
|
||||||
Contract::fib_recursive(U256::ZERO).pvm_runtime,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_fibonacci_iterative(c: &mut Criterion) {
|
|
||||||
bench(
|
|
||||||
c,
|
|
||||||
"PrepareFibonacciIterative",
|
|
||||||
#[cfg(feature = "bench-evm")]
|
|
||||||
Contract::fib_iterative(U256::ZERO).evm_runtime,
|
|
||||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
|
||||||
Contract::fib_iterative(U256::ZERO).pvm_runtime,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_fibonacci_binet(c: &mut Criterion) {
|
|
||||||
bench(
|
|
||||||
c,
|
|
||||||
"PrepareFibonacciBinet",
|
|
||||||
#[cfg(feature = "bench-evm")]
|
|
||||||
Contract::fib_binet(U256::ZERO).evm_runtime,
|
|
||||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
|
||||||
Contract::fib_binet(U256::ZERO).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,28 +1,70 @@
|
|||||||
use polkavm::{BackendKind, Config, Engine, ExportIndex, Instance, SandboxKind};
|
#[cfg(feature = "bench-pvm-interpreter")]
|
||||||
use revive_integration::mock_runtime::{self, TransactionBuilder};
|
pub fn create_specs(contract: &revive_integration::cases::Contract) -> revive_runner::Specs {
|
||||||
use revive_integration::mock_runtime::{State, Transaction};
|
use revive_runner::*;
|
||||||
|
use SpecsAction::*;
|
||||||
pub fn prepare_pvm(
|
Specs {
|
||||||
code: &[u8],
|
differential: false,
|
||||||
input: Vec<u8>,
|
actions: vec![
|
||||||
backend: BackendKind,
|
Instantiate {
|
||||||
) -> (TransactionBuilder, Instance<Transaction>, ExportIndex) {
|
code: Code::Bytes(contract.pvm_runtime.to_vec()),
|
||||||
let mut config = Config::new();
|
origin: TestAddress::Alice,
|
||||||
config.set_backend(Some(backend));
|
data: Default::default(),
|
||||||
config.set_sandbox(Some(SandboxKind::Linux));
|
value: Default::default(),
|
||||||
|
gas_limit: Default::default(),
|
||||||
let (instance, export_index) = mock_runtime::prepare(code, Some(config));
|
storage_deposit_limit: Default::default(),
|
||||||
let transaction = State::default()
|
salt: Default::default(),
|
||||||
.transaction()
|
},
|
||||||
.with_default_account(code)
|
Call {
|
||||||
.calldata(input);
|
origin: TestAddress::Alice,
|
||||||
|
dest: TestAddress::Instantiated(0),
|
||||||
(transaction, instance, export_index)
|
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 {
|
#[cfg(feature = "bench-pvm-interpreter")]
|
||||||
let mut config = Config::new();
|
pub fn measure_pvm(specs: &revive_runner::Specs, iters: u64) -> std::time::Duration {
|
||||||
config.set_backend(Some(backend));
|
use revive_runner::*;
|
||||||
config.set_sandbox(Some(SandboxKind::Linux));
|
let mut total_time = std::time::Duration::default();
|
||||||
mock_runtime::setup(Some(config))
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ pub const BYTE_LENGTH_WORD: usize = 32;
|
|||||||
pub const BYTE_LENGTH_VALUE: usize = 32;
|
pub const BYTE_LENGTH_VALUE: usize = 32;
|
||||||
|
|
||||||
/// Byte length of the runtime block number type.
|
/// 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.
|
/// Byte length of the runtime block timestamp type.
|
||||||
pub const BYTE_LENGTH_BLOCK_TIMESTAMP: usize = 8;
|
pub const BYTE_LENGTH_BLOCK_TIMESTAMP: usize = 4;
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ authors.workspace = true
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
evm-interpreter = { workspace = true }
|
hex = { workspace = true }
|
||||||
primitive-types = { workspace = true }
|
tempfile = { workspace = true }
|
||||||
alloy-primitives = { 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,30 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"chainId": 1,
|
||||||
|
"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": {}
|
||||||
|
}
|
||||||
@@ -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")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+542
-131
@@ -1,159 +1,570 @@
|
|||||||
use alloy_primitives::{keccak256, Address, B256};
|
use core::str;
|
||||||
use evm_interpreter::{
|
use std::{
|
||||||
interpreter::{EtableInterpreter, RunInterpreter},
|
collections::BTreeMap,
|
||||||
trap::CallCreateTrap,
|
io::Write,
|
||||||
Context, Etable, ExitError, Log, Machine, RuntimeBackend, RuntimeBaseBackend,
|
path::PathBuf,
|
||||||
RuntimeEnvironment, RuntimeState, TransactionContext, Valids,
|
process::{Command, Stdio},
|
||||||
|
str::FromStr,
|
||||||
|
time::Duration,
|
||||||
};
|
};
|
||||||
use primitive_types::{H160, H256, U256};
|
|
||||||
|
|
||||||
static RUNTIME_ETABLE: Etable<RuntimeState, UnimplementedHandler, CallCreateTrap> =
|
use alloy_genesis::{Genesis, GenesisAccount};
|
||||||
Etable::runtime();
|
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 use self::go_duration::parse_go_duration;
|
||||||
pub struct UnimplementedHandler {
|
|
||||||
logs: Vec<Log>,
|
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: execution reverted";
|
||||||
|
|
||||||
|
/// 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 {
|
impl From<StateDump> for Genesis {
|
||||||
fn block_hash(&self, _number: U256) -> H256 {
|
fn from(value: StateDump) -> Self {
|
||||||
unimplemented!()
|
let mut genesis: Genesis = serde_json::from_str(GENESIS_JSON).unwrap();
|
||||||
}
|
genesis.alloc = value
|
||||||
fn block_number(&self) -> U256 {
|
.accounts
|
||||||
U256::from(123)
|
.iter()
|
||||||
}
|
.map(|(address, account)| (*address, account.clone().into()))
|
||||||
fn block_coinbase(&self) -> H160 {
|
.collect();
|
||||||
unimplemented!()
|
genesis
|
||||||
}
|
|
||||||
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 RuntimeBaseBackend for UnimplementedHandler {
|
/// The geth EVM state dump account structure
|
||||||
fn balance(&self, _address: H160) -> U256 {
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
unimplemented!()
|
pub struct Account {
|
||||||
}
|
pub balance: U256,
|
||||||
fn code_size(&self, _address: H160) -> U256 {
|
pub nonce: u64,
|
||||||
unimplemented!()
|
pub code: Option<Bytes>,
|
||||||
}
|
#[serde(
|
||||||
fn code_hash(&self, _address: H160) -> H256 {
|
default,
|
||||||
unimplemented!()
|
skip_serializing_if = "Option::is_none",
|
||||||
}
|
deserialize_with = "deserialize_storage_map"
|
||||||
fn code(&self, _address: H160) -> Vec<u8> {
|
)]
|
||||||
unimplemented!()
|
pub storage: Option<BTreeMap<B256, B256>>,
|
||||||
}
|
pub key: Option<B256>,
|
||||||
fn storage(&self, _address: H160, _index: H256) -> H256 {
|
}
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exists(&self, _address: H160) -> bool {
|
impl From<Account> for GenesisAccount {
|
||||||
unimplemented!()
|
fn from(value: Account) -> Self {
|
||||||
|
GenesisAccount {
|
||||||
|
balance: value.balance,
|
||||||
|
nonce: Some(value.nonce),
|
||||||
|
code: value.code,
|
||||||
|
storage: value.storage,
|
||||||
|
private_key: value.key,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn nonce(&self, _address: H160) -> U256 {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeBackend for UnimplementedHandler {
|
/// Contains the output from geth `emv` invocations
|
||||||
fn original_storage(&self, _address: H160, _index: H256) -> H256 {
|
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||||
unimplemented!()
|
pub struct EvmOutput {
|
||||||
}
|
pub output: Bytes,
|
||||||
|
#[serde(rename = "gasUsed")]
|
||||||
|
pub gas_used: U256,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
fn deleted(&self, _address: H160) -> bool {
|
impl EvmOutput {
|
||||||
unimplemented!()
|
/// Return if there was no error found.
|
||||||
}
|
///
|
||||||
fn is_cold(&self, _address: H160, _index: Option<H256>) -> bool {
|
/// Panics if the gas used is zero as this indicates nothing was run, i.e.
|
||||||
unimplemented!()
|
/// there was no receiving account but still no error is reported.
|
||||||
}
|
pub fn run_success(&self) -> bool {
|
||||||
|
assert_ne!(self.gas_used, U256::ZERO, "nothing was executed");
|
||||||
fn mark_hot(&mut self, _address: H160, _index: Option<H256>) {
|
self.error.is_none()
|
||||||
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)]
|
/// Contains the full log from geth `emv` invocations
|
||||||
pub struct PreparedEvm {
|
#[derive(Clone, Debug)]
|
||||||
pub valids: Valids,
|
pub struct EvmLog {
|
||||||
pub vm: Machine<RuntimeState>,
|
pub account_deployed: Option<Address>,
|
||||||
|
pub output: EvmOutput,
|
||||||
|
pub state_dump: StateDump,
|
||||||
|
pub stderr: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn prepare(code: Vec<u8>, data: Vec<u8>) -> PreparedEvm {
|
impl EvmLog {
|
||||||
let address = Address::default().create2(B256::default(), keccak256([]).0);
|
pub const EXECUTION_TIME_MARKER: &'static str = "execution time:";
|
||||||
let caller = Address::default().create2(B256::default(), keccak256([]).0);
|
|
||||||
|
|
||||||
let state = RuntimeState {
|
/// Parse the reported execution time from stderr (requires --bench)
|
||||||
context: Context {
|
pub fn execution_time(&self) -> Result<Duration, String> {
|
||||||
address: H160::from(address.0 .0),
|
for line in self.stderr.lines() {
|
||||||
caller: H160::from(caller.0 .0),
|
if let Some(value) = line.split("execution time:").nth(1) {
|
||||||
apparent_value: U256::default(),
|
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()
|
||||||
},
|
},
|
||||||
transaction_context: TransactionContext {
|
state_dump: Default::default(),
|
||||||
gas_price: U256::default(),
|
stderr: Default::default(),
|
||||||
origin: H160::default(),
|
|
||||||
}
|
}
|
||||||
.into(),
|
}
|
||||||
retbuf: Vec::new(),
|
}
|
||||||
|
|
||||||
|
/// 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);
|
||||||
};
|
};
|
||||||
|
|
||||||
PreparedEvm {
|
// Dynamic args
|
||||||
valids: Valids::new(&code[..]),
|
command.args(["--prestate", genesis_json_path]);
|
||||||
vm: evm_interpreter::Machine::new(code.into(), data.to_vec().into(), 1024, 0xFFFF, state),
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn execute(pre: PreparedEvm) -> (Vec<u8>, Vec<Log>) {
|
#[cfg(test)]
|
||||||
let mut vm = EtableInterpreter::new_valid(pre.vm, &RUNTIME_ETABLE, pre.valids);
|
mod tests {
|
||||||
let mut handler = UnimplementedHandler::default();
|
use std::{str::FromStr, time::Duration};
|
||||||
vm.run(&mut handler).exit().unwrap().unwrap();
|
|
||||||
(vm.retval.clone(), handler.logs)
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,11 +14,13 @@ alloy-sol-types = { workspace = true }
|
|||||||
hex = { workspace = true }
|
hex = { workspace = true }
|
||||||
env_logger = { workspace = true }
|
env_logger = { workspace = true }
|
||||||
log = { workspace = true }
|
log = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
|
||||||
revive-solidity = { workspace = true }
|
revive-solidity = { workspace = true }
|
||||||
revive-differential = { workspace = true }
|
revive-differential = { workspace = true }
|
||||||
revive-llvm-context = { workspace = true }
|
revive-llvm-context = { workspace = true }
|
||||||
revive-common = { workspace = true }
|
revive-common = { workspace = true }
|
||||||
|
revive-runner = { workspace = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
sha1 = { workspace = true }
|
sha1 = { workspace = true }
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"Baseline": 934,
|
"Baseline": 878,
|
||||||
"Computation": 4360,
|
"Computation": 4305,
|
||||||
"DivisionArithmetics": 39824,
|
"DivisionArithmetics": 39774,
|
||||||
"ERC20": 46471,
|
"ERC20": 53405,
|
||||||
"Events": 1749,
|
"Events": 1693,
|
||||||
"FibonacciIterative": 2973,
|
"FibonacciIterative": 2917,
|
||||||
"Flipper": 3563,
|
"Flipper": 3570,
|
||||||
"SHA1": 32543
|
"SHA1": 32557
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,20 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
|
||||||
|
{
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"origin": "Alice",
|
||||||
|
"value": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
contract Baseline {
|
contract Baseline {
|
||||||
|
|||||||
@@ -2,6 +2,31 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"differential": true,
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"code": {
|
||||||
|
"Solidity": {
|
||||||
|
"contract": "Bitwise"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "3fa4f245"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
contract Bitwise {
|
contract Bitwise {
|
||||||
function opByte(uint i, uint x) public payable returns (uint ret) {
|
function opByte(uint i, uint x) public payable returns (uint ret) {
|
||||||
assembly {
|
assembly {
|
||||||
|
|||||||
@@ -2,12 +2,49 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
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 {
|
contract Block {
|
||||||
function timestamp() public view returns (uint ret) {
|
function timestamp() public view returns (uint ret) {
|
||||||
ret = block.timestamp;
|
ret = block.timestamp;
|
||||||
}
|
}
|
||||||
|
|
||||||
function number() public view returns (uint ret) {
|
function number() public view returns (uint ret) {
|
||||||
|
if (block.number == 0) {
|
||||||
|
ret = 1;
|
||||||
|
} else {
|
||||||
ret = block.number;
|
ret = block.number;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,44 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
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 {
|
contract Computation {
|
||||||
function triangle_number(int64 n) public pure returns (int64 sum) {
|
function triangle_number(int64 n) public pure returns (int64 sum) {
|
||||||
unchecked {
|
unchecked {
|
||||||
|
|||||||
@@ -2,6 +2,39 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
contract Context {
|
contract Context {
|
||||||
function address_this() public view returns (address ret) {
|
function address_this() public view returns (address ret) {
|
||||||
ret = address(this);
|
ret = address(this);
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
pragma solidity ^0.8.24;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "f9fbd5540000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c68656c6c6f20776f726c64210000000000000000000000000000000000000000"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"VerifyCall": {
|
||||||
|
"success": true,
|
||||||
|
"output": "57caa176af1ac0433c5df30e8dabcd2ec1af1e92a26eced5f719b88458777cd6"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
contract TestSha3 {
|
||||||
|
function test(string memory _pre) external payable returns (bytes32 hash) {
|
||||||
|
hash = keccak256(bytes(_pre));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,16 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol
|
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol
|
||||||
interface IERC20 {
|
interface IERC20 {
|
||||||
function totalSupply() external view returns (uint);
|
function totalSupply() external view returns (uint);
|
||||||
|
|||||||
@@ -2,6 +2,43 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"differential": true,
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"code": {
|
||||||
|
"Solidity": {
|
||||||
|
"contract": "Events"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "4d43bec90000000000000000000000000000000000000000000000000000000000000000"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* TODO when pallet_revive accepts Solidity event topics
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "4d43bec9000000000000000000000000000000000000000000000000000000000000007b"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
contract Events {
|
contract Events {
|
||||||
event A() anonymous;
|
event A() anonymous;
|
||||||
event E(uint, uint indexed, uint indexed, uint indexed);
|
event E(uint, uint indexed, uint indexed, uint indexed);
|
||||||
|
|||||||
@@ -2,7 +2,29 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
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 {
|
contract FibonacciRecursive {
|
||||||
function f(uint n) internal pure returns (uint) {
|
function f(uint n) internal pure returns (uint) {
|
||||||
@@ -36,6 +58,7 @@ contract FibonacciIterative {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// https://medium.com/coinmonks/fibonacci-in-solidity-8477d907e22a
|
||||||
contract FibonacciBinet {
|
contract FibonacciBinet {
|
||||||
function fib3(uint n) external pure returns (uint a) {
|
function fib3(uint n) external pure returns (uint a) {
|
||||||
if (n == 0) {
|
if (n == 0) {
|
||||||
|
|||||||
@@ -2,6 +2,31 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"differential": true,
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"code": {
|
||||||
|
"Solidity": {
|
||||||
|
"contract": "MCopy"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "0ee188b0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000030102030000000000000000000000000000000000000000000000000000000000"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
contract MCopy {
|
contract MCopy {
|
||||||
function memcpy(bytes memory payload) public pure returns (bytes memory) {
|
function memcpy(bytes memory payload) public pure returns (bytes memory) {
|
||||||
return payload;
|
return payload;
|
||||||
|
|||||||
@@ -2,6 +2,51 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"code": {
|
||||||
|
"Solidity": {
|
||||||
|
"contract": "MSize",
|
||||||
|
"solc_optimizer": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "f016832c"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"VerifyCall": {
|
||||||
|
"success": true,
|
||||||
|
"output": "0000000000000000000000000000000000000000000000000000000000000060"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "f4a63aa5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"VerifyCall": {
|
||||||
|
"success": true,
|
||||||
|
"output": "0000000000000000000000000000000000000000000000000000000000000084"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
contract MSize {
|
contract MSize {
|
||||||
uint[] public data;
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,31 @@
|
|||||||
// SPDX-License-Identifier: BSD-2-Clause
|
// SPDX-License-Identifier: BSD-2-Clause
|
||||||
pragma solidity ^0.8.4;
|
pragma solidity ^0.8.4;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"differential": true,
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"code": {
|
||||||
|
"Solidity": {
|
||||||
|
"contract": "SHA1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "1605782b00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000200ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
contract SHA1 {
|
contract SHA1 {
|
||||||
function sha1(bytes memory data) public pure returns (bytes20 ret) {
|
function sha1(bytes memory data) public pure returns (bytes20 ret) {
|
||||||
assembly {
|
assembly {
|
||||||
|
|||||||
@@ -2,6 +2,31 @@
|
|||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"differential": true,
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"code": {
|
||||||
|
"Solidity": {
|
||||||
|
"contract": "Storage"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "fabc9efaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
contract Storage {
|
contract Storage {
|
||||||
function transient(uint value) public returns (uint ret) {
|
function transient(uint value) public returns (uint ret) {
|
||||||
assembly {
|
assembly {
|
||||||
|
|||||||
@@ -1,7 +1,31 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
pragma solidity ^0.8;
|
pragma solidity ^0.8;
|
||||||
|
|
||||||
|
/* runner.json
|
||||||
|
{
|
||||||
|
"differential": true,
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"Instantiate": {
|
||||||
|
"code": {
|
||||||
|
"Solidity": {
|
||||||
|
"contract": "Value"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Call": {
|
||||||
|
"dest": {
|
||||||
|
"Instantiated": 0
|
||||||
|
},
|
||||||
|
"data": "3fa4f245"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
contract Value {
|
contract Value {
|
||||||
function value() public payable returns (uint ret) {
|
function value() public payable returns (uint ret) {
|
||||||
ret = msg.value;
|
ret = msg.value;
|
||||||
|
|||||||
@@ -1,6 +1,44 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
pragma solidity ^0.8;
|
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 {
|
contract Flipper {
|
||||||
bool coin;
|
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
use alloy_primitives::{Address, I256, U256};
|
use alloy_primitives::{Address, Bytes, I256, U256};
|
||||||
use alloy_sol_types::{sol, SolCall, SolConstructor};
|
use alloy_sol_types::{sol, SolCall, SolConstructor};
|
||||||
|
|
||||||
use revive_solidity::test_utils::*;
|
use revive_solidity::test_utils::*;
|
||||||
|
|
||||||
use crate::mock_runtime::{CallOutput, State};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Contract {
|
pub struct Contract {
|
||||||
pub name: &'static str,
|
pub name: &'static str,
|
||||||
@@ -93,7 +91,7 @@ sol!(
|
|||||||
function sha1(bytes memory data) public pure returns (bytes20 ret);
|
function sha1(bytes memory data) public pure returns (bytes20 ret);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
case!("SHA1.sol", SHA1, sha1Call, sha1, pre: Vec<u8>);
|
case!("SHA1.sol", SHA1, sha1Call, sha1, pre: Bytes);
|
||||||
|
|
||||||
sol!(
|
sol!(
|
||||||
contract ERC20 {
|
contract ERC20 {
|
||||||
@@ -163,7 +161,7 @@ sol!(
|
|||||||
function mStore8(uint value) public pure returns (uint256 word);
|
function mStore8(uint value) public pure returns (uint256 word);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
case!("mStore8.sol", MStore8, mStore8Call, mstore8, value: U256);
|
case!("MStore8.sol", MStore8, mStore8Call, mstore8, value: U256);
|
||||||
|
|
||||||
sol!(
|
sol!(
|
||||||
contract Events {
|
contract Events {
|
||||||
@@ -190,7 +188,7 @@ sol!(
|
|||||||
function memcpy(bytes memory payload) public pure returns (bytes memory);
|
function memcpy(bytes memory payload) public pure returns (bytes memory);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
case!("MCopy.sol", MCopy, memcpyCall, memcpy, payload: Vec<u8>);
|
case!("MCopy.sol", MCopy, memcpyCall, memcpy, payload: Bytes);
|
||||||
|
|
||||||
sol!(
|
sol!(
|
||||||
contract Call {
|
contract Call {
|
||||||
@@ -205,7 +203,7 @@ sol!(
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
case!("Call.sol", Call, value_transferCall, call_value_transfer, destination: Address);
|
case!("Call.sol", Call, value_transferCall, call_value_transfer, destination: Address);
|
||||||
case!("Call.sol", Call, callCall, call_call, destination: Address, payload: Vec<u8>);
|
case!("Call.sol", Call, callCall, call_call, destination: Address, payload: Bytes);
|
||||||
case!("Call.sol", "Call", vec![], call_constructor);
|
case!("Call.sol", "Call", vec![], call_constructor);
|
||||||
|
|
||||||
sol!(
|
sol!(
|
||||||
@@ -230,24 +228,6 @@ sol!(
|
|||||||
case!("Storage.sol", Storage, transientCall, storage_transient, value: U256);
|
case!("Storage.sol", Storage, transientCall, storage_transient, value: U256);
|
||||||
|
|
||||||
impl Contract {
|
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()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build(calldata: Vec<u8>, name: &'static str, code: &str) -> Self {
|
fn build(calldata: Vec<u8>, name: &'static str, code: &str) -> Self {
|
||||||
Self {
|
Self {
|
||||||
name,
|
name,
|
||||||
@@ -260,7 +240,7 @@ impl Contract {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use alloy_primitives::U256;
|
use alloy_primitives::{Bytes, U256};
|
||||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||||
use serde::{de::Deserialize, Serialize};
|
use serde::{de::Deserialize, Serialize};
|
||||||
use std::{collections::BTreeMap, fs::File};
|
use std::{collections::BTreeMap, fs::File};
|
||||||
@@ -305,7 +285,7 @@ mod tests {
|
|||||||
(|| Contract::odd_product(0)) as fn() -> Contract,
|
(|| Contract::odd_product(0)) as fn() -> Contract,
|
||||||
(|| Contract::fib_iterative(U256::ZERO)) as fn() -> Contract,
|
(|| Contract::fib_iterative(U256::ZERO)) as fn() -> Contract,
|
||||||
Contract::erc20 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::division_arithmetics_div(U256::ZERO, U256::ZERO)) as fn() -> Contract,
|
||||||
(|| Contract::event(U256::ZERO)) as fn() -> Contract,
|
(|| Contract::event(U256::ZERO)) as fn() -> Contract,
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,42 +1,4 @@
|
|||||||
use alloy_primitives::{Address, U256};
|
|
||||||
use cases::Contract;
|
|
||||||
use mock_runtime::{CallOutput, State};
|
|
||||||
|
|
||||||
use crate::mock_runtime::{Event, ReturnFlags};
|
|
||||||
|
|
||||||
pub mod cases;
|
pub mod cases;
|
||||||
pub mod mock_runtime;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|
||||||
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
+192
-443
@@ -1,439 +1,260 @@
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use alloy_primitives::{keccak256, Address, FixedBytes, B256, I256, U256};
|
use alloy_primitives::*;
|
||||||
use alloy_sol_types::{sol, SolCall, SolValue};
|
use revive_runner::*;
|
||||||
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
|
use SpecsAction::*;
|
||||||
use sha1::Digest;
|
|
||||||
|
|
||||||
use revive_solidity::test_utils::*;
|
use crate::cases::Contract;
|
||||||
|
|
||||||
use crate::{
|
macro_rules! test_spec {
|
||||||
assert_success,
|
($test_name:ident, $contract_name:literal, $source_file:literal) => {
|
||||||
cases::Contract,
|
#[test]
|
||||||
mock_runtime::{self, ReturnFlags, State, Transaction},
|
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);
|
||||||
#[test]
|
Specs::from_comment($contract_name, &path).remove(0).run();
|
||||||
fn fibonacci() {
|
|
||||||
let parameter = 6;
|
|
||||||
|
|
||||||
for contract in [
|
|
||||||
Contract::fib_recursive(U256::from(parameter)),
|
|
||||||
Contract::fib_iterative(U256::from(parameter)),
|
|
||||||
Contract::fib_binet(U256::from(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]
|
test_spec!(baseline, "Baseline", "Baseline.sol");
|
||||||
fn flipper() {
|
test_spec!(flipper, "Flipper", "flipper.sol");
|
||||||
let (state, address) = State::new_deployed(Contract::flipper_constructor(true));
|
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!(transferred_value, "Value", "Value.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");
|
||||||
|
|
||||||
let contract = Contract::flipper();
|
fn instantiate(path: &str, contract: &str) -> Vec<SpecsAction> {
|
||||||
let (state, output) = state
|
vec![Instantiate {
|
||||||
.transaction()
|
origin: TestAddress::Alice,
|
||||||
.calldata(contract.calldata.clone())
|
value: 0,
|
||||||
.callee(address)
|
gas_limit: Some(GAS_LIMIT),
|
||||||
.call();
|
storage_deposit_limit: None,
|
||||||
assert_eq!(output.flags, ReturnFlags::Success);
|
code: Code::Solidity {
|
||||||
state.assert_storage_key(address, U256::ZERO, U256::ZERO);
|
path: Some(path.into()),
|
||||||
|
contract: contract.to_string(),
|
||||||
let (state, output) = state
|
solc_optimizer: None,
|
||||||
.transaction()
|
pipeline: None,
|
||||||
.calldata(contract.calldata)
|
},
|
||||||
.callee(address)
|
data: vec![],
|
||||||
.call();
|
salt: OptionalHex::default(),
|
||||||
assert_eq!(output.flags, ReturnFlags::Success);
|
}]
|
||||||
state.assert_storage_key(address, U256::ZERO, U256::from(1));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
fn run_differential(actions: Vec<SpecsAction>) {
|
||||||
fn hash_keccak_256() {
|
Specs {
|
||||||
sol!(
|
differential: true,
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
actions,
|
||||||
contract TestSha3 {
|
..Default::default()
|
||||||
function test(string memory _pre) external payable returns (bytes32);
|
|
||||||
}
|
}
|
||||||
);
|
.run();
|
||||||
let source = r#"contract TestSha3 {
|
|
||||||
function test(string memory _pre) external payable returns (bytes32 hash) {
|
|
||||||
hash = keccak256(bytes(_pre));
|
|
||||||
}
|
|
||||||
}"#;
|
|
||||||
let code = 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]
|
#[test]
|
||||||
fn erc20() {
|
fn bitwise_byte() {
|
||||||
let _ = compile_blob("ERC20", include_str!("../contracts/ERC20.sol"));
|
let mut actions = instantiate("contracts/Bitwise.sol", "Bitwise");
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
let de_bruijn_sequence =
|
||||||
fn triangle_number() {
|
hex::decode("4060503824160d0784426150b864361d0f88c4a27148ac5a2f198d46e391d8f4").unwrap();
|
||||||
let (_, output) = assert_success(&Contract::triangle_number(13), true);
|
let value = U256::from_be_bytes::<32>(de_bruijn_sequence.clone().try_into().unwrap());
|
||||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
for input in de_bruijn_sequence
|
||||||
let expected = U256::try_from(91).unwrap();
|
.iter()
|
||||||
assert_eq!(received, expected);
|
.enumerate()
|
||||||
}
|
.map(|(index, _)| Contract::bitwise_byte(U256::from(index), value).calldata)
|
||||||
|
.chain([
|
||||||
#[test]
|
Contract::bitwise_byte(U256::ZERO, U256::ZERO).calldata,
|
||||||
fn odd_product() {
|
Contract::bitwise_byte(U256::ZERO, U256::MAX).calldata,
|
||||||
let (_, output) = assert_success(&Contract::odd_product(5), true);
|
Contract::bitwise_byte(U256::MAX, U256::ZERO).calldata,
|
||||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
Contract::bitwise_byte(U256::from_str("18446744073709551619").unwrap(), U256::MAX)
|
||||||
let expected = I256::try_from(945i64).unwrap();
|
.calldata,
|
||||||
assert_eq!(received, expected);
|
])
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn msize_plain() {
|
|
||||||
sol!(
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
contract MSize {
|
|
||||||
function mSize() public pure returns (uint);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
let code = 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 = 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 = 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<_>>()
|
|
||||||
{
|
{
|
||||||
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]
|
run_differential(actions);
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn unsigned_division() {
|
fn unsigned_division() {
|
||||||
|
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||||
|
|
||||||
let one = U256::from(1);
|
let one = U256::from(1);
|
||||||
let two = U256::from(2);
|
let two = U256::from(2);
|
||||||
let five = U256::from(5);
|
let five = U256::from(5);
|
||||||
for (received, expected) in [
|
for (n, d) in [
|
||||||
(five, five, one),
|
(five, five),
|
||||||
(five, one, five),
|
(five, one),
|
||||||
(U256::ZERO, U256::MAX, U256::ZERO),
|
(U256::ZERO, U256::MAX),
|
||||||
(five, two, two),
|
(five, two),
|
||||||
(one, U256::ZERO, U256::ZERO),
|
(one, U256::ZERO),
|
||||||
]
|
] {
|
||||||
.par_iter()
|
actions.push(Call {
|
||||||
.map(|(n, d, q)| {
|
origin: TestAddress::Alice,
|
||||||
let (_, output) = assert_success(&Contract::division_arithmetics_div(*n, *d), true);
|
dest: TestAddress::Instantiated(0),
|
||||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
value: 0,
|
||||||
(received, *q)
|
gas_limit: None,
|
||||||
|
storage_deposit_limit: None,
|
||||||
|
data: Contract::division_arithmetics_div(n, d).calldata,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
|
||||||
{
|
|
||||||
assert_eq!(received, expected)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
run_differential(actions);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn signed_division() {
|
fn signed_division() {
|
||||||
|
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||||
|
|
||||||
let one = I256::try_from(1).unwrap();
|
let one = I256::try_from(1).unwrap();
|
||||||
let two = I256::try_from(2).unwrap();
|
let two = I256::try_from(2).unwrap();
|
||||||
let minus_two = I256::try_from(-2).unwrap();
|
let minus_two = I256::try_from(-2).unwrap();
|
||||||
let five = I256::try_from(5).unwrap();
|
let five = I256::try_from(5).unwrap();
|
||||||
let minus_five = I256::try_from(-5).unwrap();
|
let minus_five = I256::try_from(-5).unwrap();
|
||||||
for (received, expected) in [
|
for (n, d) in [
|
||||||
(five, five, one),
|
(five, five),
|
||||||
(five, one, five),
|
(five, one),
|
||||||
(I256::ZERO, I256::MAX, I256::ZERO),
|
(I256::ZERO, I256::MAX),
|
||||||
(I256::ZERO, I256::MINUS_ONE, I256::ZERO),
|
(I256::ZERO, I256::MINUS_ONE),
|
||||||
(five, two, two),
|
(five, two),
|
||||||
(five, I256::MINUS_ONE, minus_five),
|
(five, I256::MINUS_ONE),
|
||||||
(I256::MINUS_ONE, minus_two, I256::ZERO),
|
(I256::MINUS_ONE, minus_two),
|
||||||
(minus_five, minus_five, one),
|
(minus_five, minus_five),
|
||||||
(minus_five, two, minus_two),
|
(minus_five, two),
|
||||||
(I256::MINUS_ONE, I256::MIN, I256::ZERO),
|
(I256::MINUS_ONE, I256::MIN),
|
||||||
(one, I256::ZERO, I256::ZERO),
|
(one, I256::ZERO),
|
||||||
]
|
] {
|
||||||
.par_iter()
|
actions.push(Call {
|
||||||
.map(|(n, d, q)| {
|
origin: TestAddress::Alice,
|
||||||
let (_, output) = assert_success(&Contract::division_arithmetics_sdiv(*n, *d), true);
|
dest: TestAddress::Instantiated(0),
|
||||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
value: 0,
|
||||||
(received, *q)
|
gas_limit: None,
|
||||||
|
storage_deposit_limit: None,
|
||||||
|
data: Contract::division_arithmetics_sdiv(n, d).calldata,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
|
||||||
{
|
|
||||||
assert_eq!(received, expected);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
run_differential(actions);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn unsigned_remainder() {
|
fn unsigned_remainder() {
|
||||||
|
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||||
|
|
||||||
let one = U256::from(1);
|
let one = U256::from(1);
|
||||||
let two = U256::from(2);
|
let two = U256::from(2);
|
||||||
let five = U256::from(5);
|
let five = U256::from(5);
|
||||||
for (received, expected) in [
|
for (n, d) in [
|
||||||
(five, five, U256::ZERO),
|
(five, five),
|
||||||
(five, one, U256::ZERO),
|
(five, one),
|
||||||
(U256::ZERO, U256::MAX, U256::ZERO),
|
(U256::ZERO, U256::MAX),
|
||||||
(U256::MAX, U256::MAX, U256::ZERO),
|
(U256::MAX, U256::MAX),
|
||||||
(five, two, one),
|
(five, two),
|
||||||
(two, five, two),
|
(two, five),
|
||||||
(U256::MAX, U256::ZERO, U256::ZERO),
|
(U256::MAX, U256::ZERO),
|
||||||
]
|
] {
|
||||||
.par_iter()
|
actions.push(Call {
|
||||||
.map(|(n, d, q)| {
|
origin: TestAddress::Alice,
|
||||||
let (_, output) = assert_success(&Contract::division_arithmetics_mod(*n, *d), true);
|
dest: TestAddress::Instantiated(0),
|
||||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
value: 0,
|
||||||
(received, *q)
|
gas_limit: None,
|
||||||
|
storage_deposit_limit: None,
|
||||||
|
data: Contract::division_arithmetics_mod(n, d).calldata,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
|
||||||
{
|
|
||||||
assert_eq!(received, expected);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
run_differential(actions);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn signed_remainder() {
|
fn signed_remainder() {
|
||||||
|
let mut actions = instantiate("contracts/DivisionArithmetics.sol", "DivisionArithmetics");
|
||||||
|
|
||||||
let one = I256::try_from(1).unwrap();
|
let one = I256::try_from(1).unwrap();
|
||||||
let two = I256::try_from(2).unwrap();
|
let two = I256::try_from(2).unwrap();
|
||||||
let minus_two = I256::try_from(-2).unwrap();
|
let minus_two = I256::try_from(-2).unwrap();
|
||||||
let five = I256::try_from(5).unwrap();
|
let five = I256::try_from(5).unwrap();
|
||||||
let minus_five = I256::try_from(-5).unwrap();
|
let minus_five = I256::try_from(-5).unwrap();
|
||||||
for (received, expected) in [
|
for (n, d) in [
|
||||||
(five, five, I256::ZERO),
|
(five, five),
|
||||||
(five, one, I256::ZERO),
|
(five, one),
|
||||||
(I256::ZERO, I256::MAX, I256::ZERO),
|
(I256::ZERO, I256::MAX),
|
||||||
(I256::MAX, I256::MAX, I256::ZERO),
|
(I256::MAX, I256::MAX),
|
||||||
(five, two, one),
|
(five, two),
|
||||||
(two, five, two),
|
(two, five),
|
||||||
(five, minus_five, I256::ZERO),
|
(five, minus_five),
|
||||||
(five, I256::MINUS_ONE, I256::ZERO),
|
(five, I256::MINUS_ONE),
|
||||||
(five, minus_two, one),
|
(five, minus_two),
|
||||||
(minus_five, two, I256::MINUS_ONE),
|
(minus_five, two),
|
||||||
(minus_two, five, minus_two),
|
(minus_two, five),
|
||||||
(minus_five, minus_five, I256::ZERO),
|
(minus_five, minus_five),
|
||||||
(minus_five, I256::MINUS_ONE, I256::ZERO),
|
(minus_five, I256::MINUS_ONE),
|
||||||
(minus_five, minus_two, I256::MINUS_ONE),
|
(minus_five, minus_two),
|
||||||
(minus_two, minus_five, minus_two),
|
(minus_two, minus_five),
|
||||||
(I256::MIN, I256::MINUS_ONE, I256::ZERO),
|
(I256::MIN, I256::MINUS_ONE),
|
||||||
(I256::ZERO, I256::ZERO, I256::ZERO),
|
(I256::ZERO, I256::ZERO),
|
||||||
]
|
] {
|
||||||
.par_iter()
|
actions.push(Call {
|
||||||
.map(|(n, d, q)| {
|
origin: TestAddress::Alice,
|
||||||
let (_, output) = assert_success(&Contract::division_arithmetics_smod(*n, *d), true);
|
dest: TestAddress::Instantiated(0),
|
||||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
value: 0,
|
||||||
(received, *q)
|
gas_limit: None,
|
||||||
|
storage_deposit_limit: None,
|
||||||
|
data: Contract::division_arithmetics_smod(n, d).calldata,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
|
||||||
{
|
|
||||||
assert_eq!(received, expected);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
#[test]
|
#[test]
|
||||||
fn events() {
|
fn events() {
|
||||||
assert_success(&Contract::event(U256::ZERO), true);
|
assert_success(&Contract::event(U256::ZERO), true);
|
||||||
assert_success(&Contract::event(U256::from(123)), true);
|
assert_success(&Contract::event(U256::from(123)), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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]
|
#[test]
|
||||||
fn create2() {
|
fn create2() {
|
||||||
let mut state = State::default();
|
let mut state = State::default();
|
||||||
@@ -565,76 +386,4 @@ fn echo() {
|
|||||||
|
|
||||||
assert_eq!(expected, received);
|
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()));
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ polkavm-disassembler = { workspace = true }
|
|||||||
polkavm-common = { workspace = true }
|
polkavm-common = { workspace = true }
|
||||||
|
|
||||||
revive-common = { workspace = true }
|
revive-common = { workspace = true }
|
||||||
pallet-contracts-pvm-llapi = { workspace = true }
|
revive-runtime-api = { workspace = true }
|
||||||
revive-linker = { workspace = true }
|
revive-linker = { workspace = true }
|
||||||
revive-builtins = { workspace = true }
|
revive-builtins = { workspace = true }
|
||||||
revive-stdlib = { workspace = true }
|
revive-stdlib = { workspace = true }
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ pub mod imports {
|
|||||||
|
|
||||||
pub static BLOCK_NUMBER: &str = "block_number";
|
pub static BLOCK_NUMBER: &str = "block_number";
|
||||||
|
|
||||||
pub static CALL: &str = "seal_call";
|
pub static CALL: &str = "call";
|
||||||
|
|
||||||
pub static CALLER: &str = "caller";
|
pub static CALLER: &str = "caller";
|
||||||
|
|
||||||
|
|||||||
@@ -233,11 +233,12 @@ where
|
|||||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||||
let entry_arguments = vec![context.bool_type().as_basic_type_enum()];
|
let entry_arguments = vec![context.bool_type().as_basic_type_enum()];
|
||||||
let entry_function_type = context.function_type(entry_arguments, 0, false);
|
let entry_function_type = context.function_type(entry_arguments, 0, false);
|
||||||
context.add_function(runtime::FUNCTION_ENTRY, entry_function_type, 0, None)?;
|
context.add_function(
|
||||||
|
runtime::FUNCTION_ENTRY,
|
||||||
for symbol in runtime_api::exports::EXPORTS {
|
entry_function_type,
|
||||||
context.declare_extern_function(symbol)?;
|
0,
|
||||||
}
|
Some(inkwell::module::Linkage::External),
|
||||||
|
)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -258,26 +259,6 @@ where
|
|||||||
true,
|
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_current_function(runtime::FUNCTION_ENTRY)?;
|
||||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||||
|
|
||||||
|
|||||||
@@ -124,27 +124,17 @@ where
|
|||||||
.expect("the stdlib module should be linkable");
|
.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).
|
/// 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,
|
llvm: &'ctx inkwell::context::Context,
|
||||||
module: &inkwell::module::Module<'ctx>,
|
module: &inkwell::module::Module<'ctx>,
|
||||||
) {
|
) {
|
||||||
module
|
module
|
||||||
.link_in_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 runtime_api::imports::IMPORTS {
|
||||||
module
|
module
|
||||||
@@ -154,6 +144,24 @@ 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
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Configure the PolkaVM minimum stack size.
|
/// Configure the PolkaVM minimum stack size.
|
||||||
fn set_polkavm_stack_size(
|
fn set_polkavm_stack_size(
|
||||||
llvm: &'ctx inkwell::context::Context,
|
llvm: &'ctx inkwell::context::Context,
|
||||||
@@ -161,7 +169,7 @@ where
|
|||||||
size: u32,
|
size: u32,
|
||||||
) {
|
) {
|
||||||
module
|
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,
|
llvm,
|
||||||
"polkavm_stack_size",
|
"polkavm_stack_size",
|
||||||
size,
|
size,
|
||||||
@@ -191,7 +199,7 @@ where
|
|||||||
debug_config: Option<DebugConfig>,
|
debug_config: Option<DebugConfig>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self::link_stdlib_module(llvm, &module);
|
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_polkavm_stack_size(llvm, &module, Self::POLKAVM_STACK_SIZE);
|
||||||
Self::set_module_flags(llvm, &module);
|
Self::set_module_flags(llvm, &module);
|
||||||
|
|
||||||
@@ -230,6 +238,8 @@ where
|
|||||||
) -> anyhow::Result<Build> {
|
) -> anyhow::Result<Build> {
|
||||||
let module_clone = self.module.clone();
|
let module_clone = self.module.clone();
|
||||||
|
|
||||||
|
self.link_polkavm_exports(contract_path)?;
|
||||||
|
|
||||||
let target_machine = TargetMachine::new(Target::PVM, self.optimizer.settings())?;
|
let target_machine = TargetMachine::new(Target::PVM, self.optimizer.settings())?;
|
||||||
target_machine.set_target_data(self.module());
|
target_machine.set_target_data(self.module());
|
||||||
|
|
||||||
@@ -688,8 +698,14 @@ where
|
|||||||
self.builder()
|
self.builder()
|
||||||
.build_store(storage_key_pointer.value, storage_key_value)?;
|
.build_store(storage_key_pointer.value, storage_key_value)?;
|
||||||
|
|
||||||
let (storage_value_pointer, storage_value_length_pointer) = self
|
let storage_value_pointer =
|
||||||
.build_stack_parameter(revive_common::BIT_LENGTH_WORD, "storage_value_pointer");
|
self.build_alloca(self.word_type(), "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;
|
let transient = pointer.address_space == AddressSpace::TransientStorage;
|
||||||
|
|
||||||
@@ -698,7 +714,7 @@ where
|
|||||||
&[
|
&[
|
||||||
self.xlen_type().const_int(transient as u64, false).into(),
|
self.xlen_type().const_int(transient as u64, false).into(),
|
||||||
storage_key_pointer_casted.into(),
|
storage_key_pointer_casted.into(),
|
||||||
self.integer_const(crate::polkavm::XLEN, 32).into(),
|
self.xlen_type().const_all_ones().into(),
|
||||||
storage_value_pointer.to_int(self).into(),
|
storage_value_pointer.to_int(self).into(),
|
||||||
storage_value_length_pointer.to_int(self).into(),
|
storage_value_length_pointer.to_int(self).into(),
|
||||||
],
|
],
|
||||||
@@ -797,7 +813,7 @@ where
|
|||||||
&[
|
&[
|
||||||
self.xlen_type().const_int(transient as u64, false).into(),
|
self.xlen_type().const_int(transient as u64, false).into(),
|
||||||
storage_key_pointer_casted.into(),
|
storage_key_pointer_casted.into(),
|
||||||
self.integer_const(crate::polkavm::XLEN, 32).into(),
|
self.xlen_type().const_all_ones().into(),
|
||||||
storage_value_pointer_casted.into(),
|
storage_value_pointer_casted.into(),
|
||||||
self.integer_const(crate::polkavm::XLEN, 32).into(),
|
self.integer_const(crate::polkavm::XLEN, 32).into(),
|
||||||
],
|
],
|
||||||
@@ -1233,7 +1249,7 @@ where
|
|||||||
self.llvm.custom_width_int_type(crate::polkavm::XLEN as u32)
|
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> {
|
pub fn sentinel_pointer(&self) -> Pointer<'ctx> {
|
||||||
let sentinel_pointer = self
|
let sentinel_pointer = self
|
||||||
.xlen_type()
|
.xlen_type()
|
||||||
|
|||||||
@@ -57,9 +57,9 @@ where
|
|||||||
let output_length_pointer = context.get_global(crate::polkavm::GLOBAL_RETURN_DATA_SIZE)?;
|
let output_length_pointer = context.get_global(crate::polkavm::GLOBAL_RETURN_DATA_SIZE)?;
|
||||||
context.build_store(output_length_pointer.into(), output_length)?;
|
context.build_store(output_length_pointer.into(), output_length)?;
|
||||||
|
|
||||||
let argument_pointer = pallet_contracts_pvm_llapi::calling_convention::Spill::new(
|
let argument_pointer = revive_runtime_api::calling_convention::Spill::new(
|
||||||
context.builder(),
|
context.builder(),
|
||||||
pallet_contracts_pvm_llapi::calling_convention::call(context.llvm()),
|
revive_runtime_api::calling_convention::call(context.llvm()),
|
||||||
"call_arguments",
|
"call_arguments",
|
||||||
)?
|
)?
|
||||||
.next(context.xlen_type().const_int(flags as u64, false))?
|
.next(context.xlen_type().const_int(flags as u64, false))?
|
||||||
|
|||||||
@@ -38,12 +38,12 @@ where
|
|||||||
|
|
||||||
/// Translates the `chain_id` instruction.
|
/// Translates the `chain_id` instruction.
|
||||||
pub fn chain_id<'ctx, D>(
|
pub fn chain_id<'ctx, D>(
|
||||||
_context: &mut Context<'ctx, D>,
|
context: &mut Context<'ctx, D>,
|
||||||
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
|
||||||
where
|
where
|
||||||
D: Dependency + Clone,
|
D: Dependency + Clone,
|
||||||
{
|
{
|
||||||
todo!()
|
Ok(context.word_const(0).as_basic_value_enum())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Translates the `block_number` instruction.
|
/// Translates the `block_number` instruction.
|
||||||
|
|||||||
@@ -58,9 +58,9 @@ where
|
|||||||
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "address_pointer");
|
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "address_pointer");
|
||||||
context.build_store(address_pointer, context.word_const(0))?;
|
context.build_store(address_pointer, context.word_const(0))?;
|
||||||
|
|
||||||
let argument_pointer = pallet_contracts_pvm_llapi::calling_convention::Spill::new(
|
let argument_pointer = revive_runtime_api::calling_convention::Spill::new(
|
||||||
context.builder(),
|
context.builder(),
|
||||||
pallet_contracts_pvm_llapi::calling_convention::instantiate(context.llvm()),
|
revive_runtime_api::calling_convention::instantiate(context.llvm()),
|
||||||
"create2_arguments",
|
"create2_arguments",
|
||||||
)?
|
)?
|
||||||
.next(code_hash_pointer.value)?
|
.next(code_hash_pointer.value)?
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
pub mod calling_convention;
|
|
||||||
pub mod polkavm_guest;
|
|
||||||
@@ -4,14 +4,29 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
repository.authors = true
|
authors.workspace = true
|
||||||
descritption = "Execute revive contracts in a simulated blockchain runtime"
|
description = "Execute revive contracts in a simulated blockchain runtime"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["solidity"]
|
||||||
|
solidity = ["revive-solidity", "revive-differential"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
|
hex = { workspace = true, features = ["serde"] }
|
||||||
codec = { workspace = true, default-features = false }
|
codec = { workspace = true, default-features = false }
|
||||||
scale-info = { 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 }
|
||||||
|
|||||||
+149
-217
@@ -7,49 +7,74 @@
|
|||||||
//! ```rust
|
//! ```rust
|
||||||
//! use revive_runner::*;
|
//! use revive_runner::*;
|
||||||
//! use SpecsAction::*;
|
//! use SpecsAction::*;
|
||||||
//! run_test(Specs {
|
//! Specs {
|
||||||
|
//! differential: false,
|
||||||
//! balances: vec![(ALICE, 1_000_000_000)],
|
//! balances: vec![(ALICE, 1_000_000_000)],
|
||||||
//! actions: vec![Instantiate {
|
//! actions: vec![Instantiate {
|
||||||
//! origin: ALICE,
|
//! origin: TestAddress::Alice,
|
||||||
//! value: 0,
|
//! value: 0,
|
||||||
//! gas_limit: Some(GAS_LIMIT),
|
//! gas_limit: Some(GAS_LIMIT),
|
||||||
//! storage_deposit_limit: Some(DEPOSIT_LIMIT),
|
//! storage_deposit_limit: Some(DEPOSIT_LIMIT),
|
||||||
//! code: Code::Bytes(include_bytes!("../fixtures/Baseline.pvm").to_vec()),
|
//! code: Code::Bytes(include_bytes!("../fixtures/Baseline.pvm").to_vec()),
|
||||||
//! data: vec![],
|
//! data: vec![],
|
||||||
//! salt: vec![],
|
//! salt: Default::default(),
|
||||||
//! }],
|
//! }],
|
||||||
//! })
|
//! }
|
||||||
|
//! .run();
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use hex::{FromHex, ToHex};
|
||||||
|
use pallet_revive::AddressMapper;
|
||||||
use polkadot_sdk::*;
|
use polkadot_sdk::*;
|
||||||
use polkadot_sdk::{
|
use polkadot_sdk::{
|
||||||
pallet_revive::{CollectEvents, ContractExecResult, ContractInstantiateResult, DebugInfo},
|
pallet_revive::{CollectEvents, ContractExecResult, ContractInstantiateResult, DebugInfo},
|
||||||
polkadot_runtime_common::BuildStorage,
|
polkadot_runtime_common::BuildStorage,
|
||||||
polkadot_sdk_frame::testing_prelude::*,
|
polkadot_sdk_frame::testing_prelude::*,
|
||||||
|
sp_core::H160,
|
||||||
sp_keystore::{testing::MemoryKeystore, KeystoreExt},
|
sp_keystore::{testing::MemoryKeystore, KeystoreExt},
|
||||||
sp_runtime::AccountId32,
|
sp_runtime::AccountId32,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
mod runtime;
|
|
||||||
use crate::runtime::*;
|
use crate::runtime::*;
|
||||||
|
pub use crate::specs::*;
|
||||||
|
|
||||||
pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]);
|
mod runtime;
|
||||||
pub const BOB: AccountId32 = AccountId32::new([2u8; 32]);
|
mod specs;
|
||||||
pub const CHARLIE: AccountId32 = AccountId32::new([3u8; 32]);
|
|
||||||
|
#[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
|
/// Externalities builder
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct ExtBuilder {
|
pub struct ExtBuilder {
|
||||||
/// List of endowments at genesis
|
/// List of endowments at genesis
|
||||||
balance_genesis_config: Vec<(AccountId, Balance)>,
|
balance_genesis_config: Vec<(AccountId32, Balance)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ExtBuilder {
|
impl ExtBuilder {
|
||||||
/// Set the balance of an account at genesis
|
/// Set the balance of an account at genesis
|
||||||
fn balance_genesis_config(mut self, value: Vec<(AccountId, Balance)>) -> Self {
|
fn balance_genesis_config(self, value: Vec<(H160, Balance)>) -> Self {
|
||||||
self.balance_genesis_config = value;
|
Self {
|
||||||
self
|
balance_genesis_config: value
|
||||||
|
.iter()
|
||||||
|
.map(|(address, balance)| (AccountId::to_account_id(address), *balance))
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build the externalities
|
/// 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
|
/// Expectation for a call
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct VerifyCallExpectation {
|
pub struct VerifyCallExpectation {
|
||||||
/// When provided, the expected gas consumed
|
/// When provided, the expected gas consumed
|
||||||
gas_consumed: Option<Weight>,
|
pub gas_consumed: Option<Weight>,
|
||||||
/// When provided, the expected output
|
/// When provided, the expected output
|
||||||
output: Option<Vec<u8>>,
|
#[serde(default, with = "hex")]
|
||||||
|
pub output: OptionalHex<Vec<u8>>,
|
||||||
///Expected call result
|
///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 {
|
impl Default for VerifyCallExpectation {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
gas_consumed: None,
|
gas_consumed: None,
|
||||||
output: None,
|
output: OptionalHex(None),
|
||||||
success: true,
|
success: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,42 +158,53 @@ impl Default for VerifyCallExpectation {
|
|||||||
|
|
||||||
impl VerifyCallExpectation {
|
impl VerifyCallExpectation {
|
||||||
/// Verify that the expectations are met
|
/// Verify that the expectations are met
|
||||||
fn verify(self, result: CallResult) {
|
fn verify(self, result: &CallResult) {
|
||||||
dbg!(&result);
|
assert_eq!(
|
||||||
assert_eq!(self.success, result.is_ok());
|
self.success,
|
||||||
|
result.is_ok(),
|
||||||
|
"contract execution result mismatch: {result:?}"
|
||||||
|
);
|
||||||
|
|
||||||
if let Some(gas_consumed) = self.gas_consumed {
|
if let Some(gas_consumed) = self.gas_consumed {
|
||||||
assert_eq!(gas_consumed, result.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
|
/// Result of a call
|
||||||
#[derive(Debug)]
|
#[derive(Clone, Debug)]
|
||||||
enum CallResult {
|
pub enum CallResult {
|
||||||
Exec(ContractExecResult<Balance, EventRecord>),
|
Exec {
|
||||||
Instantiate(ContractInstantiateResult<AccountId, Balance, EventRecord>),
|
result: ContractExecResult<Balance, EventRecord>,
|
||||||
|
wall_time: Duration,
|
||||||
|
},
|
||||||
|
Instantiate {
|
||||||
|
result: ContractInstantiateResult<Balance, EventRecord>,
|
||||||
|
wall_time: Duration,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CallResult {
|
impl CallResult {
|
||||||
/// Check if the call was successful
|
/// Check if the call was successful
|
||||||
fn is_ok(&self) -> bool {
|
fn is_ok(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Exec(res) => res.result.is_ok(),
|
Self::Exec { result, .. } => result.result.is_ok(),
|
||||||
Self::Instantiate(res) => res.result.is_ok(),
|
Self::Instantiate { result, .. } => result.result.is_ok(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Get the output of the call
|
/// Get the output of the call
|
||||||
fn output(&self) -> Vec<u8> {
|
fn output(&self) -> Vec<u8> {
|
||||||
match self {
|
match self {
|
||||||
Self::Exec(res) => res
|
Self::Exec { result, .. } => result
|
||||||
.result
|
.result
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|r| r.data.clone())
|
.map(|r| r.data.clone())
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
Self::Instantiate(res) => res
|
Self::Instantiate { result, .. } => result
|
||||||
.result
|
.result
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|r| r.result.data.clone())
|
.map(|r| r.result.data.clone())
|
||||||
@@ -145,17 +214,20 @@ impl CallResult {
|
|||||||
/// Get the gas consumed by the call
|
/// Get the gas consumed by the call
|
||||||
fn gas_consumed(&self) -> Weight {
|
fn gas_consumed(&self) -> Weight {
|
||||||
match self {
|
match self {
|
||||||
Self::Exec(res) => res.gas_consumed,
|
Self::Exec { result, .. } => result.gas_consumed,
|
||||||
Self::Instantiate(res) => res.gas_consumed,
|
Self::Instantiate { result, .. } => result.gas_consumed,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub enum Code {
|
pub enum Code {
|
||||||
|
#[cfg(feature = "revive-solidity")]
|
||||||
/// Compile a single solidity source and use the blob of `contract`
|
/// Compile a single solidity source and use the blob of `contract`
|
||||||
Solidity {
|
Solidity {
|
||||||
path: std::path::PathBuf,
|
path: Option<std::path::PathBuf>,
|
||||||
|
solc_optimizer: Option<bool>,
|
||||||
|
pipeline: Option<revive_solidity::SolcPipeline>,
|
||||||
contract: String,
|
contract: String,
|
||||||
},
|
},
|
||||||
/// Read the contract blob from disk
|
/// Read the contract blob from disk
|
||||||
@@ -166,13 +238,33 @@ pub enum Code {
|
|||||||
Hash(Hash),
|
Hash(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 {
|
fn from(val: Code) -> Self {
|
||||||
match val {
|
match val {
|
||||||
Code::Solidity { path, contract } => {
|
#[cfg(feature = "solidity")]
|
||||||
pallet_revive::Code::Upload(revive_solidity::test_utils::compile_blob(
|
Code::Solidity {
|
||||||
contract.as_str(),
|
path,
|
||||||
std::fs::read_to_string(path).unwrap().as_str(),
|
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()),
|
Code::Path(path) => pallet_revive::Code::Upload(std::fs::read(path).unwrap()),
|
||||||
@@ -182,201 +274,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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use crate::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn instantiate_works() {
|
fn instantiate_works() {
|
||||||
use SpecsAction::*;
|
use specs::SpecsAction::*;
|
||||||
run_test(Specs {
|
let specs = Specs {
|
||||||
|
differential: false,
|
||||||
balances: vec![(ALICE, 1_000_000_000)],
|
balances: vec![(ALICE, 1_000_000_000)],
|
||||||
actions: vec![Instantiate {
|
actions: vec![Instantiate {
|
||||||
origin: ALICE,
|
origin: TestAddress::Alice,
|
||||||
value: 0,
|
value: 0,
|
||||||
gas_limit: Some(GAS_LIMIT),
|
gas_limit: Some(GAS_LIMIT),
|
||||||
storage_deposit_limit: Some(DEPOSIT_LIMIT),
|
storage_deposit_limit: Some(DEPOSIT_LIMIT),
|
||||||
code: Code::Bytes(include_bytes!("../fixtures/Baseline.pvm").to_vec()),
|
code: Code::Bytes(include_bytes!("../fixtures/Baseline.pvm").to_vec()),
|
||||||
data: vec![],
|
data: vec![],
|
||||||
salt: vec![],
|
salt: OptionalHex::default(),
|
||||||
}],
|
}],
|
||||||
})
|
};
|
||||||
|
specs.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn instantiate_with_json() {
|
fn instantiate_with_json() {
|
||||||
let specs = serde_json::from_str::<Specs>(
|
serde_json::from_str::<Specs>(
|
||||||
r#"
|
r#"
|
||||||
{
|
{
|
||||||
"balances": [
|
"balances": [
|
||||||
[ "5C62Ck4UrFPiBtoCmeSrgF7x9yv9mn38446dhCpsi2mLHiFT", 1000000000 ]
|
[ "0101010101010101010101010101010101010101", 1000000000 ]
|
||||||
],
|
],
|
||||||
"actions": [
|
"actions": [
|
||||||
{
|
{
|
||||||
"Instantiate": {
|
"Instantiate": {
|
||||||
"origin": "5C62Ck4UrFPiBtoCmeSrgF7x9yv9mn38446dhCpsi2mLHiFT",
|
"origin": "Alice",
|
||||||
"value": 0,
|
"value": 0,
|
||||||
"code": {
|
"code": {
|
||||||
"Path": "fixtures/Baseline.pvm"
|
"Path": "fixtures/Baseline.pvm"
|
||||||
@@ -387,7 +319,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap()
|
||||||
run_test(specs);
|
.run();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use polkadot_sdk::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
pub type Balance = u128;
|
pub type Balance = u128;
|
||||||
pub type AccountId = AccountId32;
|
pub type AccountId = pallet_revive::DefaultAddressMapper;
|
||||||
pub type Block = frame_system::mocking::MockBlock<Runtime>;
|
pub type Block = frame_system::mocking::MockBlock<Runtime>;
|
||||||
pub type Hash = <Runtime as frame_system::Config>::Hash;
|
pub type Hash = <Runtime as frame_system::Config>::Hash;
|
||||||
pub type EventRecord =
|
pub type EventRecord =
|
||||||
@@ -45,7 +45,7 @@ mod runtime {
|
|||||||
#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
|
#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
|
||||||
impl frame_system::Config for Runtime {
|
impl frame_system::Config for Runtime {
|
||||||
type Block = Block;
|
type Block = Block;
|
||||||
type AccountId = AccountId;
|
type AccountId = AccountId32;
|
||||||
type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
|
type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,10 +74,10 @@ impl pallet_revive::Config for Runtime {
|
|||||||
type ChainExtension = ();
|
type ChainExtension = ();
|
||||||
type DepositPerByte = DepositPerByte;
|
type DepositPerByte = DepositPerByte;
|
||||||
type DepositPerItem = DepositPerItem;
|
type DepositPerItem = DepositPerItem;
|
||||||
type AddressGenerator = pallet_revive::DefaultAddressGenerator;
|
type AddressMapper = AccountId;
|
||||||
type UnsafeUnstableInterface = UnstableInterface;
|
type UnsafeUnstableInterface = UnstableInterface;
|
||||||
type UploadOrigin = EnsureSigned<AccountId>;
|
type UploadOrigin = EnsureSigned<AccountId32>;
|
||||||
type InstantiateOrigin = EnsureSigned<AccountId>;
|
type InstantiateOrigin = EnsureSigned<AccountId32>;
|
||||||
type Migrations = ();
|
type Migrations = ();
|
||||||
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
|
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
|
||||||
type Debug = ();
|
type Debug = ();
|
||||||
|
|||||||
@@ -0,0 +1,498 @@
|
|||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use pallet_revive::AddressMapper;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::*;
|
||||||
|
use alloy_primitives::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)],
|
||||||
|
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,
|
||||||
|
storage_deposit_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!(solc_optimizer, Some(false), "solc_optimizer must be enabled in differntial mode");
|
||||||
|
assert_ne!(pipeline, Some(revive_solidity::SolcPipeline::EVMLA), "yul pipeline must be enabled in differntial mode");
|
||||||
|
assert!(storage_deposit_limit.is_none(), "storage deposit limit is not supported 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) => compile_evm_deploy_code(&contract, &solidity_source),
|
||||||
|
Err(err) => panic!(
|
||||||
|
"failed to read solidity source\n . path: '{}'\n . error: {:?}",
|
||||||
|
path.display(),
|
||||||
|
err
|
||||||
|
),
|
||||||
|
};
|
||||||
|
let deploy_code = hex::encode(deploy_code);
|
||||||
|
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,
|
||||||
|
storage_deposit_limit,
|
||||||
|
data,
|
||||||
|
} => {
|
||||||
|
assert_eq!(origin, TestAddress::default(), "configuring the origin is not supported in differential mode");
|
||||||
|
assert!(storage_deposit_limit.is_none(), "storage deposit limit 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());
|
||||||
|
}
|
||||||
|
_ => panic!("only instantiate and call action allowed in differential mode, got: {action:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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.into(),
|
||||||
|
data,
|
||||||
|
salt.0,
|
||||||
|
DebugInfo::Skip,
|
||||||
|
CollectEvents::Skip,
|
||||||
|
);
|
||||||
|
results.push(CallResult::Instantiate {
|
||||||
|
result,
|
||||||
|
wall_time: time_start.elapsed(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
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_default(),
|
||||||
|
)
|
||||||
|
.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);
|
||||||
|
dbg!(contract.to_account_id(&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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "pallet-contracts-pvm-llapi"
|
name = "revive-runtime-api"
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
repository.authors = true
|
authors.workspace = true
|
||||||
descritption = "Implements the low level runtime API bindings with pallet contracts"
|
description = "Implements the low level runtime API bindings with pallet contracts"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
riscv-64 = []
|
riscv-64 = []
|
||||||
@@ -20,7 +20,15 @@ const TARGET_ABI_FLAG: &str = "-mabi=ilp32e";
|
|||||||
#[cfg(feature = "riscv-64")]
|
#[cfg(feature = "riscv-64")]
|
||||||
const TARGET_ABI_FLAG: &str = "-mabi=lp64e";
|
const TARGET_ABI_FLAG: &str = "-mabi=lp64e";
|
||||||
|
|
||||||
fn compile(bitcode_path: &str) {
|
const IMPORTS_SOUCE: &str = "src/polkavm_imports.c";
|
||||||
|
const IMPORTS_BC: &str = "polkavm_imports.bc";
|
||||||
|
const IMPORTS_RUST: &str = "polkavm_imports.rs";
|
||||||
|
|
||||||
|
const EXPORTS_SOUCE: &str = "src/polkavm_exports.c";
|
||||||
|
const EXPORTS_BC: &str = "polkavm_exports.bc";
|
||||||
|
const EXPORTS_RUST: &str = "polkavm_exports.rs";
|
||||||
|
|
||||||
|
fn compile(source_path: &str, bitcode_path: &str) {
|
||||||
let output = Command::new("clang")
|
let output = Command::new("clang")
|
||||||
.args([
|
.args([
|
||||||
TARGET_FLAG,
|
TARGET_FLAG,
|
||||||
@@ -35,9 +43,9 @@ fn compile(bitcode_path: &str) {
|
|||||||
"-O3",
|
"-O3",
|
||||||
"-emit-llvm",
|
"-emit-llvm",
|
||||||
"-c",
|
"-c",
|
||||||
"src/polkavm_guest.c",
|
|
||||||
"-o",
|
"-o",
|
||||||
bitcode_path,
|
bitcode_path,
|
||||||
|
source_path,
|
||||||
])
|
])
|
||||||
.output()
|
.output()
|
||||||
.expect("should be able to invoke C clang");
|
.expect("should be able to invoke C clang");
|
||||||
@@ -49,19 +57,24 @@ fn compile(bitcode_path: &str) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn build_module(source_path: &str, bitcode_path: &str, rust_file: &str) {
|
||||||
let out_dir = env::var_os("OUT_DIR").expect("env should have $OUT_DIR");
|
let out_dir = env::var_os("OUT_DIR").expect("env should have $OUT_DIR");
|
||||||
let lib = "polkavm_guest.bc";
|
let lib = Path::new(&out_dir).join(bitcode_path);
|
||||||
let bitcode_path = Path::new(&out_dir).join(lib);
|
compile(source_path, lib.to_str().expect("$OUT_DIR should be UTF-8"));
|
||||||
compile(bitcode_path.to_str().expect("$OUT_DIR should be UTF-8"));
|
|
||||||
|
|
||||||
let bitcode = fs::read(bitcode_path).expect("bitcode should have been built");
|
let bitcode = fs::read(lib).expect("bitcode should have been built");
|
||||||
let len = bitcode.len();
|
let len = bitcode.len();
|
||||||
let src_path = Path::new(&out_dir).join("polkavm_guest.rs");
|
let src_path = Path::new(&out_dir).join(rust_file);
|
||||||
let src = format!("pub static BITCODE: &[u8; {len}] = include_bytes!(\"{lib}\");");
|
let src = format!("pub static BITCODE: &[u8; {len}] = include_bytes!(\"{bitcode_path}\");");
|
||||||
fs::write(src_path, src).expect("should be able to write in $OUT_DIR");
|
fs::write(src_path, src).expect("should be able to write in $OUT_DIR");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
build_module(IMPORTS_SOUCE, IMPORTS_BC, IMPORTS_RUST);
|
||||||
|
build_module(EXPORTS_SOUCE, EXPORTS_BC, EXPORTS_RUST);
|
||||||
|
|
||||||
println!("cargo:rerun-if-changed=build.rs");
|
println!("cargo:rerun-if-changed=build.rs");
|
||||||
println!("cargo:rerun-if-changed=src/polkavm_guest.c");
|
println!("cargo:rerun-if-changed=src/polkavm_imports.c");
|
||||||
|
println!("cargo:rerun-if-changed=src/polkavm_exports.c");
|
||||||
println!("cargo:rerun-if-changed=src/polkavm_guest.h");
|
println!("cargo:rerun-if-changed=src/polkavm_guest.h");
|
||||||
}
|
}
|
||||||
Binary file not shown.
Binary file not shown.
+16
@@ -1,10 +1,26 @@
|
|||||||
use inkwell::{
|
use inkwell::{
|
||||||
builder::Builder,
|
builder::Builder,
|
||||||
context::Context,
|
context::Context,
|
||||||
|
module::Module,
|
||||||
types::{BasicType, StructType},
|
types::{BasicType, StructType},
|
||||||
values::{BasicValue, PointerValue},
|
values::{BasicValue, PointerValue},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
}
|
||||||
|
|
||||||
pub struct Spill<'a, 'ctx> {
|
pub struct Spill<'a, 'ctx> {
|
||||||
pointer: PointerValue<'ctx>,
|
pointer: PointerValue<'ctx>,
|
||||||
builder: &'a Builder<'ctx>,
|
builder: &'a Builder<'ctx>,
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
//! This crate vendors the [PolkaVM][0] C API and provides a LLVM module for interacting
|
||||||
|
//! with the `pallet-revive` 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]
|
||||||
|
|
||||||
|
pub mod calling_convention;
|
||||||
|
pub mod polkavm_exports;
|
||||||
|
pub mod polkavm_imports;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
#include "polkavm_guest.h"
|
||||||
|
|
||||||
|
extern void __entry(bool);
|
||||||
|
|
||||||
|
static void deploy() {
|
||||||
|
__entry(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void call() {
|
||||||
|
__entry(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
POLKAVM_EXPORT(void, deploy)
|
||||||
|
POLKAVM_EXPORT(void, call)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
use inkwell::{context::Context, memory_buffer::MemoryBuffer, module::Module, support::LLVMString};
|
||||||
|
|
||||||
|
include!(concat!(env!("OUT_DIR"), "/polkavm_exports.rs"));
|
||||||
|
|
||||||
|
/// Creates a LLVM module from the [BITCODE].
|
||||||
|
/// The module exports `call` and `deploy` functions (which are named thereafter).
|
||||||
|
/// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::polkavm_exports;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_works() {
|
||||||
|
inkwell::targets::Target::initialize_riscv(&Default::default());
|
||||||
|
let context = inkwell::context::Context::create();
|
||||||
|
let module = polkavm_exports::module(&context, "polkavm_exports").unwrap();
|
||||||
|
|
||||||
|
assert!(module.get_function("call").is_some());
|
||||||
|
assert!(module.get_function("deploy").is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-9
@@ -48,14 +48,6 @@ void * __sbrk(uint32_t size) {
|
|||||||
return (void *)address;
|
return (void *)address;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exports
|
|
||||||
|
|
||||||
extern void call();
|
|
||||||
POLKAVM_EXPORT(void, call)
|
|
||||||
|
|
||||||
extern void deploy();
|
|
||||||
POLKAVM_EXPORT(void, deploy)
|
|
||||||
|
|
||||||
|
|
||||||
// Imports
|
// Imports
|
||||||
|
|
||||||
@@ -77,7 +69,7 @@ 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, take_storage, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||||
|
|
||||||
POLKAVM_IMPORT(uint32_t, seal_call, uint32_t)
|
POLKAVM_IMPORT(uint32_t, 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, delegate_call, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
|
||||||
|
|
||||||
+6
-26
@@ -1,6 +1,6 @@
|
|||||||
//! This crate vendors the [PolkaVM][0] C API and provides a LLVM module for interacting
|
//! This crate vendors the [PolkaVM][0] C API and provides a LLVM module for interacting
|
||||||
//! with the `pallet-contracts` runtime API.
|
//! with the `pallet-revive` runtime API.
|
||||||
//! At present, the contracts pallet requires blobs to export `call` and `deploy`,
|
//! At present, the revive pallet requires blobs to export `call` and `deploy`,
|
||||||
//! and offers a bunch of [runtime API methods][1]. The provided [module] implements
|
//! and offers a bunch of [runtime API methods][1]. The provided [module] implements
|
||||||
//! those exports and imports.
|
//! those exports and imports.
|
||||||
//! [0]: [https://crates.io/crates/polkavm]
|
//! [0]: [https://crates.io/crates/polkavm]
|
||||||
@@ -8,12 +8,10 @@
|
|||||||
|
|
||||||
use inkwell::{context::Context, memory_buffer::MemoryBuffer, module::Module, support::LLVMString};
|
use inkwell::{context::Context, memory_buffer::MemoryBuffer, module::Module, support::LLVMString};
|
||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/polkavm_guest.rs"));
|
include!(concat!(env!("OUT_DIR"), "/polkavm_imports.rs"));
|
||||||
|
|
||||||
/// Creates a LLVM module from the [BITCODE].
|
/// Creates a LLVM module from the [BITCODE].
|
||||||
/// The module does:
|
/// The module imports `pallet-revive` runtime API functions.
|
||||||
/// - 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.
|
/// Returns `Error` if the bitcode fails to parse, which should never happen.
|
||||||
pub fn module<'context>(
|
pub fn module<'context>(
|
||||||
context: &'context Context,
|
context: &'context Context,
|
||||||
@@ -23,32 +21,14 @@ pub fn module<'context>(
|
|||||||
Module::parse_bitcode_from_buffer(&buf, context)
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::polkavm_guest;
|
use crate::polkavm_imports;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_works() {
|
fn it_works() {
|
||||||
inkwell::targets::Target::initialize_riscv(&Default::default());
|
inkwell::targets::Target::initialize_riscv(&Default::default());
|
||||||
let context = inkwell::context::Context::create();
|
let context = inkwell::context::Context::create();
|
||||||
let module = polkavm_guest::module(&context, "polkavm_guest").unwrap();
|
let _ = polkavm_imports::module(&context, "polkavm_imports").unwrap();
|
||||||
|
|
||||||
assert!(module.get_function("call").is_some());
|
|
||||||
assert!(module.get_function("deploy").is_some());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,7 @@ pub fn call(input: Input) -> anyhow::Result<Output> {
|
|||||||
|
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
if let Some(dbg_config) = &input.debug_config {
|
if let Some(dbg_config) = &input.debug_config {
|
||||||
let _ = dbg_config
|
dbg_config
|
||||||
.dump_stage_output(&input.contract.path, Some("stage"), &input_json)
|
.dump_stage_output(&input.contract.path, Some("stage"), &input_json)
|
||||||
.map_err(|error| {
|
.map_err(|error| {
|
||||||
anyhow::anyhow!(
|
anyhow::anyhow!(
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ pub struct Arguments {
|
|||||||
#[structopt(long = "version")]
|
#[structopt(long = "version")]
|
||||||
pub version: bool,
|
pub version: bool,
|
||||||
|
|
||||||
|
/// Print the licence and exit.
|
||||||
|
#[structopt(long = "license")]
|
||||||
|
pub license: bool,
|
||||||
|
|
||||||
/// Specify the input paths and remappings.
|
/// Specify the input paths and remappings.
|
||||||
/// If an argument contains a '=', it is considered a remapping.
|
/// If an argument contains a '=', it is considered a remapping.
|
||||||
/// Multiple Solidity files can be passed in the default Solidity mode.
|
/// Multiple Solidity files can be passed in the default Solidity mode.
|
||||||
@@ -192,14 +196,14 @@ impl Arguments {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
if self.recursive_process_input != None && !self.recursive_process {
|
if self.recursive_process_input.is_none() && !self.recursive_process {
|
||||||
anyhow::bail!("--process-input can be only used when --recursive-process is given");
|
anyhow::bail!("--process-input can be only used when --recursive-process is given");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
if self.recursive_process
|
if self.recursive_process
|
||||||
&& ((self.recursive_process_input == None && std::env::args().count() > 2)
|
&& ((self.recursive_process_input.is_none() && std::env::args().count() > 2)
|
||||||
|| (self.recursive_process_input != None && std::env::args().count() > 4))
|
|| (self.recursive_process_input.is_none() && std::env::args().count() > 4))
|
||||||
{
|
{
|
||||||
anyhow::bail!("No other options are allowed in recursive mode.");
|
anyhow::bail!("No other options are allowed in recursive mode.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,14 @@ fn main_inner() -> anyhow::Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if arguments.license {
|
||||||
|
let license_mit = include_str!("../../../../LICENSE-MIT");
|
||||||
|
let license_apache = include_str!("../../../../LICENSE-APACHE");
|
||||||
|
|
||||||
|
println!("{}\n{}\n", license_mit, license_apache);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
rayon::ThreadPoolBuilder::new()
|
rayon::ThreadPoolBuilder::new()
|
||||||
.stack_size(RAYON_WORKER_STACK_SIZE)
|
.stack_size(RAYON_WORKER_STACK_SIZE)
|
||||||
.build_global()
|
.build_global()
|
||||||
|
|||||||
@@ -129,7 +129,6 @@ impl Compiler {
|
|||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
output.preprocess_ast(&version, pipeline, suppressed_warnings.as_slice())?;
|
output.preprocess_ast(&version, pipeline, suppressed_warnings.as_slice())?;
|
||||||
output.remove_evm();
|
|
||||||
|
|
||||||
Ok(output)
|
Ok(output)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
//! The Solidity compiler pipeline type.
|
//! The Solidity compiler pipeline type.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::solc::version::Version as SolcVersion;
|
use crate::solc::version::Version as SolcVersion;
|
||||||
use crate::solc::Compiler as SolcCompiler;
|
use crate::solc::Compiler as SolcCompiler;
|
||||||
|
|
||||||
/// The Solidity compiler pipeline type.
|
/// The Solidity compiler pipeline type.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
#[allow(non_camel_case_types)]
|
#[allow(non_camel_case_types)]
|
||||||
#[allow(clippy::upper_case_acronyms)]
|
#[allow(clippy::upper_case_acronyms)]
|
||||||
pub enum Pipeline {
|
pub enum Pipeline {
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ pub enum Flag {
|
|||||||
/// The EVM legacy assembly JSON.
|
/// The EVM legacy assembly JSON.
|
||||||
#[serde(rename = "evm.legacyAssembly")]
|
#[serde(rename = "evm.legacyAssembly")]
|
||||||
EVMLA,
|
EVMLA,
|
||||||
|
#[serde(rename = "evm.bytecode")]
|
||||||
|
EVMBC,
|
||||||
#[serde(rename = "evm.deployedBytecode")]
|
#[serde(rename = "evm.deployedBytecode")]
|
||||||
EVMDBC,
|
EVMDBC,
|
||||||
}
|
}
|
||||||
@@ -62,6 +64,7 @@ impl std::fmt::Display for Flag {
|
|||||||
Self::AST => write!(f, "ast"),
|
Self::AST => write!(f, "ast"),
|
||||||
Self::Yul => write!(f, "irOptimized"),
|
Self::Yul => write!(f, "irOptimized"),
|
||||||
Self::EVMLA => write!(f, "evm.legacyAssembly"),
|
Self::EVMLA => write!(f, "evm.legacyAssembly"),
|
||||||
|
Self::EVMBC => write!(f, "evm.bytecode"),
|
||||||
Self::EVMDBC => write!(f, "evm.deployedBytecode"),
|
Self::EVMDBC => write!(f, "evm.deployedBytecode"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ impl File {
|
|||||||
Self {
|
Self {
|
||||||
per_file: Some(HashSet::from_iter([SelectionFlag::AST])),
|
per_file: Some(HashSet::from_iter([SelectionFlag::AST])),
|
||||||
per_contract: Some(HashSet::from_iter([
|
per_contract: Some(HashSet::from_iter([
|
||||||
|
SelectionFlag::EVMBC,
|
||||||
SelectionFlag::EVMDBC,
|
SelectionFlag::EVMDBC,
|
||||||
SelectionFlag::MethodIdentifiers,
|
SelectionFlag::MethodIdentifiers,
|
||||||
SelectionFlag::Metadata,
|
SelectionFlag::Metadata,
|
||||||
|
|||||||
@@ -138,19 +138,6 @@ impl Output {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes EVM artifacts to prevent their accidental usage.
|
|
||||||
pub fn remove_evm(&mut self) {
|
|
||||||
if let Some(files) = self.contracts.as_mut() {
|
|
||||||
for (_, file) in files.iter_mut() {
|
|
||||||
for (_, contract) in file.iter_mut() {
|
|
||||||
if let Some(evm) = contract.evm.as_mut() {
|
|
||||||
evm.bytecode = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Traverses the AST and returns the list of additional errors and warnings.
|
/// Traverses the AST and returns the list of additional errors and warnings.
|
||||||
pub fn preprocess_ast(
|
pub fn preprocess_ast(
|
||||||
&mut self,
|
&mut self,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use crate::solc::pipeline::Pipeline as SolcPipeline;
|
|||||||
use crate::solc::standard_json::input::settings::optimizer::Optimizer as SolcStandardJsonInputSettingsOptimizer;
|
use crate::solc::standard_json::input::settings::optimizer::Optimizer as SolcStandardJsonInputSettingsOptimizer;
|
||||||
use crate::solc::standard_json::input::settings::selection::Selection as SolcStandardJsonInputSettingsSelection;
|
use crate::solc::standard_json::input::settings::selection::Selection as SolcStandardJsonInputSettingsSelection;
|
||||||
use crate::solc::standard_json::input::Input as SolcStandardJsonInput;
|
use crate::solc::standard_json::input::Input as SolcStandardJsonInput;
|
||||||
|
use crate::solc::standard_json::output::contract::evm::bytecode::Bytecode;
|
||||||
use crate::solc::standard_json::output::contract::evm::bytecode::DeployedBytecode;
|
use crate::solc::standard_json::output::contract::evm::bytecode::DeployedBytecode;
|
||||||
use crate::solc::standard_json::output::Output as SolcStandardJsonOutput;
|
use crate::solc::standard_json::output::Output as SolcStandardJsonOutput;
|
||||||
use crate::solc::Compiler as SolcCompiler;
|
use crate::solc::Compiler as SolcCompiler;
|
||||||
@@ -20,6 +21,8 @@ use crate::warning::Warning;
|
|||||||
|
|
||||||
static PVM_BLOB_CACHE: Lazy<Mutex<HashMap<CachedBlob, Vec<u8>>>> = Lazy::new(Default::default);
|
static PVM_BLOB_CACHE: Lazy<Mutex<HashMap<CachedBlob, Vec<u8>>>> = Lazy::new(Default::default);
|
||||||
static EVM_BLOB_CACHE: Lazy<Mutex<HashMap<CachedBlob, Vec<u8>>>> = Lazy::new(Default::default);
|
static EVM_BLOB_CACHE: Lazy<Mutex<HashMap<CachedBlob, Vec<u8>>>> = Lazy::new(Default::default);
|
||||||
|
static EVM_RUNTIME_BLOB_CACHE: Lazy<Mutex<HashMap<CachedBlob, Vec<u8>>>> =
|
||||||
|
Lazy::new(Default::default);
|
||||||
|
|
||||||
#[derive(Hash, PartialEq, Eq)]
|
#[derive(Hash, PartialEq, Eq)]
|
||||||
struct CachedBlob {
|
struct CachedBlob {
|
||||||
@@ -113,14 +116,14 @@ pub fn build_solidity_with_options(
|
|||||||
Ok(output)
|
Ok(output)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build a Solidity contract and get the EVM bin-runtime.
|
/// Build a Solidity contract and get the EVM code
|
||||||
pub fn build_solidity_with_options_evm(
|
pub fn build_solidity_with_options_evm(
|
||||||
sources: BTreeMap<String, String>,
|
sources: BTreeMap<String, String>,
|
||||||
libraries: BTreeMap<String, BTreeMap<String, String>>,
|
libraries: BTreeMap<String, BTreeMap<String, String>>,
|
||||||
remappings: Option<BTreeSet<String>>,
|
remappings: Option<BTreeSet<String>>,
|
||||||
pipeline: SolcPipeline,
|
pipeline: SolcPipeline,
|
||||||
solc_optimizer_enabled: bool,
|
solc_optimizer_enabled: bool,
|
||||||
) -> anyhow::Result<BTreeMap<String, DeployedBytecode>> {
|
) -> anyhow::Result<BTreeMap<String, (Bytecode, DeployedBytecode)>> {
|
||||||
check_dependencies();
|
check_dependencies();
|
||||||
|
|
||||||
inkwell::support::enable_llvm_pretty_stack_trace();
|
inkwell::support::enable_llvm_pretty_stack_trace();
|
||||||
@@ -155,9 +158,12 @@ pub fn build_solidity_with_options_evm(
|
|||||||
for (_, file) in files.iter_mut() {
|
for (_, file) in files.iter_mut() {
|
||||||
for (name, contract) in file.iter_mut() {
|
for (name, contract) in file.iter_mut() {
|
||||||
if let Some(evm) = contract.evm.as_mut() {
|
if let Some(evm) = contract.evm.as_mut() {
|
||||||
if let Some(deployed_bytecode) = evm.deployed_bytecode.as_ref() {
|
let (Some(bytecode), Some(deployed_bytecode)) =
|
||||||
contracts.insert(name.clone(), deployed_bytecode.clone());
|
(evm.bytecode.as_ref(), evm.deployed_bytecode.as_ref())
|
||||||
}
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
contracts.insert(name.clone(), (bytecode.clone(), deployed_bytecode.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,6 +290,16 @@ pub fn compile_blob(contract_name: &str, source_code: &str) -> Vec<u8> {
|
|||||||
/// Compile the EVM bin-runtime of `contract_name` found in given `source_code`.
|
/// Compile the EVM bin-runtime of `contract_name` found in given `source_code`.
|
||||||
/// The `solc` optimizer will be enabled
|
/// The `solc` optimizer will be enabled
|
||||||
pub fn compile_evm_bin_runtime(contract_name: &str, source_code: &str) -> Vec<u8> {
|
pub fn compile_evm_bin_runtime(contract_name: &str, source_code: &str) -> Vec<u8> {
|
||||||
|
compile_evm(contract_name, source_code, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compile the EVM bin of `contract_name` found in given `source_code`.
|
||||||
|
/// The `solc` optimizer will be enabled
|
||||||
|
pub fn compile_evm_deploy_code(contract_name: &str, source_code: &str) -> Vec<u8> {
|
||||||
|
compile_evm(contract_name, source_code, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compile_evm(contract_name: &str, source_code: &str, runtime: bool) -> Vec<u8> {
|
||||||
let pipeline = SolcPipeline::Yul;
|
let pipeline = SolcPipeline::Yul;
|
||||||
let solc_optimizer_enabled = true;
|
let solc_optimizer_enabled = true;
|
||||||
let id = CachedBlob {
|
let id = CachedBlob {
|
||||||
@@ -292,7 +308,12 @@ pub fn compile_evm_bin_runtime(contract_name: &str, source_code: &str) -> Vec<u8
|
|||||||
solc_optimizer_enabled,
|
solc_optimizer_enabled,
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(blob) = EVM_BLOB_CACHE.lock().unwrap().get(&id) {
|
let cache = if runtime {
|
||||||
|
&EVM_RUNTIME_BLOB_CACHE
|
||||||
|
} else {
|
||||||
|
&EVM_BLOB_CACHE
|
||||||
|
};
|
||||||
|
if let Some(blob) = cache.lock().unwrap().get(&id) {
|
||||||
return blob.clone();
|
return blob.clone();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,14 +326,17 @@ pub fn compile_evm_bin_runtime(contract_name: &str, source_code: &str) -> Vec<u8
|
|||||||
solc_optimizer_enabled,
|
solc_optimizer_enabled,
|
||||||
)
|
)
|
||||||
.expect("source should compile");
|
.expect("source should compile");
|
||||||
let bin_runtime = &contracts
|
let object = &contracts
|
||||||
.get(contract_name)
|
.get(contract_name)
|
||||||
.unwrap_or_else(|| panic!("contract '{}' didn't produce bin-runtime", contract_name))
|
.unwrap_or_else(|| panic!("contract '{}' didn't produce bin-runtime", contract_name));
|
||||||
.object;
|
let code = if runtime {
|
||||||
|
object.1.object.as_str()
|
||||||
|
} else {
|
||||||
|
object.0.object.as_str()
|
||||||
|
};
|
||||||
|
let blob = hex::decode(code).expect("code shold be hex encoded");
|
||||||
|
|
||||||
let blob = hex::decode(bin_runtime).expect("bin-runtime shold be hex encoded");
|
cache.lock().unwrap().insert(id, blob.clone());
|
||||||
|
|
||||||
EVM_BLOB_CACHE.lock().unwrap().insert(id, blob.clone());
|
|
||||||
|
|
||||||
blob
|
blob
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user