large upstream sync ♻️

This commit is contained in:
Andreas Bigger 2023-03-16 23:18:00 -04:00
commit 43850702c2
68 changed files with 8555 additions and 903 deletions

26
.github/workflows/benchmarks.yml vendored Normal file
View File

@ -0,0 +1,26 @@
name: benchmarks
on:
workflow_bench:
# push:
# branches: [ "master" ]
env:
MAINNET_RPC_URL: ${{ secrets.MAINNET_RPC_URL }}
GOERLI_RPC_URL: ${{ secrets.GOERLI_RPC_URL }}
jobs:
benches:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- uses: Swatinem/rust-cache@v2
- uses: actions-rs/cargo@v1
with:
command: bench

View File

@ -6,12 +6,15 @@ on:
pull_request:
branches: [ "master" ]
env:
MAINNET_RPC_URL: ${{ secrets.MAINNET_RPC_URL }}
GOERLI_RPC_URL: ${{ secrets.GOERLI_RPC_URL }}
jobs:
check:
name: check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal
@ -23,10 +26,9 @@ jobs:
command: check
test:
name: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal
@ -39,10 +41,9 @@ jobs:
args: --all
fmt:
name: fmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal
@ -56,10 +57,9 @@ jobs:
args: --all -- --check
clippy:
name: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal

8
.gitignore vendored
View File

@ -1 +1,7 @@
/target
.DS_Store
target
*.env
helios-ts/node_modules
helios-ts/dist
helios-ts/helios-*.tgz

1680
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,13 @@
[package]
name = "helios"
version = "0.1.1"
version = "0.2.0"
edition = "2021"
autobenches = false
exclude = [
"benches"
]
[workspace]
members = [
"cli",
"client",
@ -12,24 +15,52 @@ members = [
"config",
"consensus",
"execution",
"helios-ts",
]
[profile.bench]
debug = true
[dependencies]
client = { path = "./client" }
config = { path = "./config" }
common = { path = "./common" }
consensus = { path = "./consensus" }
execution = { path = "./execution" }
serde = { version = "1.0.154", features = ["derive"] }
[dev-dependencies]
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
tokio = { version = "1", features = ["full"] }
eyre = "0.6.8"
home = "0.5.4"
dirs = "4.0.0"
ethers = { version = "1.0.2", features = [ "abigen" ] }
env_logger = "0.9.0"
log = "0.4.17"
tracing-test = "0.2.4"
criterion = { version = "0.4", features = [ "async_tokio", "plotters" ]}
plotters = "0.3.4"
tempfile = "3.4.0"
hex = "0.4.3"
[profile.release]
strip = true
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
######################################
# Examples
######################################
[[example]]
name = "checkpoints"
path = "examples/checkpoints.rs"
[[example]]
name = "basic"
path = "examples/basic.rs"
[[example]]
name = "client"
path = "examples/client.rs"
@ -38,3 +69,26 @@ path = "examples/client.rs"
name = "config"
path = "examples/config.rs"
[[example]]
name = "call"
path = "examples/call.rs"
######################################
# Benchmarks
######################################
[[bench]]
name = "file_db"
harness = false
[[bench]]
name = "get_balance"
harness = false
[[bench]]
name = "get_code"
harness = false
[[bench]]
name = "sync"
harness = false

View File

@ -6,8 +6,7 @@ Helios is a fully trustless, efficient, and portable Ethereum light client writt
Helios converts an untrusted centralized RPC endpoint into a safe unmanipulable local RPC for its users. It syncs in seconds, requires no storage, and is lightweight enough to run on mobile devices.
The entire size of Helios's binary is 13Mb and should be easy to compile into WebAssembly. This makes it a perfect target to embed directly inside wallets and dapps.
The entire size of Helios's binary is 5.3Mb and should be easy to compile into WebAssembly. This makes it a perfect target to embed directly inside wallets and dapps.
## Installing
@ -19,7 +18,6 @@ curl https://raw.githubusercontent.com/a16z/helios/master/heliosup/install | bas
To install Helios, run `heliosup`.
## Usage
To run Helios, run the below command, replacing `$ETH_RPC_URL` with an RPC provider URL such as Alchemy or Infura:
@ -32,17 +30,17 @@ helios --execution-rpc $ETH_RPC_URL
Helios will now run a local RPC server at `http://127.0.0.1:8545`.
Helios also provides examples in the [`examples/`](./examples/) directory. To run an example, you can execute `cargo run --example <example_name>` from inside the helios repository.
Helios provides examples in the [`examples/`](./examples/) directory. To run an example, you can execute `cargo run --example <example_name>` from inside the helios repository.
Helios also provides documentation of its supported RPC methods in the [rpc.md](./rpc.md) file.
### Warning
Helios is still experimental software. While we hope you try it out, we do not suggest adding it as your main RPC in wallets yet. Sending high-value transactions from a wallet connected to Helios is discouraged.
### Additional Options
`--consensus-rpc` or `-c` can be used to set a custom consensus layer rpc endpoint. This must be a consenus node that supports the light client beaconchain api. We recommend using Nimbus for this. If no consensus rpc is supplied, it defaults to `https://www.lightclientdata.org` which is run by us.
`--consensus-rpc` or `-c` can be used to set a custom consensus layer rpc endpoint. This must be a consensus node that supports the light client beaconchain api. We recommend using Nimbus for this. If no consensus rpc is supplied, it defaults to `https://www.lightclientdata.org` which is run by us.
`--checkpoint` or `-w` can be used to set a custom weak subjectivity checkpoint. This must be equal the first beacon blockhash of an epoch. Weak subjectivity checkpoints are the root of trust in the system. If this is set to a malicious value, an attacker can cause the client to sync to the wrong chain. Helios sets a default value initially, then caches the most recent finalized block it has seen for later use.
@ -60,13 +58,14 @@ For example, you can specify the fallback like so: `helios --fallback "https://s
For example, say you set a checkpoint value that is too outdated and Helios cannot sync to it.
If this flag is set, Helios will query all network apis in the community-maintained list
at [ethpandaops/checkpoint-synz-health-checks](https://github.com/ethpandaops/checkpoint-sync-health-checks/blob/master/_data/endpoints.yaml) for their latest slots.
The list of slots is filtered for healthy apis and the most frequent checkpoint occuring in the latest epoch will be returned.
The list of slots is filtered for healthy apis and the most frequent checkpoint occurring in the latest epoch will be returned.
Note: this is a community-maintained list and thus no security guarantees are provided. Use this is a last resort if your checkpoint passed into `--checkpoint` fails.
This is not recommened as malicious checkpoints can be returned from the listed apis, even if they are considered _healthy_.
This is not recommended as malicious checkpoints can be returned from the listed apis, even if they are considered _healthy_.
This can be run like so: `helios --load-external-fallback` (or `helios -l` with the shorthand).
`--help` or `-h` prints the help message.
`--strict-checkpoint-age` or `-s` enables strict checkpoint age checking. If the checkpoint is over two weeks old and this flag is enabled, Helios will error. Without this flag, Helios will instead surface a warning to the user and continue. If the checkpoint is greater than two weeks old, there are theoretical attacks that can cause Helios and over light clients to sync incorrectly. These attacks are complex and expensive, so Helios disables this by default.
`--help` or `-h` prints the help message.
### Configuration Files
@ -84,6 +83,8 @@ execution_rpc = "https://eth-goerli.g.alchemy.com/v2/XXXXX"
checkpoint = "0xb5c375696913865d7c0e166d87bc7c772b6210dc9edf149f4c7ddc6da0dd4495"
```
A comprehensive breakdown of config options is available in the [config.md](./config.md) file.
### Using Helios as a Library
@ -147,16 +148,60 @@ async fn main() -> Result<()> {
}
```
## Architecture
```mermaid
graph LR
Client ----> Rpc
Client ----> Node
Node ----> ConsensusClient
Node ----> ExecutionClient
ExecutionClient ----> ExecutionRpc
ConsensusClient ----> ConsensusRpc
Node ----> Evm
Evm ----> ExecutionClient
ExecutionRpc --> UntrustedExecutionRpc
ConsensusRpc --> UntrustedConsensusRpc
classDef node fill:#f9f,stroke:#333,stroke-width:4px, color:black;
class Node,Client node
classDef execution fill:#f0f,stroke:#333,stroke-width:4px;
class ExecutionClient,ExecutionRpc execution
classDef consensus fill:#ff0,stroke:#333,stroke-width:4px;
class ConsensusClient,ConsensusRpc consensus
classDef evm fill:#0ff,stroke:#333,stroke-width:4px;
class Evm evm
classDef providerC fill:#ffc
class UntrustedConsensusRpc providerC
classDef providerE fill:#fbf
class UntrustedExecutionRpc providerE
classDef rpc fill:#e10
class Rpc rpc
subgraph "External Network"
UntrustedExecutionRpc
UntrustedConsensusRpc
end
```
## Benchmarks
Benchmarks are defined in the [benches](./benches/) subdirectory. They are built using the [criterion](https://github.com/bheisler/criterion.rs) statistics-driven benchmarking library.
To run all benchmarks, you can use `cargo bench`. To run a specific benchmark, you can use `cargo bench --bench <name>`, where `<name>` is one of the benchmarks defined in the [Cargo.toml](./Cargo.toml) file under a `[[bench]]` section.
To learn more about [helios](https://github.com/a16z/helios) benchmarking and to view benchmark flamegraphs, view the [benchmark readme](./benches/README.md).
## Contributing
All contributions to Helios are welcome. Before opening a PR, please submit an issue detailing the bug or feature. When opening a PR, please ensure that your contribution builds on the nightly rust toolchain, has been linted with `cargo fmt`, and contains tests when applicable.
## Telegram
If you are having trouble with Helios or are considering contributing, feel free to join our telegram [here](https://t.me/+IntDY_gZJSRkNTJj).
## Disclaimer
_This code is being provided as is. No guarantee, representation or warranty is being made, express or implied, as to the safety or correctness of the code. It has not been audited and as such there can be no assurance it will work as intended, and users may experience delays, failures, errors, omissions or loss of transmitted information. Nothing in this repo should be construed as investment advice or legal advice for any particular facts or circumstances and is not meant to replace competent counsel. It is strongly advised for you to contact a reputable attorney in your jurisdiction for any questions or concerns with respect thereto. a16z is not liable for any use of the foregoing, and users should proceed with caution and use at their own risk. See a16z.com/disclosures for more info._

18
benches/README.md Normal file
View File

@ -0,0 +1,18 @@
# Helios Benchmarking
Helios performance is measured using [criterion](https://github.com/bheisler/criterion.rs) for comprehensive statistics-driven benchmarking.
Benchmarks are defined in the [benches](./) subdirectory and can be run using the cargo `bench` subcommand (eg `cargo bench`). To run a specific benchmark, you can use `cargo bench --bench <name>`, where `<name>` is one of the benchmarks defined in the [Cargo.toml](./Cargo.toml) file under a `[[bench]]` section.
#### Flamegraphs
[Flamegraph](https://github.com/brendangregg/FlameGraph) is a powerful rust crate for generating profile visualizations, that is graphing the time a program spends in each function. Functions called during execution are displayed as horizontal rectangles with the width proportional to the time spent in that function. As the call stack grows (think nested function invocations), the rectangles are stacked vertically. This provides a powerful visualization for quickly understanding which parts of a codebase take up disproportionate amounts of time.
Check out Brendan Gregg's [Flame Graphs](http://www.brendangregg.com/flamegraphs.html) blog post if you're interested in learning more about flamegraphs and performance visualizations in general.
To generate a flamegraph for helios, you can use the `cargo flamegraph` subcommand. For example, to generate a flamegraph for the [`client`](./examples/client.rs) example, you can run:
```bash
cargo flamegraph --example client -o ./flamegraphs/client.svg
```

51
benches/file_db.rs Normal file
View File

@ -0,0 +1,51 @@
use client::database::Database;
use config::Config;
use criterion::{criterion_group, criterion_main, Criterion};
use helios::prelude::FileDB;
use tempfile::tempdir;
mod harness;
criterion_main!(file_db);
criterion_group! {
name = file_db;
config = Criterion::default();
targets = save_checkpoint, load_checkpoint
}
/// Benchmark saving/writing a checkpoint to the file db.
pub fn save_checkpoint(c: &mut Criterion) {
c.bench_function("save_checkpoint", |b| {
let checkpoint = vec![1, 2, 3];
b.iter(|| {
let data_dir = Some(tempdir().unwrap().into_path());
let config = Config {
data_dir,
..Default::default()
};
let db = FileDB::new(&config).unwrap();
db.save_checkpoint(checkpoint.clone()).unwrap();
})
});
}
/// Benchmark loading a checkpoint from the file db.
pub fn load_checkpoint(c: &mut Criterion) {
c.bench_function("load_checkpoint", |b| {
// First write to the db
let data_dir = Some(tempdir().unwrap().into_path());
let config = Config {
data_dir,
..Default::default()
};
let db = FileDB::new(&config).unwrap();
let written_checkpoint = vec![1; 32];
db.save_checkpoint(written_checkpoint.clone()).unwrap();
// Then read from the db
b.iter(|| {
let checkpoint = db.load_checkpoint().unwrap();
assert_eq!(checkpoint, written_checkpoint.clone());
})
});
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 27 KiB

70
benches/get_balance.rs Normal file
View File

@ -0,0 +1,70 @@
use criterion::{criterion_group, criterion_main, Criterion};
use ethers::prelude::*;
use helios::types::BlockTag;
use std::str::FromStr;
mod harness;
criterion_main!(get_balance);
criterion_group! {
name = get_balance;
config = Criterion::default().sample_size(10);
targets = bench_mainnet_get_balance, bench_goerli_get_balance
}
/// Benchmark mainnet get balance.
/// Address: 0x00000000219ab540356cbb839cbe05303d7705fa (beacon chain deposit address)
pub fn bench_mainnet_get_balance(c: &mut Criterion) {
c.bench_function("get_balance", |b| {
// Create a new multi-threaded tokio runtime.
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
// Construct a mainnet client using our harness and tokio runtime.
let client = std::sync::Arc::new(harness::construct_mainnet_client(&rt).unwrap());
// Get the beacon chain deposit contract address.
let addr = Address::from_str("0x00000000219ab540356cbb839cbe05303d7705fa").unwrap();
let block = BlockTag::Latest;
// Execute the benchmark asynchronously.
b.to_async(rt).iter(|| async {
let inner = std::sync::Arc::clone(&client);
inner.get_balance(&addr, block).await.unwrap()
})
});
}
/// Benchmark goerli get balance.
/// Address: 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6 (goerli weth)
pub fn bench_goerli_get_balance(c: &mut Criterion) {
c.bench_function("get_balance", |b| {
// Create a new multi-threaded tokio runtime.
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
// Construct a goerli client using our harness and tokio runtime.
let gc = match harness::construct_goerli_client(&rt) {
Ok(gc) => gc,
Err(e) => {
println!("failed to construct goerli client: {}", e);
std::process::exit(1);
}
};
let client = std::sync::Arc::new(gc);
// Get the beacon chain deposit contract address.
let addr = Address::from_str("0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6").unwrap();
let block = BlockTag::Latest;
// Execute the benchmark asynchronously.
b.to_async(rt).iter(|| async {
let inner = std::sync::Arc::clone(&client);
inner.get_balance(&addr, block).await.unwrap()
})
});
}

63
benches/get_code.rs Normal file
View File

@ -0,0 +1,63 @@
use criterion::{criterion_group, criterion_main, Criterion};
use ethers::prelude::*;
use helios::types::BlockTag;
use std::str::FromStr;
mod harness;
criterion_main!(get_code);
criterion_group! {
name = get_code;
config = Criterion::default().sample_size(10);
targets = bench_mainnet_get_code, bench_goerli_get_code
}
/// Benchmark mainnet get code call.
/// Address: 0x00000000219ab540356cbb839cbe05303d7705fa (beacon chain deposit address)
pub fn bench_mainnet_get_code(c: &mut Criterion) {
c.bench_function("get_code", |b| {
// Create a new multi-threaded tokio runtime.
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
// Construct a mainnet client using our harness and tokio runtime.
let client = std::sync::Arc::new(harness::construct_mainnet_client(&rt).unwrap());
// Get the beacon chain deposit contract address.
let addr = Address::from_str("0x00000000219ab540356cbb839cbe05303d7705fa").unwrap();
let block = BlockTag::Latest;
// Execute the benchmark asynchronously.
b.to_async(rt).iter(|| async {
let inner = std::sync::Arc::clone(&client);
inner.get_code(&addr, block).await.unwrap()
})
});
}
/// Benchmark goerli get code call.
/// Address: 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6 (goerli weth)
pub fn bench_goerli_get_code(c: &mut Criterion) {
c.bench_function("get_code", |b| {
// Create a new multi-threaded tokio runtime.
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
// Construct a goerli client using our harness and tokio runtime.
let client = std::sync::Arc::new(harness::construct_goerli_client(&rt).unwrap());
// Get the beacon chain deposit contract address.
let addr = Address::from_str("0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6").unwrap();
let block = BlockTag::Latest;
// Execute the benchmark asynchronously.
b.to_async(rt).iter(|| async {
let inner = std::sync::Arc::clone(&client);
inner.get_code(&addr, block).await.unwrap()
})
});
}

113
benches/harness.rs Normal file
View File

@ -0,0 +1,113 @@
#![allow(dead_code)]
use std::{str::FromStr, sync::Arc};
use ::client::{database::ConfigDB, Client};
use ethers::{
abi::Address,
types::{H256, U256},
};
use helios::{client, config::networks, types::BlockTag};
/// Fetches the latest mainnet checkpoint from the fallback service.
///
/// Uses the [CheckpointFallback](config::CheckpointFallback).
/// The `build` method will fetch a list of [CheckpointFallbackService](config::CheckpointFallbackService)s from a community-mainained list by ethPandaOps.
/// This list is NOT guaranteed to be secure, but is provided in good faith.
/// The raw list can be found here: https://github.com/ethpandaops/checkpoint-sync-health-checks/blob/master/_data/endpoints.yaml
pub async fn fetch_mainnet_checkpoint() -> eyre::Result<H256> {
let cf = config::CheckpointFallback::new().build().await.unwrap();
cf.fetch_latest_checkpoint(&networks::Network::MAINNET)
.await
}
/// Constructs a mainnet [Client](client::Client) for benchmark usage.
///
/// Requires a [Runtime](tokio::runtime::Runtime) to be passed in by reference.
/// The client is parameterized with a [FileDB](client::FileDB).
/// It will also use the environment variable `MAINNET_RPC_URL` to connect to a mainnet node.
/// The client will use `https://www.lightclientdata.org` as the consensus RPC.
pub fn construct_mainnet_client(
rt: &tokio::runtime::Runtime,
) -> eyre::Result<client::Client<ConfigDB>> {
rt.block_on(inner_construct_mainnet_client())
}
pub async fn inner_construct_mainnet_client() -> eyre::Result<client::Client<ConfigDB>> {
let benchmark_rpc_url = std::env::var("MAINNET_RPC_URL")?;
let mut client = client::ClientBuilder::new()
.network(networks::Network::MAINNET)
.consensus_rpc("https://www.lightclientdata.org")
.execution_rpc(&benchmark_rpc_url)
.load_external_fallback()
.build()?;
client.start().await?;
Ok(client)
}
pub async fn construct_mainnet_client_with_checkpoint(
checkpoint: &str,
) -> eyre::Result<client::Client<ConfigDB>> {
let benchmark_rpc_url = std::env::var("MAINNET_RPC_URL")?;
let mut client = client::ClientBuilder::new()
.network(networks::Network::MAINNET)
.consensus_rpc("https://www.lightclientdata.org")
.execution_rpc(&benchmark_rpc_url)
.checkpoint(checkpoint)
.build()?;
client.start().await?;
Ok(client)
}
/// Create a tokio multi-threaded runtime.
///
/// # Panics
///
/// Panics if the runtime cannot be created.
pub fn construct_runtime() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
}
/// Constructs a goerli client for benchmark usage.
///
/// Requires a [Runtime](tokio::runtime::Runtime) to be passed in by reference.
/// The client is parameterized with a [FileDB](client::FileDB).
/// It will also use the environment variable `GOERLI_RPC_URL` to connect to a mainnet node.
/// The client will use `http://testing.prater.beacon-api.nimbus.team` as the consensus RPC.
pub fn construct_goerli_client(
rt: &tokio::runtime::Runtime,
) -> eyre::Result<client::Client<ConfigDB>> {
rt.block_on(async {
let benchmark_rpc_url = std::env::var("GOERLI_RPC_URL")?;
let mut client = client::ClientBuilder::new()
.network(networks::Network::GOERLI)
.consensus_rpc("http://testing.prater.beacon-api.nimbus.team")
.execution_rpc(&benchmark_rpc_url)
.load_external_fallback()
.build()?;
client.start().await?;
Ok(client)
})
}
/// Gets the balance of the given address on mainnet.
pub fn get_balance(
rt: &tokio::runtime::Runtime,
client: Arc<Client<ConfigDB>>,
address: &str,
) -> eyre::Result<U256> {
rt.block_on(async {
let block = BlockTag::Latest;
let address = Address::from_str(address)?;
client.get_balance(&address, block).await
})
}
// h/t @ https://github.com/smrpn
// rev: https://github.com/smrpn/casbin-rs/commit/7a0a75d8075440ee65acdac3ee9c0de6fcbd5c48
pub fn await_future<F: std::future::Future<Output = T>, T>(future: F) -> T {
tokio::runtime::Runtime::new().unwrap().block_on(future)
}

81
benches/sync.rs Normal file
View File

@ -0,0 +1,81 @@
use criterion::{criterion_group, criterion_main, Criterion};
use ethers::types::Address;
use helios::types::BlockTag;
mod harness;
criterion_main!(sync);
criterion_group! {
name = sync;
config = Criterion::default().sample_size(10);
targets =
bench_full_sync,
bench_full_sync_with_call,
bench_full_sync_checkpoint_fallback,
bench_full_sync_with_call_checkpoint_fallback,
}
/// Benchmark full client sync.
pub fn bench_full_sync(c: &mut Criterion) {
// Externally, let's fetch the latest checkpoint from our fallback service so as not to benchmark the checkpoint fetch.
let checkpoint = harness::await_future(harness::fetch_mainnet_checkpoint()).unwrap();
let checkpoint = hex::encode(checkpoint);
// On client construction, it will sync to the latest checkpoint using our fetched checkpoint.
c.bench_function("full_sync", |b| {
b.to_async(harness::construct_runtime()).iter(|| async {
let _client = std::sync::Arc::new(
harness::construct_mainnet_client_with_checkpoint(&checkpoint)
.await
.unwrap(),
);
})
});
}
/// Benchmark full client sync.
/// Address: 0x00000000219ab540356cbb839cbe05303d7705fa (beacon chain deposit address)
pub fn bench_full_sync_with_call(c: &mut Criterion) {
// Externally, let's fetch the latest checkpoint from our fallback service so as not to benchmark the checkpoint fetch.
let checkpoint = harness::await_future(harness::fetch_mainnet_checkpoint()).unwrap();
let checkpoint = hex::encode(checkpoint);
// On client construction, it will sync to the latest checkpoint using our fetched checkpoint.
c.bench_function("full_sync_call", |b| {
b.to_async(harness::construct_runtime()).iter(|| async {
let client = std::sync::Arc::new(
harness::construct_mainnet_client_with_checkpoint(&checkpoint)
.await
.unwrap(),
);
let addr = "0x00000000219ab540356cbb839cbe05303d7705fa"
.parse::<Address>()
.unwrap();
let block = BlockTag::Latest;
client.get_balance(&addr, block).await.unwrap()
})
});
}
/// Benchmark full client sync with checkpoint fallback.
pub fn bench_full_sync_checkpoint_fallback(c: &mut Criterion) {
c.bench_function("full_sync_fallback", |b| {
let rt = harness::construct_runtime();
b.iter(|| {
let _client = std::sync::Arc::new(harness::construct_mainnet_client(&rt).unwrap());
})
});
}
/// Benchmark full client sync with a call and checkpoint fallback.
/// Address: 0x00000000219ab540356cbb839cbe05303d7705fa (beacon chain deposit address)
pub fn bench_full_sync_with_call_checkpoint_fallback(c: &mut Criterion) {
c.bench_function("full_sync_call", |b| {
let addr = "0x00000000219ab540356cbb839cbe05303d7705fa";
let rt = harness::construct_runtime();
b.iter(|| {
let client = std::sync::Arc::new(harness::construct_mainnet_client(&rt).unwrap());
harness::get_balance(&rt, client, addr).unwrap();
})
});
}

View File

@ -2,7 +2,7 @@ cargo-features = ["different-binary-name"]
[package]
name = "cli"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
[[bin]]

View File

@ -1,84 +0,0 @@
use std::{fs, path::PathBuf, str::FromStr};
use clap::Parser;
use common::utils::hex_str_to_bytes;
use dirs::home_dir;
use config::{CliConfig, Config};
#[derive(Parser)]
pub struct Cli {
#[clap(short, long, default_value = "mainnet")]
network: String,
#[clap(short = 'p', long, env)]
rpc_port: Option<u16>,
#[clap(short = 'w', long, env)]
checkpoint: Option<String>,
#[clap(short, long, env)]
execution_rpc: Option<String>,
#[clap(short, long, env)]
consensus_rpc: Option<String>,
#[clap(short, long, env)]
data_dir: Option<String>,
#[clap(short = 'f', long, env)]
fallback: Option<String>,
#[clap(short = 'l', long, env)]
load_external_fallback: bool,
#[clap(short = 's', long, env)]
with_ws: bool,
#[clap(short = 'h', long, env)]
with_http: bool,
}
impl Cli {
pub fn to_config() -> Config {
let cli = Cli::parse();
let config_path = home_dir().unwrap().join(".helios/helios.toml");
let cli_config = cli.as_cli_config();
Config::from_file(&config_path, &cli.network, &cli_config)
}
fn as_cli_config(&self) -> CliConfig {
let checkpoint = match &self.checkpoint {
Some(checkpoint) => Some(hex_str_to_bytes(checkpoint).expect("invalid checkpoint")),
None => self.get_cached_checkpoint(),
};
CliConfig {
checkpoint,
execution_rpc: self.execution_rpc.clone(),
consensus_rpc: self.consensus_rpc.clone(),
data_dir: self.get_data_dir(),
rpc_port: self.rpc_port,
fallback: self.fallback.clone(),
load_external_fallback: self.load_external_fallback,
with_ws: self.with_ws,
with_http: self.with_http,
}
}
fn get_cached_checkpoint(&self) -> Option<Vec<u8>> {
let data_dir = self.get_data_dir();
let checkpoint_file = data_dir.join("checkpoint");
if checkpoint_file.exists() {
let checkpoint_res = fs::read(checkpoint_file);
match checkpoint_res {
Ok(checkpoint) => Some(checkpoint),
Err(_) => None,
}
} else {
None
}
}
fn get_data_dir(&self) -> PathBuf {
if let Some(dir) = &self.data_dir {
PathBuf::from_str(dir).expect("cannot find data dir")
} else {
home_dir()
.unwrap()
.join(format!(".helios/data/{}", self.network))
}
}
}

View File

@ -1,19 +1,138 @@
use env_logger::Env;
use std::{
path::PathBuf,
process::exit,
str::FromStr,
sync::{Arc, Mutex},
};
use eyre::Result;
use clap::Parser;
use dirs::home_dir;
use env_logger::Env;
use futures::executor::block_on;
use log::{error, info};
use client::{Client, ClientBuilder};
mod cli;
use common::utils::hex_str_to_bytes;
use client::{database::FileDB, Client, ClientBuilder};
use config::{CliConfig, Config};
#[tokio::main]
async fn main() -> Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
let config = cli::Cli::to_config();
let mut client = ClientBuilder::new().config(config).build()?;
let config = get_config();
let mut client = match ClientBuilder::new().config(config).build() {
Ok(client) => client,
Err(err) => {
error!("{}", err);
exit(1);
}
};
client.start().await?;
if let Err(err) = client.start().await {
error!("{}", err);
exit(1);
}
Client::register_shutdown_handler(client);
std::future::pending().await
}
fn register_shutdown_handler(client: Client<FileDB>) {
let client = Arc::new(client);
let shutdown_counter = Arc::new(Mutex::new(0));
ctrlc::set_handler(move || {
let mut counter = shutdown_counter.lock().unwrap();
*counter += 1;
let counter_value = *counter;
if counter_value == 3 {
info!("forced shutdown");
exit(0);
}
info!(
"shutting down... press ctrl-c {} more times to force quit",
3 - counter_value
);
if counter_value == 1 {
let client = client.clone();
std::thread::spawn(move || {
block_on(client.shutdown());
exit(0);
});
}
})
.expect("could not register shutdown handler");
}
fn get_config() -> Config {
let cli = Cli::parse();
let config_path = home_dir().unwrap().join(".helios/helios.toml");
let cli_config = cli.as_cli_config();
Config::from_file(&config_path, &cli.network, &cli_config)
}
#[derive(Parser)]
struct Cli {
#[clap(short, long, default_value = "mainnet")]
network: String,
#[clap(short = 'p', long, env)]
rpc_port: Option<u16>,
#[clap(short = 'w', long, env)]
checkpoint: Option<String>,
#[clap(short, long, env)]
execution_rpc: Option<String>,
#[clap(short, long, env)]
consensus_rpc: Option<String>,
#[clap(short, long, env)]
data_dir: Option<String>,
#[clap(short = 'f', long, env)]
fallback: Option<String>,
#[clap(short = 'l', long, env)]
load_external_fallback: bool,
#[clap(short = 's', long, env)]
strict_checkpoint_age: bool,
#[clap(short = 's', long, env)]
with_ws: bool,
#[clap(short = 'h', long, env)]
with_http: bool,
}
impl Cli {
fn as_cli_config(&self) -> CliConfig {
let checkpoint = self
.checkpoint
.as_ref()
.map(|c| hex_str_to_bytes(c).expect("invalid checkpoint"));
CliConfig {
checkpoint,
execution_rpc: self.execution_rpc.clone(),
consensus_rpc: self.consensus_rpc.clone(),
data_dir: self.get_data_dir(),
rpc_port: self.rpc_port,
fallback: self.fallback.clone(),
load_external_fallback: self.load_external_fallback,
strict_checkpoint_age: self.strict_checkpoint_age,
with_ws: self.with_ws,
with_http: self.with_http,
}
}
fn get_data_dir(&self) -> PathBuf {
if let Some(dir) = &self.data_dir {
PathBuf::from_str(dir).expect("cannot find data dir")
} else {
home_dir()
.unwrap()
.join(format!(".helios/data/{}", self.network))
}
}
}

View File

@ -1,14 +1,13 @@
[package]
name = "client"
version = "0.1.1"
version = "0.2.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
eyre = "0.6.8"
serde = { version = "1.0.143", features = ["derive"] }
hex = "0.4.3"
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "cb08f18ca919cc1b685b861d0fa9e2daabe89737" }
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "d09f55b4f8554491e3431e01af1c32347a8781cd" }
ethers = { version = "1.0.2", features = [ "ws", "default" ] }
jsonrpsee = { version = "0.15.1", features = ["full"] }
futures = "0.3.23"
@ -20,3 +19,13 @@ common = { path = "../common" }
consensus = { path = "../consensus" }
execution = { path = "../execution" }
config = { path = "../config" }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
jsonrpsee = { version = "0.15.1", features = ["full"] }
tokio = { version = "1", features = ["full"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
gloo-timers = "0.2.6"
wasm-bindgen-futures = "0.4.33"
tokio = { version = "1", features = ["sync"] }

View File

@ -2,8 +2,12 @@ use std::process::exit;
use std::sync::{Arc, Mutex};
use config::networks::Network;
use consensus::errors::ConsensusError;
use ethers::prelude::{Address, U256};
use ethers::types::{Filter, Log, Transaction, TransactionReceipt, H256};
use ethers::types::{
FeeHistory, Filter, Log, SyncingStatus, Transaction, TransactionReceipt, H256,
};
use eyre::{eyre, Result};
use common::types::BlockTag;
use config::{CheckpointFallback, Config};
@ -11,41 +15,238 @@ use consensus::{types::Header, ConsensusClient};
use execution::rpc::{ExecutionRpc, WsRpc};
use execution::types::{CallOpts, ExecutionBlock};
use futures::executor::block_on;
use log::{info, warn};
use log::{error, info, warn};
use tokio::spawn;
use tokio::sync::RwLock;
#[cfg(not(target_arch = "wasm32"))]
use std::path::PathBuf;
#[cfg(not(target_arch = "wasm32"))]
use tokio::spawn;
#[cfg(not(target_arch = "wasm32"))]
use tokio::time::sleep;
use crate::database::{Database, FileDB};
#[cfg(target_arch = "wasm32")]
use gloo_timers::callback::Interval;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;
use crate::database::Database;
use crate::errors::NodeError;
use crate::node::Node;
#[cfg(not(target_arch = "wasm32"))]
use crate::rpc::Rpc;
pub struct Client<DB: Database, R: ExecutionRpc> {
node: Arc<RwLock<Node<R>>>,
rpc: Option<Rpc<R>>,
db: Option<DB>,
#[derive(Default)]
pub struct ClientBuilder {
network: Option<Network>,
consensus_rpc: Option<String>,
execution_rpc: Option<String>,
checkpoint: Option<Vec<u8>>,
#[cfg(not(target_arch = "wasm32"))]
rpc_port: Option<u16>,
#[cfg(not(target_arch = "wasm32"))]
data_dir: Option<PathBuf>,
config: Option<Config>,
fallback: Option<String>,
load_external_fallback: bool,
strict_checkpoint_age: bool,
}
impl ClientBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn network(mut self, network: Network) -> Self {
self.network = Some(network);
self
}
pub fn consensus_rpc(mut self, consensus_rpc: &str) -> Self {
self.consensus_rpc = Some(consensus_rpc.to_string());
self
}
pub fn execution_rpc(mut self, execution_rpc: &str) -> Self {
self.execution_rpc = Some(execution_rpc.to_string());
self
}
pub fn checkpoint(mut self, checkpoint: &str) -> Self {
let checkpoint = hex::decode(checkpoint.strip_prefix("0x").unwrap_or(checkpoint))
.expect("cannot parse checkpoint");
self.checkpoint = Some(checkpoint);
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn rpc_port(mut self, port: u16) -> Self {
self.rpc_port = Some(port);
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn data_dir(mut self, data_dir: PathBuf) -> Self {
self.data_dir = Some(data_dir);
self
}
pub fn config(mut self, config: Config) -> Self {
self.config = Some(config);
self
}
pub fn fallback(mut self, fallback: &str) -> Self {
self.fallback = Some(fallback.to_string());
self
}
pub fn load_external_fallback(mut self) -> Self {
self.load_external_fallback = true;
self
}
pub fn strict_checkpoint_age(mut self) -> Self {
self.strict_checkpoint_age = true;
self
}
pub fn build<DB: Database>(self) -> Result<Client<DB>> {
let base_config = if let Some(network) = self.network {
network.to_base_config()
} else {
let config = self
.config
.as_ref()
.ok_or(eyre!("missing network config"))?;
config.to_base_config()
};
let consensus_rpc = self.consensus_rpc.unwrap_or_else(|| {
self.config
.as_ref()
.expect("missing consensus rpc")
.consensus_rpc
.clone()
});
let execution_rpc = self.execution_rpc.unwrap_or_else(|| {
self.config
.as_ref()
.expect("missing execution rpc")
.execution_rpc
.clone()
});
let checkpoint = if let Some(checkpoint) = self.checkpoint {
Some(checkpoint)
} else if let Some(config) = &self.config {
config.checkpoint.clone()
} else {
None
};
let default_checkpoint = if let Some(config) = &self.config {
config.default_checkpoint.clone()
} else {
base_config.default_checkpoint.clone()
};
#[cfg(not(target_arch = "wasm32"))]
let rpc_port = if self.rpc_port.is_some() {
self.rpc_port
} else if let Some(config) = &self.config {
config.rpc_port
} else {
None
};
#[cfg(not(target_arch = "wasm32"))]
let data_dir = if self.data_dir.is_some() {
self.data_dir
} else if let Some(config) = &self.config {
config.data_dir.clone()
} else {
None
};
let fallback = if self.fallback.is_some() {
self.fallback
} else if let Some(config) = &self.config {
config.fallback.clone()
} else {
None
};
let load_external_fallback = if let Some(config) = &self.config {
self.load_external_fallback || config.load_external_fallback
} else {
self.load_external_fallback
};
let strict_checkpoint_age = if let Some(config) = &self.config {
self.strict_checkpoint_age || config.strict_checkpoint_age
} else {
self.strict_checkpoint_age
};
let config = Config {
consensus_rpc,
execution_rpc,
checkpoint,
default_checkpoint,
#[cfg(not(target_arch = "wasm32"))]
rpc_port,
#[cfg(target_arch = "wasm32")]
rpc_port: None,
#[cfg(not(target_arch = "wasm32"))]
data_dir,
#[cfg(target_arch = "wasm32")]
data_dir: None,
chain: base_config.chain,
forks: base_config.forks,
max_checkpoint_age: base_config.max_checkpoint_age,
fallback,
load_external_fallback,
strict_checkpoint_age,
};
Client::new(config)
}
}
pub struct Client<DB: Database> {
node: Arc<RwLock<Node>>,
#[cfg(not(target_arch = "wasm32"))]
rpc: Option<Rpc>,
db: DB,
fallback: Option<String>,
load_external_fallback: bool,
ws: bool,
http: bool,
}
impl Client<FileDB, WsRpc> {
pub fn new(config: Config) -> eyre::Result<Self> {
impl<DB: Database> Client<DB> {
fn new(mut config: Config) -> Result<Self> {
let db = DB::new(&config)?;
if config.checkpoint.is_none() {
let checkpoint = db.load_checkpoint()?;
config.checkpoint = Some(checkpoint);
}
let config = Arc::new(config);
let node = Node::new(config.clone())?;
let node = Arc::new(RwLock::new(node));
let rpc = config
.rpc_port
.map(|port| Rpc::new(node.clone(), config.with_http, config.with_ws, port));
let data_dir = config.data_dir.clone();
let db = data_dir.map(FileDB::new);
#[cfg(not(target_arch = "wasm32"))]
let rpc = config.rpc_port.map(|port| Rpc::new(node.clone(), config.with_http, config.with_ws, port));
Ok(Client {
node,
#[cfg(not(target_arch = "wasm32"))]
rpc,
db,
fallback: config.fallback.clone(),
@ -54,43 +255,9 @@ impl Client<FileDB, WsRpc> {
http: config.with_http,
})
}
}
impl Client<FileDB, WsRpc> {
pub fn register_shutdown_handler(client: Client<FileDB, WsRpc>) {
let client = Arc::new(client);
let shutdown_counter = Arc::new(Mutex::new(0));
ctrlc::set_handler(move || {
let mut counter = shutdown_counter.lock().unwrap();
*counter += 1;
let counter_value = *counter;
if counter_value == 3 {
info!("forced shutdown");
exit(0);
}
info!(
"shutting down... press ctrl-c {} more times to force quit",
3 - counter_value
);
if counter_value == 1 {
let client = client.clone();
std::thread::spawn(move || {
block_on(client.shutdown());
exit(0);
});
}
})
.expect("could not register shutdown handler");
}
}
impl<DB: Database, R: ExecutionRpc> Client<DB, R> {
pub async fn start(&mut self) -> eyre::Result<()> {
pub async fn start(&mut self) -> Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(rpc) = &mut self.rpc {
if self.ws {
rpc.start_ws().await?;
@ -100,19 +267,46 @@ impl<DB: Database, R: ExecutionRpc> Client<DB, R> {
}
}
if self.node.write().await.sync().await.is_err() {
warn!(
"failed to sync consensus node with checkpoint: 0x{}",
hex::encode(&self.node.read().await.config.checkpoint),
);
let fallback = self.boot_from_fallback().await;
if fallback.is_err() && self.load_external_fallback {
self.boot_from_external_fallbacks().await?
} else if fallback.is_err() {
return Err(eyre::eyre!("Checkpoint is too old. Please update your checkpoint. Alternatively, set an explicit checkpoint fallback service url with the `-f` flag or use the configured external fallback services with `-l` (NOT RECOMMENED). See https://github.com/a16z/helios#additional-options for more information."));
let sync_res = self.node.write().await.sync().await;
if let Err(err) = sync_res {
match err {
NodeError::ConsensusSyncError(err) => match err.downcast_ref() {
Some(ConsensusError::CheckpointTooOld) => {
warn!(
"failed to sync consensus node with checkpoint: 0x{}",
hex::encode(
self.node
.read()
.await
.config
.checkpoint
.clone()
.unwrap_or_default()
),
);
let fallback = self.boot_from_fallback().await;
if fallback.is_err() && self.load_external_fallback {
self.boot_from_external_fallbacks().await?
} else if fallback.is_err() {
error!("Invalid checkpoint. Please update your checkpoint too a more recent block. Alternatively, set an explicit checkpoint fallback service url with the `-f` flag or use the configured external fallback services with `-l` (NOT RECOMMENDED). See https://github.com/a16z/helios#additional-options for more information.");
return Err(err);
}
}
_ => return Err(err),
},
_ => return Err(err.into()),
}
}
self.start_advance_thread();
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
fn start_advance_thread(&self) {
let node = self.node.clone();
spawn(async move {
loop {
@ -122,11 +316,25 @@ impl<DB: Database, R: ExecutionRpc> Client<DB, R> {
}
let next_update = node.read().await.duration_until_next_update();
sleep(next_update).await;
}
});
}
Ok(())
#[cfg(target_arch = "wasm32")]
fn start_advance_thread(&self) {
let node = self.node.clone();
Interval::new(12000, move || {
let node = node.clone();
spawn_local(async move {
let res = node.write().await.advance().await;
if let Err(err) = res {
warn!("consensus error: {}", err);
}
});
})
.forget();
}
async fn boot_from_fallback(&self) -> eyre::Result<()> {
@ -207,8 +415,8 @@ impl<DB: Database, R: ExecutionRpc> Client<DB, R> {
};
info!("saving last checkpoint hash");
let res = self.db.as_ref().map(|db| db.save_checkpoint(checkpoint));
if res.is_some() && res.unwrap().is_err() {
let res = self.db.save_checkpoint(checkpoint);
if res.is_err() {
warn!("checkpoint save failed");
}
}
@ -239,12 +447,35 @@ impl<DB: Database, R: ExecutionRpc> Client<DB, R> {
self.node.read().await.get_nonce(address, block).await
}
pub async fn get_code(&self, address: &Address, block: BlockTag) -> eyre::Result<Vec<u8>> {
pub async fn get_block_transaction_count_by_hash(&self, hash: &Vec<u8>) -> Result<u64> {
self.node
.read()
.await
.get_block_transaction_count_by_hash(hash)
}
pub async fn get_block_transaction_count_by_number(&self, block: BlockTag) -> Result<u64> {
self.node
.read()
.await
.get_block_transaction_count_by_number(block)
}
pub async fn get_code(&self, address: &Address, block: BlockTag) -> Result<Vec<u8>> {
self.node.read().await.get_code(address, block).await
}
pub async fn get_storage_at(&self, address: &Address, slot: H256) -> eyre::Result<U256> {
self.node.read().await.get_storage_at(address, slot).await
pub async fn get_storage_at(
&self,
address: &Address,
slot: H256,
block: BlockTag,
) -> Result<U256> {
self.node
.read()
.await
.get_storage_at(address, slot, block)
.await
}
pub async fn send_raw_transaction(&self, bytes: &[u8]) -> eyre::Result<H256> {
@ -289,6 +520,19 @@ impl<DB: Database, R: ExecutionRpc> Client<DB, R> {
self.node.read().await.get_block_number()
}
pub async fn get_fee_history(
&self,
block_count: u64,
last_block: u64,
reward_percentiles: &[f64],
) -> Result<Option<FeeHistory>> {
self.node
.read()
.await
.get_fee_history(block_count, last_block, reward_percentiles)
.await
}
pub async fn get_block_by_number(
&self,
block: BlockTag,
@ -313,11 +557,31 @@ impl<DB: Database, R: ExecutionRpc> Client<DB, R> {
.await
}
pub async fn get_transaction_by_block_hash_and_index(
&self,
block_hash: &Vec<u8>,
index: usize,
) -> Result<Option<Transaction>> {
self.node
.read()
.await
.get_transaction_by_block_hash_and_index(block_hash, index)
.await
}
pub async fn chain_id(&self) -> u64 {
self.node.read().await.chain_id()
}
pub async fn get_header(&self) -> eyre::Result<Header> {
pub async fn syncing(&self) -> Result<SyncingStatus> {
self.node.read().await.syncing()
}
pub async fn get_header(&self) -> Result<Header> {
self.node.read().await.get_header()
}
pub async fn get_coinbase(&self) -> Result<Address> {
self.node.read().await.get_coinbase()
}
}

View File

@ -1,22 +1,40 @@
use std::{fs, io::Write, path::PathBuf};
#[cfg(not(target_arch = "wasm32"))]
use std::{
fs,
io::{Read, Write},
path::PathBuf,
};
use config::Config;
use eyre::Result;
pub trait Database {
fn new(config: &Config) -> Result<Self>
where
Self: Sized;
fn save_checkpoint(&self, checkpoint: Vec<u8>) -> Result<()>;
fn load_checkpoint(&self) -> Result<Vec<u8>>;
}
#[cfg(not(target_arch = "wasm32"))]
pub struct FileDB {
data_dir: PathBuf,
default_checkpoint: Vec<u8>,
}
impl FileDB {
pub fn new(data_dir: PathBuf) -> Self {
FileDB { data_dir }
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Database for FileDB {
fn new(config: &Config) -> Result<Self> {
if let Some(data_dir) = &config.data_dir {
return Ok(FileDB {
data_dir: data_dir.to_path_buf(),
default_checkpoint: config.default_checkpoint.clone(),
});
}
eyre::bail!("data dir not in config")
}
fn save_checkpoint(&self, checkpoint: Vec<u8>) -> Result<()> {
fs::create_dir_all(&self.data_dir)?;
@ -30,4 +48,42 @@ impl Database for FileDB {
Ok(())
}
fn load_checkpoint(&self) -> Result<Vec<u8>> {
let mut buf = Vec::new();
let res = fs::OpenOptions::new()
.read(true)
.open(self.data_dir.join("checkpoint"))
.map(|mut f| f.read_to_end(&mut buf));
if buf.len() == 32 && res.is_ok() {
Ok(buf)
} else {
Ok(self.default_checkpoint.clone())
}
}
}
pub struct ConfigDB {
checkpoint: Vec<u8>,
}
impl Database for ConfigDB {
fn new(config: &Config) -> Result<Self> {
Ok(Self {
checkpoint: config
.checkpoint
.clone()
.unwrap_or(config.default_checkpoint.clone()),
})
}
fn load_checkpoint(&self) -> Result<Vec<u8>> {
Ok(self.checkpoint.clone())
}
fn save_checkpoint(&self, _checkpoint: Vec<u8>) -> Result<()> {
Ok(())
}
}

View File

@ -7,7 +7,10 @@ use thiserror::Error;
#[derive(Debug, Error)]
pub enum NodeError {
#[error(transparent)]
ExecutionError(#[from] EvmError),
ExecutionEvmError(#[from] EvmError),
#[error("execution error: {0}")]
ExecutionError(Report),
#[error("out of sync: {0} slots behind")]
OutOfSync(u64),
@ -34,10 +37,11 @@ pub enum NodeError {
BlockNotFoundError(#[from] BlockNotFoundError),
}
#[cfg(not(target_arch = "wasm32"))]
impl NodeError {
pub fn to_json_rpsee_error(self) -> jsonrpsee::core::Error {
match self {
NodeError::ExecutionError(evm_err) => match evm_err {
NodeError::ExecutionEvmError(evm_err) => match evm_err {
EvmError::Revert(data) => {
let mut msg = "execution reverted".to_string();
if let Some(reason) = data.as_ref().and_then(EvmError::decode_revert_reason) {

View File

@ -13,7 +13,8 @@ pub mod database;
pub mod errors;
/// Expose rpc module
#[cfg(not(target_arch = "wasm32"))]
pub mod rpc;
/// Node module is internal to the client crate
mod node;
pub mod node;

View File

@ -3,13 +3,16 @@ use std::sync::Arc;
use std::time::Duration;
use ethers::prelude::{Address, U256};
use ethers::types::{Filter, Log, Transaction, TransactionReceipt, H256};
use ethers::types::{FeeHistory, Filter, Log, SyncProgress, SyncingStatus, Transaction, TransactionReceipt, H256};
use execution::rpc::{ExecutionRpc, WsRpc};
use eyre::{eyre, Result};
use common::errors::BlockNotFoundError;
use common::types::BlockTag;
use config::Config;
use consensus::rpc::nimbus_rpc::NimbusRpc;
use consensus::types::{ExecutionPayload, Header};
use consensus::ConsensusClient;
@ -26,13 +29,14 @@ pub struct Node<R: ExecutionRpc> {
pub config: Arc<Config>,
payloads: BTreeMap<u64, ExecutionPayload>,
finalized_payloads: BTreeMap<u64, ExecutionPayload>,
current_slot: Option<u64>,
pub history_size: usize,
}
impl Node<WsRpc> {
pub fn new(config: Arc<Config>) -> Result<Self, NodeError> {
let consensus_rpc = &config.consensus_rpc;
let checkpoint_hash = &config.checkpoint;
let checkpoint_hash = &config.checkpoint.as_ref().unwrap();
let execution_rpc = &config.execution_rpc;
let consensus = ConsensusClient::new(consensus_rpc, checkpoint_hash, config.clone())
@ -59,6 +63,7 @@ impl Node<WsRpc> {
config,
payloads,
finalized_payloads,
current_slot: None,
history_size: 64,
})
}
@ -69,10 +74,22 @@ where
R: ExecutionRpc,
{
pub async fn sync(&mut self) -> Result<(), NodeError> {
let chain_id = self.config.chain.chain_id;
self.execution
.check_rpc(chain_id)
.await
.map_err(NodeError::ExecutionError)?;
self.consensus
.check_rpc()
.await
.map_err(NodeError::ConsensusSyncError)?;
self.consensus
.sync()
.await
.map_err(NodeError::ConsensusSyncError)?;
self.update_payloads().await
}
@ -113,12 +130,26 @@ where
self.finalized_payloads
.insert(finalized_payload.block_number, finalized_payload);
let start_slot = self
.current_slot
.unwrap_or(latest_header.slot - self.history_size as u64);
let backfill_payloads = self
.consensus
.get_payloads(start_slot, latest_header.slot)
.await
.map_err(NodeError::ConsensusPayloadError)?;
for payload in backfill_payloads {
self.payloads.insert(payload.block_number, payload);
}
self.current_slot = Some(latest_header.slot);
while self.payloads.len() > self.history_size {
self.payloads.pop_first();
}
// only save one finalized block per epoch
// finality updates only occur on epoch boundries
// finality updates only occur on epoch boundaries
while self.finalized_payloads.len() > usize::max(self.history_size / 32, 1) {
self.finalized_payloads.pop_first();
}
@ -136,7 +167,7 @@ where
&self.payloads,
self.chain_id(),
);
evm.call(opts).await.map_err(NodeError::ExecutionError)
evm.call(opts).await.map_err(NodeError::ExecutionEvmError)
}
pub async fn estimate_gas(&self, opts: &CallOpts) -> Result<u64, NodeError> {
@ -151,7 +182,7 @@ where
);
evm.estimate_gas(opts)
.await
.map_err(NodeError::ExecutionError)
.map_err(NodeError::ExecutionEvmError)
}
pub async fn get_balance(&self, address: &Address, block: BlockTag) -> Result<U256> {
@ -170,6 +201,20 @@ where
Ok(account.nonce)
}
pub fn get_block_transaction_count_by_hash(&self, hash: &Vec<u8>) -> Result<u64> {
let payload = self.get_payload_by_hash(hash)?;
let transaction_count = payload.1.transactions.len();
Ok(transaction_count as u64)
}
pub fn get_block_transaction_count_by_number(&self, block: BlockTag) -> Result<u64> {
let payload = self.get_payload(block)?;
let transaction_count = payload.transactions.len();
Ok(transaction_count as u64)
}
pub async fn get_code(&self, address: &Address, block: BlockTag) -> Result<Vec<u8>> {
self.check_blocktag_age(&block)?;
@ -178,10 +223,15 @@ where
Ok(account.code)
}
pub async fn get_storage_at(&self, address: &Address, slot: H256) -> Result<U256> {
pub async fn get_storage_at(
&self,
address: &Address,
slot: H256,
block: BlockTag,
) -> Result<U256> {
self.check_head_age()?;
let payload = self.get_payload(BlockTag::Latest)?;
let payload = self.get_payload(block)?;
let account = self
.execution
.get_account(address, Some(&[slot]), payload)
@ -213,6 +263,18 @@ where
.await
}
pub async fn get_transaction_by_block_hash_and_index(
&self,
hash: &Vec<u8>,
index: usize,
) -> Result<Option<Transaction>> {
let payload = self.get_payload_by_hash(hash)?;
self.execution
.get_transaction_by_block_hash_and_index(payload.1, index)
.await
}
pub async fn get_logs(&self, filter: &Filter) -> Result<Vec<Log>> {
self.execution.get_logs(filter, &self.payloads).await
}
@ -253,24 +315,27 @@ where
}
}
pub async fn get_fee_history(
&self,
block_count: u64,
last_block: u64,
reward_percentiles: &[f64],
) -> Result<Option<FeeHistory>> {
self.execution
.get_fee_history(block_count, last_block, reward_percentiles, &self.payloads)
.await
}
pub async fn get_block_by_hash(
&self,
hash: &Vec<u8>,
full_tx: bool,
) -> Result<Option<ExecutionBlock>> {
let payloads = self
.payloads
.iter()
.filter(|entry| &entry.1.block_hash.to_vec() == hash)
.collect::<Vec<(&u64, &ExecutionPayload)>>();
let payload = self.get_payload_by_hash(hash);
if let Some(payload_entry) = payloads.get(0) {
self.execution
.get_block(payload_entry.1, full_tx)
.await
.map(Some)
} else {
Ok(None)
match payload {
Ok(payload) => self.execution.get_block(payload.1, full_tx).await.map(Some),
Err(_) => Ok(None),
}
}
@ -278,11 +343,49 @@ where
self.config.chain.chain_id
}
pub fn syncing(&self) -> Result<SyncingStatus> {
if self.check_head_age().is_ok() {
Ok(SyncingStatus::IsFalse)
} else {
let latest_synced_block = self.get_block_number()?;
let oldest_payload = self.payloads.first_key_value();
let oldest_synced_block =
oldest_payload.map_or(latest_synced_block, |(key, _value)| *key);
let highest_block = self.consensus.expected_current_slot();
Ok(SyncingStatus::IsSyncing(Box::new(SyncProgress {
current_block: latest_synced_block.into(),
highest_block: highest_block.into(),
starting_block: oldest_synced_block.into(),
pulled_states: None,
known_states: None,
healed_bytecode_bytes: None,
healed_bytecodes: None,
healed_trienode_bytes: None,
healed_trienodes: None,
healing_bytecode: None,
healing_trienodes: None,
synced_account_bytes: None,
synced_accounts: None,
synced_bytecode_bytes: None,
synced_bytecodes: None,
synced_storage: None,
synced_storage_bytes: None,
})))
}
}
pub fn get_header(&self) -> Result<Header> {
self.check_head_age()?;
Ok(self.consensus.get_header().clone())
}
pub fn get_coinbase(&self) -> Result<Address> {
self.check_head_age()?;
let payload = self.get_payload(BlockTag::Latest)?;
let coinbase_address = Address::from_slice(&payload.fee_recipient);
Ok(coinbase_address)
}
pub fn get_last_checkpoint(&self) -> Option<Vec<u8>> {
self.consensus.last_checkpoint.clone()
}
@ -306,6 +409,19 @@ where
}
}
fn get_payload_by_hash(&self, hash: &Vec<u8>) -> Result<(&u64, &ExecutionPayload)> {
let payloads = self
.payloads
.iter()
.filter(|entry| &entry.1.block_hash.to_vec() == hash)
.collect::<Vec<(&u64, &ExecutionPayload)>>();
payloads
.get(0)
.cloned()
.ok_or(eyre!("Block not found by hash"))
}
fn check_head_age(&self) -> Result<(), NodeError> {
let synced_slot = self.consensus.get_header().slot;
let expected_slot = self.consensus.expected_current_slot();

View File

@ -1,4 +1,7 @@
use ethers::types::{Address, Filter, Log, Transaction, TransactionReceipt, H256};
use ethers::{
abi::AbiEncode,
types::{Address, Filter, Log, SyncingStatus, Transaction, TransactionReceipt, H256, U256},
};
use eyre::Result;
use std::{fmt::Display, net::SocketAddr, str::FromStr, sync::Arc};
use tokio::sync::RwLock;
@ -69,6 +72,11 @@ trait EthRpc {
async fn get_balance(&self, address: &str, block: BlockTag) -> Result<String, Error>;
#[method(name = "getTransactionCount")]
async fn get_transaction_count(&self, address: &str, block: BlockTag) -> Result<String, Error>;
#[method(name = "getBlockTransactionCountByHash")]
async fn get_block_transaction_count_by_hash(&self, hash: &str) -> Result<String, Error>;
#[method(name = "getBlockTransactionCountByNumber")]
async fn get_block_transaction_count_by_number(&self, block: BlockTag)
-> Result<String, Error>;
#[method(name = "getCode")]
async fn get_code(&self, address: &str, block: BlockTag) -> Result<String, Error>;
#[method(name = "call")]
@ -104,8 +112,25 @@ trait EthRpc {
) -> Result<Option<TransactionReceipt>, Error>;
#[method(name = "getTransactionByHash")]
async fn get_transaction_by_hash(&self, hash: &str) -> Result<Option<Transaction>, Error>;
#[method(name = "getTransactionByBlockHashAndIndex")]
async fn get_transaction_by_block_hash_and_index(
&self,
hash: &str,
index: usize,
) -> Result<Option<Transaction>, Error>;
#[method(name = "getLogs")]
async fn get_logs(&self, filter: Filter) -> Result<Vec<Log>, Error>;
#[method(name = "getStorageAt")]
async fn get_storage_at(
&self,
address: &str,
slot: H256,
block: BlockTag,
) -> Result<String, Error>;
#[method(name = "getCoinbase")]
async fn get_coinbase(&self) -> Result<Address, Error>;
#[method(name = "syncing")]
async fn syncing(&self) -> Result<SyncingStatus, Error>;
}
#[rpc(client, server, namespace = "net")]
@ -185,6 +210,26 @@ impl<R: ExecutionRpc> EthRpcServer for RpcInner<R> {
let nonce = convert_err(node.get_nonce(&address, block).await)?;
Ok(format!("0x{nonce:x}"))
<<<<<<< HEAD
=======
}
async fn get_block_transaction_count_by_hash(&self, hash: &str) -> Result<String, Error> {
let hash = convert_err(hex_str_to_bytes(hash))?;
let node = self.node.read().await;
let transaction_count = convert_err(node.get_block_transaction_count_by_hash(&hash))?;
Ok(u64_to_hex_string(transaction_count))
}
async fn get_block_transaction_count_by_number(
&self,
block: BlockTag,
) -> Result<String, Error> {
let node = self.node.read().await;
let transaction_count = convert_err(node.get_block_transaction_count_by_number(block))?;
Ok(u64_to_hex_string(transaction_count))
>>>>>>> master
}
async fn get_code(&self, address: &str, block: BlockTag) -> Result<String, Error> {
@ -284,10 +329,46 @@ impl<R: ExecutionRpc> EthRpcServer for RpcInner<R> {
convert_err(node.get_transaction_by_hash(&hash).await)
}
async fn get_transaction_by_block_hash_and_index(
&self,
hash: &str,
index: usize,
) -> Result<Option<Transaction>, Error> {
let hash = convert_err(hex_str_to_bytes(hash))?;
let node = self.node.read().await;
convert_err(
node.get_transaction_by_block_hash_and_index(&hash, index)
.await,
)
}
async fn get_coinbase(&self) -> Result<Address, Error> {
let node = self.node.read().await;
Ok(node.get_coinbase().unwrap())
}
async fn syncing(&self) -> Result<SyncingStatus, Error> {
let node = self.node.read().await;
convert_err(node.syncing())
}
async fn get_logs(&self, filter: Filter) -> Result<Vec<Log>, Error> {
let node = self.node.read().await;
convert_err(node.get_logs(&filter).await)
}
async fn get_storage_at(
&self,
address: &str,
slot: H256,
block: BlockTag,
) -> Result<String, Error> {
let address = convert_err(Address::from_str(address))?;
let node = self.node.read().await;
let storage = convert_err(node.get_storage_at(&address, slot, block).await)?;
Ok(format_hex(&storage))
}
}
#[async_trait]
@ -301,3 +382,23 @@ impl<R: ExecutionRpc> NetRpcServer for RpcInner<R> {
fn convert_err<T, E: Display>(res: Result<T, E>) -> Result<T, Error> {
res.map_err(|err| Error::Custom(err.to_string()))
}
<<<<<<< HEAD
=======
fn format_hex(num: &U256) -> String {
let stripped = num
.encode_hex()
.strip_prefix("0x")
.unwrap()
.trim_start_matches('0')
.to_string();
let stripped = if stripped.is_empty() {
"0".to_string()
} else {
stripped
};
format!("0x{stripped}")
}
>>>>>>> master

View File

@ -1,12 +1,12 @@
[package]
name = "common"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
[dependencies]
eyre = "0.6.8"
serde = { version = "1.0.143", features = ["derive"] }
hex = "0.4.3"
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "cb08f18ca919cc1b685b861d0fa9e2daabe89737" }
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "d09f55b4f8554491e3431e01af1c32347a8781cd" }
ethers = { version = "1.0.2", features = [ "ws", "default" ] }
thiserror = "1.0.37"

View File

@ -1,3 +1,4 @@
use ethers::types::H256;
use thiserror::Error;
use crate::types::BlockTag;
@ -14,6 +15,18 @@ impl BlockNotFoundError {
}
}
#[derive(Debug, Error)]
#[error("slot not found: {slot:?}")]
pub struct SlotNotFoundError {
slot: H256,
}
impl SlotNotFoundError {
pub fn new(slot: H256) -> Self {
Self { slot }
}
}
#[derive(Debug, Error)]
#[error("rpc error on method: {method}, message: {error}")]
pub struct RpcError<E: ToString> {

74
config.md Normal file
View File

@ -0,0 +1,74 @@
## Helios Configuration
All configuration options can be set on a per-network level in `~/.helios/helios.toml`.
#### Comprehensive Example
```toml
[mainnet]
# The consensus rpc to use. This should be a trusted rpc endpoint. Defaults to "https://www.lightclientdata.org".
consensus_rpc = "https://www.lightclientdata.org"
# [REQUIRED] The execution rpc to use. This should be a trusted rpc endpoint.
execution_rpc = "https://eth-mainnet.g.alchemy.com/v2/XXXXX"
# The port to run the JSON-RPC server on. By default, Helios will use port 8545.
rpc_port = 8545
# The latest checkpoint. This should be a trusted checkpoint that is no greater than ~2 weeks old.
# If you are unsure what checkpoint to use, you can skip this option and set either `load_external_fallback` or `fallback` values (described below) to fetch a checkpoint. Though this is not recommended and less secure.
checkpoint = "0x85e6151a246e8fdba36db27a0c7678a575346272fe978c9281e13a8b26cdfa68"
# The directory to store the checkpoint database in. If not provided, Helios will use "~/.helios/data/mainnet", where `mainnet` is the network.
# It is recommended to set this directory to a persistent location mapped to a fast storage device.
data_dir = "/home/user/.helios/mainnet"
# The maximum age of a checkpoint in seconds. If the checkpoint is older than this, Helios will attempt to fetch a new checkpoint.
max_checkpoint_age = 86400
# A checkpoint fallback is used if no checkpoint is provided or the given checkpoint is too old.
# This is expected to be a trusted checkpoint sync api (like provided in https://github.com/ethpandaops/checkpoint-sync-health-checks/blob/master/_data/endpoints.yaml).
fallback = "https://sync-mainnet.beaconcha.in"
# If no checkpoint is provided, or the checkpoint is too old, Helios will attempt to dynamically fetch a checkpoint from a maintained list of checkpoint sync apis.
# NOTE: This is an insecure feature and not recommended for production use. Checkpoint manipulation is possible.
load_external_fallback = true
[goerli]
# The consensus rpc to use. This should be a trusted rpc endpoint. Defaults to Nimbus testnet.
consensus_rpc = "http://testing.prater.beacon-api.nimbus.team"
# [REQUIRED] The execution rpc to use. This should be a trusted rpc endpoint.
execution_rpc = "https://eth-goerli.g.alchemy.com/v2/XXXXX"
# The port to run the JSON-RPC server on. By default, Helios will use port 8545.
rpc_port = 8545
# The latest checkpoint. This should be a trusted checkpoint that is no greater than ~2 weeks old.
# If you are unsure what checkpoint to use, you can skip this option and set either `load_external_fallback` or `fallback` values (described below) to fetch a checkpoint. Though this is not recommended and less secure.
checkpoint = "0xb5c375696913865d7c0e166d87bc7c772b6210dc9edf149f4c7ddc6da0dd4495"
# The directory to store the checkpoint database in. If not provided, Helios will use "~/.helios/data/goerli", where `goerli` is the network.
# It is recommended to set this directory to a persistent location mapped to a fast storage device.
data_dir = "/home/user/.helios/goerli"
# The maximum age of a checkpoint in seconds. If the checkpoint is older than this, Helios will attempt to fetch a new checkpoint.
max_checkpoint_age = 86400
# A checkpoint fallback is used if no checkpoint is provided or the given checkpoint is too old.
# This is expected to be a trusted checkpoint sync api (like provided in https://github.com/ethpandaops/checkpoint-sync-health-checks/blob/master/_data/endpoints.yaml).
fallback = "https://sync-goerli.beaconcha.in"
# If no checkpoint is provided, or the checkpoint is too old, Helios will attempt to dynamically fetch a checkpoint from a maintained list of checkpoint sync apis.
# NOTE: This is an insecure feature and not recommended for production use. Checkpoint manipulation is possible.
load_external_fallback = true
```
#### Options
All configuration options below are available on a per-network level, where network is specified by a header (eg `[mainnet]` or `[goerli]`). Many of these options can be configured through cli flags as well. See [README.md](./README.md#additional-options) or run `helios --help` for more information.
- `consensus_rpc` - The URL of the consensus RPC endpoint used to fetch the latest beacon chain head and sync status. This must be a consenus node that supports the light client beaconchain api. We recommend using Nimbus for this. If no consensus rpc is supplied, it defaults to `https://www.lightclientdata.org` which is run by us.
- `execution_rpc` - The URL of the execution RPC endpoint used to fetch the latest execution chain head and sync status. This must be an execution node that supports the light client execution api. We recommend using Geth for this.
- `rpc_port` - The port to run the JSON-RPC server on. By default, Helios will use port 8545.
- `checkpoint` - The latest checkpoint. This should be a trusted checkpoint that is no greater than ~2 weeks old. If you are unsure what checkpoint to use, you can skip this option and set either `load_external_fallback` or `fallback` values (described below) to fetch a checkpoint. Though this is not recommended and less secure.
- `data_dir` - The directory to store the checkpoint database in. If not provided, Helios will use "~/.helios/data/<NETWORK>", where `<NETWORK>` is the network. It is recommended to set this directory to a persistent location mapped to a fast storage device.
- `max_checkpoint_age` - The maximum age of a checkpoint in seconds. If the checkpoint is older than this, Helios will attempt to fetch a new checkpoint.
- `fallback` - A checkpoint fallback is used if no checkpoint is provided or the given checkpoint is too old. This is expected to be a trusted checkpoint sync api (eg https://sync-mainnet.beaconcha.in). An extensive list of checkpoint sync apis can be found here: https://github.com/ethpandaops/checkpoint-sync-health-checks/blob/master/_data/endpoints.yaml.
- `load_external_fallback` - If no checkpoint is provided, or the checkpoint is too old, Helios will attempt to dynamically fetch a checkpoint from a maintained list of checkpoint sync apis. NOTE: This is an insecure feature and not recommended for production use. Checkpoint manipulation is possible.

View File

@ -1,24 +1,24 @@
[package]
name = "config"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
eyre = "0.6.8"
serde = { version = "1.0.143", features = ["derive"] }
hex = "0.4.3"
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "cb08f18ca919cc1b685b861d0fa9e2daabe89737" }
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "d09f55b4f8554491e3431e01af1c32347a8781cd" }
ethers = { version = "1.0.2", features = [ "ws", "default" ] }
figment = { version = "0.10.7", features = ["toml", "env"] }
thiserror = "1.0.37"
log = "0.4.17"
common = { path = "../common" }
reqwest = "0.11.13"
serde_yaml = "0.9.14"
strum = "0.24.1"
futures = "0.3.25"
common = { path = "../common" }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["full"] }

View File

@ -12,7 +12,7 @@ pub struct BaseConfig {
deserialize_with = "bytes_deserialize",
serialize_with = "bytes_serialize"
)]
pub checkpoint: Vec<u8>,
pub default_checkpoint: Vec<u8>,
pub chain: ChainConfig,
pub forks: Forks,
pub max_checkpoint_age: u64,

View File

@ -117,10 +117,18 @@ impl CheckpointFallback {
&self,
network: &crate::networks::Network,
) -> eyre::Result<H256> {
let services = &self.services[network];
let services = &self.get_healthy_fallback_services(network);
Self::fetch_latest_checkpoint_from_services(&services[..]).await
}
async fn query_service(endpoint: &str) -> Option<RawSlotResponse> {
let client = reqwest::Client::new();
let constructed_url = Self::construct_url(endpoint);
let res = client.get(&constructed_url).send().await.ok()?;
let raw: RawSlotResponse = res.json().await.ok()?;
Some(raw)
}
/// Fetch the latest checkpoint from a list of checkpoint fallback services.
pub async fn fetch_latest_checkpoint_from_services(
services: &[CheckpointFallbackService],
@ -128,27 +136,36 @@ impl CheckpointFallback {
// Iterate over all mainnet checkpoint sync services and get the latest checkpoint slot for each.
let tasks: Vec<_> = services
.iter()
.map(|service| {
.map(|service| async move {
let service = service.clone();
tokio::spawn(async move {
let client = reqwest::Client::new();
let constructed_url = Self::construct_url(&service.endpoint);
let res = client.get(&constructed_url).send().await?;
let raw: RawSlotResponse = res.json().await?;
if raw.data.slots.is_empty() {
return Err(eyre::eyre!("no slots"));
match Self::query_service(&service.endpoint).await {
Some(raw) => {
if raw.data.slots.is_empty() {
return Err(eyre::eyre!("no slots"));
}
let slot = raw
.data
.slots
.iter()
.find(|s| s.block_root.is_some())
.ok_or(eyre::eyre!("no valid slots"))?;
Ok(slot.clone())
}
Ok(raw.data.slots[0].clone())
})
None => Err(eyre::eyre!("failed to query service")),
}
})
.collect();
let slots = futures::future::join_all(tasks)
.await
.iter()
.filter_map(|slot| match &slot {
Ok(Ok(s)) => Some(s.clone()),
Ok(s) => Some(s.clone()),
_ => None,
})
.filter(|s| s.block_root.is_some())
.collect::<Vec<_>>();
// Get the max epoch
@ -230,6 +247,22 @@ impl CheckpointFallback {
.collect()
}
/// Returns a list of healthchecked checkpoint fallback services.
///
/// ### Warning
///
/// These services are not trustworthy and may act with malice by returning invalid checkpoints.
pub fn get_healthy_fallback_services(
&self,
network: &networks::Network,
) -> Vec<CheckpointFallbackService> {
self.services[network]
.iter()
.filter(|service| service.state)
.cloned()
.collect::<Vec<CheckpointFallbackService>>()
}
/// Returns the raw checkpoint fallback service objects for a given network.
pub fn get_fallback_services(
&self,

View File

@ -13,6 +13,7 @@ pub struct CliConfig {
pub data_dir: PathBuf,
pub fallback: Option<String>,
pub load_external_fallback: bool,
pub strict_checkpoint_age: bool,
pub with_ws: bool,
pub with_http: bool,
}
@ -48,6 +49,11 @@ impl CliConfig {
Value::from(self.load_external_fallback),
);
user_dict.insert(
"strict_checkpoint_age",
Value::from(self.strict_checkpoint_age),
);
user_dict.insert("with_ws", Value::from(self.with_ws));
user_dict.insert("with_http", Value::from(self.with_http));

View File

@ -2,31 +2,32 @@ use figment::{
providers::{Format, Serialized, Toml},
Figment,
};
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use std::{path::PathBuf, process::exit};
use crate::base::BaseConfig;
use crate::cli::CliConfig;
use crate::networks;
use crate::types::{ChainConfig, Forks};
use crate::utils::{bytes_deserialize, bytes_serialize};
use crate::utils::{bytes_deserialize, bytes_opt_deserialize};
#[derive(Serialize, Deserialize, Debug, Default)]
#[derive(Deserialize, Debug, Default)]
pub struct Config {
pub consensus_rpc: String,
pub execution_rpc: String,
pub rpc_port: Option<u16>,
#[serde(
deserialize_with = "bytes_deserialize",
serialize_with = "bytes_serialize"
)]
pub checkpoint: Vec<u8>,
#[serde(deserialize_with = "bytes_deserialize")]
pub default_checkpoint: Vec<u8>,
#[serde(default)]
#[serde(deserialize_with = "bytes_opt_deserialize")]
pub checkpoint: Option<Vec<u8>>,
pub data_dir: Option<PathBuf>,
pub chain: ChainConfig,
pub forks: Forks,
pub max_checkpoint_age: u64,
pub fallback: Option<String>,
pub load_external_fallback: bool,
pub strict_checkpoint_age: bool,
pub with_ws: bool,
pub with_http: bool,
}
@ -87,7 +88,7 @@ impl Config {
BaseConfig {
rpc_port: self.rpc_port.unwrap_or(8545),
consensus_rpc: Some(self.consensus_rpc.clone()),
checkpoint: self.checkpoint.clone(),
default_checkpoint: self.default_checkpoint.clone(),
chain: self.chain.clone(),
forks: self.forks.clone(),
max_checkpoint_age: self.max_checkpoint_age,

View File

@ -35,8 +35,8 @@ impl Network {
pub fn mainnet() -> BaseConfig {
BaseConfig {
checkpoint: hex_str_to_bytes(
"0x428ce0b5f5bbed1fc2b3feb5d4152ae0fe98a80b1bfa8de36681868e81e9222a",
default_checkpoint: hex_str_to_bytes(
"0x766647f3c4e1fc91c0db9a9374032ae038778411fbff222974e11f2e3ce7dadf",
)
.unwrap(),
rpc_port: 8545,
@ -69,7 +69,7 @@ pub fn mainnet() -> BaseConfig {
pub fn goerli() -> BaseConfig {
BaseConfig {
checkpoint: hex_str_to_bytes(
default_checkpoint: hex_str_to_bytes(
"0xd4344682866dbede543395ecf5adf9443a27f423a4b00f270458e7932686ced1",
)
.unwrap(),

View File

@ -15,3 +15,15 @@ where
let bytes_string = hex::encode(bytes);
serializer.serialize_str(&bytes_string)
}
pub fn bytes_opt_deserialize<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let bytes_opt: Option<String> = serde::Deserialize::deserialize(deserializer)?;
if let Some(bytes) = bytes_opt {
Ok(Some(hex_str_to_bytes(&bytes).unwrap()))
} else {
Ok(None)
}
}

View File

@ -1,27 +1,32 @@
[package]
name = "consensus"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
eyre = "0.6.8"
futures = "0.3.23"
serde = { version = "1.0.143", features = ["derive"] }
serde_json = "1.0.85"
hex = "0.4.3"
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "cb08f18ca919cc1b685b861d0fa9e2daabe89737" }
blst = "0.3.10"
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "d09f55b4f8554491e3431e01af1c32347a8781cd" }
milagro_bls = { git = "https://github.com/Snowfork/milagro_bls" }
ethers = { version = "1.0.2", features = [ "ws", "default" ] }
bytes = "1.2.1"
toml = "0.5.9"
async-trait = "0.1.57"
log = "0.4.17"
chrono = "0.4.22"
chrono = "0.4.23"
thiserror = "1.0.37"
openssl = { version = "0.10", features = ["vendored"] }
reqwest = { version = "0.11.12", features = ["json"] }
reqwest-middleware = "0.1.6"
reqwest-retry = "0.1.5"
reqwest = { version = "0.11.13", features = ["json"] }
common = { path = "../common" }
config = { path = "../config" }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
tokio = { version = "1", features = ["full"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-timer = "0.2.5"

View File

@ -1,12 +1,13 @@
use std::cmp;
use std::sync::Arc;
use std::time::UNIX_EPOCH;
use blst::min_pk::PublicKey;
use chrono::Duration;
use eyre::eyre;
use eyre::Result;
use futures::future::join_all;
use log::warn;
use log::{debug, info};
use milagro_bls::PublicKey;
use ssz_rs::prelude::*;
use common::types::*;
@ -20,9 +21,20 @@ use super::rpc::ConsensusRpc;
use super::types::*;
use super::utils::*;
#[cfg(not(target_arch = "wasm32"))]
use std::time::SystemTime;
#[cfg(not(target_arch = "wasm32"))]
use std::time::UNIX_EPOCH;
#[cfg(target_arch = "wasm32")]
use wasm_timer::SystemTime;
#[cfg(target_arch = "wasm32")]
use wasm_timer::UNIX_EPOCH;
// https://github.com/ethereum/consensus-specs/blob/dev/specs/altair/light-client/sync-protocol.md
// does not implement force updates
#[derive(Debug)]
pub struct ConsensusClient<R: ConsensusRpc> {
rpc: R,
store: LightClientStore,
@ -58,6 +70,16 @@ impl<R: ConsensusRpc> ConsensusClient<R> {
})
}
pub async fn check_rpc(&self) -> Result<()> {
let chain_id = self.rpc.chain_id().await?;
if chain_id != self.config.chain.chain_id {
Err(ConsensusError::IncorrectRpcNetwork.into())
} else {
Ok(())
}
}
pub async fn get_execution_payload(&self, slot: &Option<u64>) -> Result<ExecutionPayload> {
let slot = slot.unwrap_or(self.store.optimistic_header.slot);
let mut block = self.rpc.get_block(slot).await?;
@ -85,6 +107,43 @@ impl<R: ConsensusRpc> ConsensusClient<R> {
}
}
pub async fn get_payloads(
&self,
start_slot: u64,
end_slot: u64,
) -> Result<Vec<ExecutionPayload>> {
let payloads_fut = (start_slot..end_slot)
.rev()
.map(|slot| self.rpc.get_block(slot));
let mut prev_parent_hash: Bytes32 = self
.rpc
.get_block(end_slot)
.await?
.body
.execution_payload
.parent_hash;
let mut payloads: Vec<ExecutionPayload> = Vec::new();
for result in join_all(payloads_fut).await {
if result.is_err() {
continue;
}
let payload = result.unwrap().body.execution_payload;
if payload.block_hash != prev_parent_hash {
warn!(
"error while backfilling blocks: {}",
ConsensusError::InvalidHeaderHash(
format!("{prev_parent_hash:02X?}"),
format!("{:02X?}", payload.parent_hash),
)
);
break;
}
prev_parent_hash = payload.parent_hash.clone();
payloads.push(payload);
}
Ok(payloads)
}
pub fn get_header(&self) -> &Header {
&self.store.optimistic_header
}
@ -94,10 +153,6 @@ impl<R: ConsensusRpc> ConsensusClient<R> {
}
pub async fn sync(&mut self) -> Result<()> {
info!(
"Consensus client in sync with checkpoint: 0x{}",
hex::encode(&self.initial_checkpoint)
);
self.bootstrap().await?;
let current_period = calc_sync_period(self.store.finalized_header.slot);
@ -119,6 +174,11 @@ impl<R: ConsensusRpc> ConsensusClient<R> {
self.verify_optimistic_update(&optimistic_update)?;
self.apply_optimistic_update(&optimistic_update);
info!(
"consensus client in sync with checkpoint: 0x{}",
hex::encode(&self.initial_checkpoint)
);
Ok(())
}
@ -158,8 +218,13 @@ impl<R: ConsensusRpc> ConsensusClient<R> {
.map_err(|_| eyre!("could not fetch bootstrap"))?;
let is_valid = self.is_valid_checkpoint(bootstrap.header.slot);
if !is_valid {
return Err(ConsensusError::CheckpointTooOld.into());
if self.config.strict_checkpoint_age {
return Err(ConsensusError::CheckpointTooOld.into());
} else {
warn!("checkpoint too old, consider using a more recent block");
}
}
let committee_valid = is_current_committee_proof_valid(
@ -463,18 +528,13 @@ impl<R: ConsensusRpc> ConsensusClient<R> {
fn age(&self, slot: u64) -> Duration {
let expected_time = self.slot_timestamp(slot);
let now = std::time::SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap();
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let delay = now - std::time::Duration::from_secs(expected_time);
chrono::Duration::from_std(delay).unwrap()
}
pub fn expected_current_slot(&self) -> u64 {
let now = std::time::SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap();
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let genesis_time = self.config.chain.genesis_time;
let since_genesis = now - std::time::Duration::from_secs(genesis_time);
@ -492,7 +552,7 @@ impl<R: ConsensusRpc> ConsensusClient<R> {
let next_slot = current_slot + 1;
let next_slot_timestamp = self.slot_timestamp(next_slot);
let now = std::time::SystemTime::now()
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
@ -523,7 +583,7 @@ fn get_participating_keys(
bitfield.iter().enumerate().for_each(|(i, bit)| {
if bit == true {
let pk = &committee.pubkeys[i];
let pk = PublicKey::from_bytes(pk).unwrap();
let pk = PublicKey::from_bytes_unchecked(pk).unwrap();
pks.push(pk);
}
});
@ -594,14 +654,14 @@ mod tests {
};
use config::{networks, Config};
async fn get_client(large_checkpoint_age: bool) -> ConsensusClient<MockRpc> {
async fn get_client(strict_checkpoint_age: bool) -> ConsensusClient<MockRpc> {
let base_config = networks::goerli();
let config = Config {
consensus_rpc: String::new(),
execution_rpc: String::new(),
chain: base_config.chain,
forks: base_config.forks,
max_checkpoint_age: if large_checkpoint_age { 123123123 } else { 123 },
strict_checkpoint_age,
..Default::default()
};
@ -616,7 +676,7 @@ mod tests {
#[tokio::test]
async fn test_verify_update() {
let client = get_client(true).await;
let client = get_client(false).await;
let period = calc_sync_period(client.store.finalized_header.slot);
let updates = client
.rpc
@ -630,7 +690,7 @@ mod tests {
#[tokio::test]
async fn test_verify_update_invalid_committee() {
let client = get_client(true).await;
let client = get_client(false).await;
let period = calc_sync_period(client.store.finalized_header.slot);
let updates = client
.rpc
@ -650,7 +710,7 @@ mod tests {
#[tokio::test]
async fn test_verify_update_invalid_finality() {
let client = get_client(true).await;
let client = get_client(false).await;
let period = calc_sync_period(client.store.finalized_header.slot);
let updates = client
.rpc
@ -670,7 +730,7 @@ mod tests {
#[tokio::test]
async fn test_verify_update_invalid_sig() {
let client = get_client(true).await;
let client = get_client(false).await;
let period = calc_sync_period(client.store.finalized_header.slot);
let updates = client
.rpc
@ -690,7 +750,7 @@ mod tests {
#[tokio::test]
async fn test_verify_finality() {
let mut client = get_client(true).await;
let mut client = get_client(false).await;
client.sync().await.unwrap();
let update = client.rpc.get_finality_update().await.unwrap();
@ -700,7 +760,7 @@ mod tests {
#[tokio::test]
async fn test_verify_finality_invalid_finality() {
let mut client = get_client(true).await;
let mut client = get_client(false).await;
client.sync().await.unwrap();
let mut update = client.rpc.get_finality_update().await.unwrap();
@ -715,7 +775,7 @@ mod tests {
#[tokio::test]
async fn test_verify_finality_invalid_sig() {
let mut client = get_client(true).await;
let mut client = get_client(false).await;
client.sync().await.unwrap();
let mut update = client.rpc.get_finality_update().await.unwrap();
@ -730,7 +790,7 @@ mod tests {
#[tokio::test]
async fn test_verify_optimistic() {
let mut client = get_client(true).await;
let mut client = get_client(false).await;
client.sync().await.unwrap();
let update = client.rpc.get_optimistic_update().await.unwrap();
@ -739,7 +799,7 @@ mod tests {
#[tokio::test]
async fn test_verify_optimistic_invalid_sig() {
let mut client = get_client(true).await;
let mut client = get_client(false).await;
client.sync().await.unwrap();
let mut update = client.rpc.get_optimistic_update().await.unwrap();
@ -755,6 +815,6 @@ mod tests {
#[tokio::test]
#[should_panic]
async fn test_verify_checkpoint_age_invalid() {
get_client(false).await;
get_client(true).await;
}
}

View File

@ -24,4 +24,6 @@ pub enum ConsensusError {
PayloadNotFound(u64),
#[error("checkpoint is too old")]
CheckpointTooOld,
#[error("consensus rpc is for the incorrect network")]
IncorrectRpcNetwork,
}

View File

@ -1,16 +1,15 @@
use std::{fs::read_to_string, path::PathBuf};
use async_trait::async_trait;
use eyre::Result;
use super::ConsensusRpc;
use crate::types::{BeaconBlock, Bootstrap, FinalityUpdate, OptimisticUpdate, Update};
use async_trait::async_trait;
use eyre::Result;
pub struct MockRpc {
testdata: PathBuf,
}
#[async_trait]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl ConsensusRpc for MockRpc {
fn new(path: &str) -> Self {
MockRpc {
@ -42,4 +41,8 @@ impl ConsensusRpc for MockRpc {
let block = read_to_string(self.testdata.join("blocks.json"))?;
Ok(serde_json::from_str(&block)?)
}
async fn chain_id(&self) -> Result<u64> {
eyre::bail!("not implemented")
}
}

View File

@ -7,7 +7,8 @@ use eyre::Result;
use crate::types::{BeaconBlock, Bootstrap, FinalityUpdate, OptimisticUpdate, Update};
// implements https://github.com/ethereum/beacon-APIs/tree/master/apis/beacon/light_client
#[async_trait]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait ConsensusRpc {
fn new(path: &str) -> Self;
async fn get_bootstrap(&self, block_root: &'_ [u8]) -> Result<Bootstrap>;
@ -15,4 +16,5 @@ pub trait ConsensusRpc {
async fn get_finality_update(&self) -> Result<FinalityUpdate>;
async fn get_optimistic_update(&self) -> Result<OptimisticUpdate>;
async fn get_block(&self, slot: u64) -> Result<BeaconBlock>;
async fn chain_id(&self) -> Result<u64>;
}

View File

@ -1,33 +1,23 @@
use async_trait::async_trait;
use common::errors::RpcError;
use eyre::Result;
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
use std::cmp;
use super::ConsensusRpc;
use crate::constants::MAX_REQUEST_LIGHT_CLIENT_UPDATES;
use crate::types::*;
use common::errors::RpcError;
#[derive(Debug)]
pub struct NimbusRpc {
rpc: String,
client: ClientWithMiddleware,
}
#[async_trait]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl ConsensusRpc for NimbusRpc {
fn new(rpc: &str) -> Self {
let retry_policy = ExponentialBackoff::builder()
.backoff_exponent(1)
.build_with_max_retries(3);
let client = ClientBuilder::new(reqwest::Client::new())
.with(RetryTransientMiddleware::new_with_policy(retry_policy))
.build();
NimbusRpc {
rpc: rpc.to_string(),
client,
}
}
@ -38,8 +28,8 @@ impl ConsensusRpc for NimbusRpc {
self.rpc, root_hex
);
let res = self
.client
let client = reqwest::Client::new();
let res = client
.get(req)
.send()
.await
@ -58,8 +48,8 @@ impl ConsensusRpc for NimbusRpc {
self.rpc, period, count
);
let res = self
.client
let client = reqwest::Client::new();
let res = client
.get(req)
.send()
.await
@ -73,10 +63,7 @@ impl ConsensusRpc for NimbusRpc {
async fn get_finality_update(&self) -> Result<FinalityUpdate> {
let req = format!("{}/eth/v1/beacon/light_client/finality_update", self.rpc);
let res = self
.client
.get(req)
.send()
let res = reqwest::get(req)
.await
.map_err(|e| RpcError::new("finality_update", e))?
.json::<FinalityUpdateResponse>()
@ -88,10 +75,7 @@ impl ConsensusRpc for NimbusRpc {
async fn get_optimistic_update(&self) -> Result<OptimisticUpdate> {
let req = format!("{}/eth/v1/beacon/light_client/optimistic_update", self.rpc);
let res = self
.client
.get(req)
.send()
let res = reqwest::get(req)
.await
.map_err(|e| RpcError::new("optimistic_update", e))?
.json::<OptimisticUpdateResponse>()
@ -103,10 +87,7 @@ impl ConsensusRpc for NimbusRpc {
async fn get_block(&self, slot: u64) -> Result<BeaconBlock> {
let req = format!("{}/eth/v2/beacon/blocks/{}", self.rpc, slot);
let res = self
.client
.get(req)
.send()
let res = reqwest::get(req)
.await
.map_err(|e| RpcError::new("blocks", e))?
.json::<BeaconBlockResponse>()
@ -115,6 +96,18 @@ impl ConsensusRpc for NimbusRpc {
Ok(res.data.message)
}
async fn chain_id(&self) -> Result<u64> {
let req = format!("{}/eth/v1/config/spec", self.rpc);
let res = reqwest::get(req)
.await
.map_err(|e| RpcError::new("spec", e))?
.json::<SpecResponse>()
.await
.map_err(|e| RpcError::new("spec", e))?;
Ok(res.data.chain_id)
}
}
#[derive(serde::Deserialize, Debug)]
@ -148,3 +141,14 @@ struct OptimisticUpdateResponse {
struct BootstrapResponse {
data: Bootstrap,
}
#[derive(serde::Deserialize, Debug)]
struct SpecResponse {
data: Spec,
}
#[derive(serde::Deserialize, Debug)]
struct Spec {
#[serde(rename = "DEPOSIT_NETWORK_ID", deserialize_with = "u64_deserialize")]
chain_id: u64,
}

View File

@ -188,6 +188,7 @@ pub struct Eth1Data {
#[derive(serde::Deserialize, Debug)]
pub struct Bootstrap {
#[serde(deserialize_with = "header_deserialize")]
pub header: Header,
pub current_sync_committee: SyncCommittee,
#[serde(deserialize_with = "branch_deserialize")]
@ -196,10 +197,12 @@ pub struct Bootstrap {
#[derive(serde::Deserialize, Debug, Clone)]
pub struct Update {
#[serde(deserialize_with = "header_deserialize")]
pub attested_header: Header,
pub next_sync_committee: SyncCommittee,
#[serde(deserialize_with = "branch_deserialize")]
pub next_sync_committee_branch: Vec<Bytes32>,
#[serde(deserialize_with = "header_deserialize")]
pub finalized_header: Header,
#[serde(deserialize_with = "branch_deserialize")]
pub finality_branch: Vec<Bytes32>,
@ -210,7 +213,9 @@ pub struct Update {
#[derive(serde::Deserialize, Debug)]
pub struct FinalityUpdate {
#[serde(deserialize_with = "header_deserialize")]
pub attested_header: Header,
#[serde(deserialize_with = "header_deserialize")]
pub finalized_header: Header,
#[serde(deserialize_with = "branch_deserialize")]
pub finality_branch: Vec<Bytes32>,
@ -221,6 +226,7 @@ pub struct FinalityUpdate {
#[derive(serde::Deserialize, Debug)]
pub struct OptimisticUpdate {
#[serde(deserialize_with = "header_deserialize")]
pub attested_header: Header,
pub sync_aggregate: SyncAggregate,
#[serde(deserialize_with = "u64_deserialize")]
@ -370,7 +376,7 @@ where
.map_err(D::Error::custom)
}
fn u64_deserialize<'de, D>(deserializer: D) -> Result<u64, D::Error>
pub fn u64_deserialize<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
D: serde::Deserializer<'de>,
{
@ -453,3 +459,27 @@ where
Ok(attesting_indices)
}
fn header_deserialize<'de, D>(deserializer: D) -> Result<Header, D::Error>
where
D: serde::Deserializer<'de>,
{
let header: LightClientHeader = serde::Deserialize::deserialize(deserializer)?;
Ok(match header {
LightClientHeader::Unwrapped(header) => header,
LightClientHeader::Wrapped(header) => header.beacon,
})
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum LightClientHeader {
Unwrapped(Header),
Wrapped(Beacon),
}
#[derive(serde::Deserialize)]
struct Beacon {
beacon: Header,
}

View File

@ -1,9 +1,6 @@
use blst::{
min_pk::{PublicKey, Signature},
BLST_ERROR,
};
use common::{types::Bytes32, utils::bytes32_to_node};
use eyre::Result;
use milagro_bls::{AggregateSignature, PublicKey};
use ssz_rs::prelude::*;
use crate::types::{Header, SignatureBytes};
@ -14,10 +11,9 @@ pub fn calc_sync_period(slot: u64) -> u64 {
}
pub fn is_aggregate_valid(sig_bytes: &SignatureBytes, msg: &[u8], pks: &[&PublicKey]) -> bool {
let dst: &[u8] = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";
let sig_res = Signature::from_bytes(sig_bytes);
let sig_res = AggregateSignature::from_bytes(sig_bytes);
match sig_res {
Ok(sig) => sig.fast_aggregate_verify(true, msg, dst, pks) == BLST_ERROR::BLST_SUCCESS,
Ok(sig) => sig.fast_aggregate_verify(msg, pks),
Err(_) => false,
}
}

45
examples/basic.rs Normal file
View File

@ -0,0 +1,45 @@
use std::{path::PathBuf, str::FromStr};
use env_logger::Env;
use ethers::{types::Address, utils};
use eyre::Result;
use helios::{config::networks::Network, prelude::*};
#[tokio::main]
async fn main() -> Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
let untrusted_rpc_url = "https://eth-mainnet.g.alchemy.com/v2/<YOUR_API_KEY>";
log::info!("Using untrusted RPC URL [REDACTED]");
let consensus_rpc = "https://www.lightclientdata.org";
log::info!("Using consensus RPC URL: {}", consensus_rpc);
let mut client: Client<FileDB> = ClientBuilder::new()
.network(Network::MAINNET)
.consensus_rpc(consensus_rpc)
.execution_rpc(untrusted_rpc_url)
.load_external_fallback()
.data_dir(PathBuf::from("/tmp/helios"))
.build()?;
log::info!(
"Built client on network \"{}\" with external checkpoint fallbacks",
Network::MAINNET
);
client.start().await?;
let head_block_num = client.get_block_number().await?;
let addr = Address::from_str("0x00000000219ab540356cBB839Cbe05303d7705Fa")?;
let block = BlockTag::Latest;
let balance = client.get_balance(&addr, block).await?;
log::info!("synced up to block: {}", head_block_num);
log::info!(
"balance of deposit contract: {}",
utils::format_ether(balance)
);
Ok(())
}

93
examples/call.rs Normal file
View File

@ -0,0 +1,93 @@
#![allow(deprecated)]
use env_logger::Env;
use ethers::prelude::*;
use std::{path::PathBuf, sync::Arc};
use helios::{
client::{Client, ClientBuilder, FileDB},
config::networks::Network,
types::{BlockTag, CallOpts},
};
// Generate the type-safe contract bindings with an ABI
abigen!(
Renderer,
r#"[
function renderBroker(uint256) external view returns (string memory)
function renderBroker(uint256, uint256) external view returns (string memory)
]"#,
event_derives(serde::Deserialize, serde::Serialize)
);
#[tokio::main]
async fn main() -> eyre::Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("debug")).init();
// Load the rpc url using the `MAINNET_RPC_URL` environment variable
let eth_rpc_url = std::env::var("MAINNET_RPC_URL")?;
let consensus_rpc = "https://www.lightclientdata.org";
log::info!("Consensus RPC URL: {}", consensus_rpc);
// Construct the client
let data_dir = PathBuf::from("/tmp/helios");
let mut client: Client<FileDB> = ClientBuilder::new()
.network(Network::MAINNET)
.data_dir(data_dir)
.consensus_rpc(consensus_rpc)
.execution_rpc(&eth_rpc_url)
.load_external_fallback()
.build()?;
log::info!(
"[\"{}\"] Client built with external checkpoint fallbacks",
Network::MAINNET
);
// Start the client
client.start().await?;
// Call the erroneous account method
// The expected asset is: https://0x8bb9a8baeec177ae55ac410c429cbbbbb9198cac.w3eth.io/renderBroker/5
// Retrieved by calling `renderBroker(5)` on the contract: https://etherscan.io/address/0x8bb9a8baeec177ae55ac410c429cbbbbb9198cac#code
let account = "0x8bb9a8baeec177ae55ac410c429cbbbbb9198cac";
let method = "renderBroker(uint256)";
let method2 = "renderBroker(uint256, uint256)";
let argument = U256::from(5);
let address = account.parse::<Address>()?;
let block = BlockTag::Latest;
let provider = Provider::<Http>::try_from(eth_rpc_url)?;
let render = Renderer::new(address, Arc::new(provider.clone()));
log::debug!("Context: call @ {account}::{method} <{argument}>");
// Call using abigen
let result = render.render_broker_0(argument).call().await?;
log::info!(
"[ABIGEN] {account}::{method} -> Response Length: {:?}",
result.len()
);
let render = Renderer::new(address, Arc::new(provider.clone()));
let result = render
.render_broker_1(argument, U256::from(10))
.call()
.await?;
log::info!(
"[ABIGEN] {account}::{method2} -> Response Length: {:?}",
result.len()
);
// Call on helios client
let encoded_call = render.render_broker_0(argument).calldata().unwrap();
let call_opts = CallOpts {
from: Some("0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8".parse::<Address>()?),
to: Some(address),
gas: Some(U256::from(U64::MAX.as_u64())),
gas_price: None,
value: None,
data: Some(encoded_call.to_vec()),
};
log::debug!("Calling helios client on block: {block:?}");
let result = client.call(&call_opts, block).await?;
log::info!("[HELIOS] {account}::{method} ->{:?}", result.len());
Ok(())
}

View File

@ -35,7 +35,7 @@ async fn main() -> Result<()> {
builder = builder.load_external_fallback();
// Build the client
let _client = builder.build().unwrap();
let _client: Client<FileDB> = builder.build().unwrap();
println!("Constructed client!");
Ok(())

View File

@ -1,4 +1,5 @@
use config::CliConfig;
use dirs::home_dir;
use eyre::Result;
use helios::prelude::*;
@ -6,7 +7,7 @@ use helios::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
// Load the config from the global config file
let config_path = home::home_dir().unwrap().join(".helios/helios.toml");
let config_path = home_dir().unwrap().join(".helios/helios.toml");
let config = Config::from_file(&config_path, "mainnet", &CliConfig::default());
println!("Constructed config: {config:#?}");

View File

@ -1,18 +1,17 @@
[package]
name = "execution"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
eyre = "0.6.8"
serde = { version = "1.0.143", features = ["derive"] }
serde_json = "1.0.85"
hex = "0.4.3"
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "cb08f18ca919cc1b685b861d0fa9e2daabe89737" }
ssz-rs = { git = "https://github.com/ralexstokes/ssz-rs", rev = "d09f55b4f8554491e3431e01af1c32347a8781cd" }
ethers = { version = "1.0.2", features = [ "ws", "default" ] }
revm = "2.1.0"
revm = { version = "2.3", default-features = false, features = ["std", "k256", "with-serde"] }
bytes = "1.2.1"
futures = "0.3.23"
toml = "0.5.9"
@ -20,7 +19,10 @@ triehash-ethereum = { git = "https://github.com/openethereum/parity-ethereum", r
async-trait = "0.1.57"
log = "0.4.17"
thiserror = "1.0.37"
openssl = { version = "0.10", features = ["vendored"] }
common = { path = "../common" }
consensus = { path = "../consensus" }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
tokio = { version = "1", features = ["full"] }

View File

@ -24,6 +24,18 @@ pub enum ExecutionError {
MissingLog(String, U256),
#[error("too many logs to prove: {0}, current limit is: {1}")]
TooManyLogsToProve(usize, usize),
#[error("execution rpc is for the incorect network")]
IncorrectRpcNetwork(),
#[error("Invalid base gas fee helios {0} vs rpc endpoint {1} at block {2}")]
InvalidBaseGaseFee(U256, U256, u64),
#[error("Invalid gas used ratio of helios {0} vs rpc endpoint {1} at block {2}")]
InvalidGasUsedRatio(f64, f64, u64),
#[error("Block {0} not found")]
BlockNotFoundError(u64),
#[error("Helios Execution Payload is empty")]
EmptyExecutionPayload(),
#[error("User query for block {0} but helios oldest block is {1}")]
InvalidBlockRange(u64, u64),
}
/// Errors that can occur during evm.rs calls

View File

@ -6,17 +6,19 @@ use std::{
};
use bytes::Bytes;
use common::{errors::BlockNotFoundError, types::BlockTag};
use common::{
errors::{BlockNotFoundError, SlotNotFoundError},
types::BlockTag,
};
use ethers::{
abi::ethereum_types::BigEndianHash,
prelude::{Address, H160, H256, U256},
types::transaction::eip2930::AccessListItem,
types::{Address, H160, H256, U256},
};
use eyre::{Report, Result};
use futures::future::join_all;
use futures::{executor::block_on, future::join_all};
use log::trace;
use revm::{AccountInfo, Bytecode, Database, Env, TransactOut, TransactTo, EVM};
use tokio::runtime::Runtime;
use consensus::types::ExecutionPayload;
@ -60,7 +62,7 @@ impl<'a, R: ExecutionRpc> Evm<'a, R> {
TransactOut::Call(bytes) => Err(EvmError::Revert(Some(bytes))),
_ => Err(EvmError::Revert(None)),
},
revm::Return::Return => {
revm::Return::Return | revm::Return::Stop => {
if let Some(err) = &self.evm.db.as_ref().unwrap().error {
return Err(EvmError::Generic(err.clone()));
}
@ -88,7 +90,7 @@ impl<'a, R: ExecutionRpc> Evm<'a, R> {
TransactOut::Call(bytes) => Err(EvmError::Revert(Some(bytes))),
_ => Err(EvmError::Revert(None)),
},
revm::Return::Return => {
revm::Return::Return | revm::Return::Stop => {
if let Some(err) = &self.evm.db.as_ref().unwrap().error {
return Err(EvmError::Generic(err.clone()));
}
@ -132,7 +134,7 @@ impl<'a, R: ExecutionRpc> Evm<'a, R> {
};
let to_access_entry = AccessListItem {
address: opts_moved.to,
address: opts_moved.to.unwrap_or_default(),
storage_keys: Vec::default(),
};
@ -173,10 +175,10 @@ impl<'a, R: ExecutionRpc> Evm<'a, R> {
let mut env = Env::default();
let payload = &self.evm.db.as_ref().unwrap().current_payload;
env.tx.transact_to = TransactTo::Call(opts.to);
env.tx.transact_to = TransactTo::Call(opts.to.unwrap_or_default());
env.tx.caller = opts.from.unwrap_or(Address::zero());
env.tx.value = opts.value.unwrap_or(U256::from(0));
env.tx.data = Bytes::from(opts.data.clone().unwrap_or(vec![]));
env.tx.data = Bytes::from(opts.data.clone().unwrap_or_default());
env.tx.gas_limit = opts.gas.map(|v| v.as_u64()).unwrap_or(u64::MAX);
env.tx.gas_price = opts.gas_price.unwrap_or(U256::zero());
@ -225,8 +227,7 @@ impl<'a, R: ExecutionRpc> ProofDB<'a, R> {
let handle = thread::spawn(move || {
let account_fut = execution.get_account(&address, Some(&slots), &payload);
let runtime = Runtime::new()?;
runtime.block_on(account_fut)
block_on(account_fut)
});
handle.join().unwrap()
@ -242,7 +243,7 @@ impl<'a, R: ExecutionRpc> Database for ProofDB<'a, R> {
}
trace!(
"fetch basic evm state for addess=0x{}",
"fetch basic evm state for address=0x{}",
hex::encode(address.as_bytes())
);
@ -269,11 +270,7 @@ impl<'a, R: ExecutionRpc> Database for ProofDB<'a, R> {
}
fn storage(&mut self, address: H160, slot: U256) -> Result<U256, Report> {
trace!(
"fetch evm state for address=0x{}, slot={}",
hex::encode(address.as_bytes()),
slot
);
trace!("fetch evm state for address={:?}, slot={}", address, slot);
let slot = H256::from_uint(&slot);
@ -284,13 +281,13 @@ impl<'a, R: ExecutionRpc> Database for ProofDB<'a, R> {
.get_account(address, &[slot])?
.slots
.get(&slot)
.unwrap(),
.ok_or(SlotNotFoundError::new(slot))?,
},
None => *self
.get_account(address, &[slot])?
.slots
.get(&slot)
.unwrap(),
.ok_or(SlotNotFoundError::new(slot))?,
})
}
@ -303,3 +300,59 @@ fn is_precompile(address: &Address) -> bool {
address.le(&Address::from_str("0x0000000000000000000000000000000000000009").unwrap())
&& address.gt(&Address::zero())
}
#[cfg(test)]
mod tests {
use common::utils::hex_str_to_bytes;
use ssz_rs::Vector;
use crate::rpc::mock_rpc::MockRpc;
use super::*;
fn get_client() -> ExecutionClient<MockRpc> {
ExecutionClient::new("testdata/").unwrap()
}
#[test]
fn test_proof_db() {
// Construct proofdb params
let execution = get_client();
let address = Address::from_str("14f9D4aF749609c1438528C0Cce1cC3f6D411c47").unwrap();
let payload = ExecutionPayload {
state_root: Vector::from_iter(
hex_str_to_bytes(
"0xaa02f5db2ee75e3da400d10f3c30e894b6016ce8a2501680380a907b6674ce0d",
)
.unwrap(),
),
..ExecutionPayload::default()
};
let mut payloads = BTreeMap::new();
payloads.insert(7530933, payload.clone());
// Construct the proof database with the given client and payloads
let mut proof_db = ProofDB::new(Arc::new(execution), &payload, &payloads);
// Set the proof db accounts
let slot = U256::from(1337);
let mut accounts = HashMap::new();
let account = Account {
balance: U256::from(100),
code: hex_str_to_bytes("0x").unwrap(),
..Default::default()
};
accounts.insert(address, account);
proof_db.set_accounts(accounts);
// Get the account from the proof database
let storage_proof = proof_db.storage(address, slot);
// Check that the storage proof correctly returns a slot not found error
let expected_err: eyre::Report = SlotNotFoundError::new(H256::from_uint(&slot)).into();
assert_eq!(
expected_err.to_string(),
storage_proof.unwrap_err().to_string()
);
}
}

View File

@ -3,7 +3,7 @@ use std::str::FromStr;
use ethers::abi::AbiEncode;
use ethers::prelude::{Address, U256};
use ethers::types::{Filter, Log, Transaction, TransactionReceipt, H256};
use ethers::types::{FeeHistory, Filter, Log, Transaction, TransactionReceipt, H256};
use ethers::utils::keccak256;
use ethers::utils::rlp::{encode, Encodable, RlpStream};
use eyre::Result;
@ -40,10 +40,18 @@ impl ExecutionClient<WsRpc> {
impl<R: ExecutionRpc> ExecutionClient<R> {
pub fn new(rpc: &str) -> Result<Self> {
let rpc = ExecutionRpc::new(rpc)?;
let rpc: R = ExecutionRpc::new(rpc)?;
Ok(ExecutionClient { rpc })
}
pub async fn check_rpc(&self, chain_id: u64) -> Result<()> {
if self.rpc.chain_id().await? != chain_id {
Err(ExecutionError::IncorrectRpcNetwork().into())
} else {
Ok(())
}
}
pub async fn get_account(
&self,
address: &Address,
@ -187,6 +195,21 @@ impl<R: ExecutionRpc> ExecutionClient<R> {
})
}
pub async fn get_transaction_by_block_hash_and_index(
&self,
payload: &ExecutionPayload,
index: usize,
) -> Result<Option<Transaction>> {
let tx = payload.transactions[index].clone();
let tx_hash = H256::from_slice(&keccak256(tx));
let mut payloads = BTreeMap::new();
payloads.insert(payload.block_number, payload.clone());
let tx_option = self.get_transaction(&tx_hash, &payloads).await?;
let tx = tx_option.ok_or(eyre::eyre!("not reachable"))?;
Ok(Some(tx))
}
pub async fn get_transaction_receipt(
&self,
tx_hash: &H256,
@ -268,7 +291,6 @@ impl<R: ExecutionRpc> ExecutionClient<R> {
if !txs_encoded.contains(&tx_encoded) {
return Err(ExecutionError::MissingTransaction(hash.to_string()).into());
}
Ok(Some(tx))
}
@ -277,7 +299,22 @@ impl<R: ExecutionRpc> ExecutionClient<R> {
filter: &Filter,
payloads: &BTreeMap<u64, ExecutionPayload>,
) -> Result<Vec<Log>> {
let logs = self.rpc.get_logs(filter).await?;
let filter = filter.clone();
// avoid fetching logs for a block helios hasn't seen yet
let filter = if filter.get_to_block().is_none() && filter.get_block_hash().is_none() {
let block = *payloads.last_key_value().unwrap().0;
let filter = filter.to_block(block);
if filter.get_from_block().is_none() {
filter.from_block(block)
} else {
filter
}
} else {
filter
};
let logs = self.rpc.get_logs(&filter).await?;
if logs.len() > MAX_SUPPORTED_LOGS_NUMBER {
return Err(
ExecutionError::TooManyLogsToProve(logs.len(), MAX_SUPPORTED_LOGS_NUMBER).into(),
@ -316,6 +353,130 @@ impl<R: ExecutionRpc> ExecutionClient<R> {
}
Ok(logs)
}
pub async fn get_fee_history(
&self,
block_count: u64,
last_block: u64,
_reward_percentiles: &[f64],
payloads: &BTreeMap<u64, ExecutionPayload>,
) -> Result<Option<FeeHistory>> {
// Extract the latest and oldest block numbers from the payloads
let helios_latest_block_number = *payloads
.last_key_value()
.ok_or(ExecutionError::EmptyExecutionPayload())?
.0;
let helios_oldest_block_number = *payloads
.first_key_value()
.ok_or(ExecutionError::EmptyExecutionPayload())?
.0;
// Case where all requested blocks are earlier than Helios' latest block number
// So helios can't prove anything in this range
if last_block < helios_oldest_block_number {
return Err(
ExecutionError::InvalidBlockRange(last_block, helios_latest_block_number).into(),
);
}
// If the requested block is more recent than helios' latest block
// we can only return up to helios' latest block
let mut request_latest_block = last_block;
if request_latest_block > helios_latest_block_number {
request_latest_block = helios_latest_block_number;
}
// Requested oldest block is further out than what helios' synced
let mut request_oldest_block = request_latest_block - block_count;
if request_oldest_block < helios_oldest_block_number {
request_oldest_block = helios_oldest_block_number;
}
// Construct a fee history
let mut fee_history = FeeHistory {
oldest_block: U256::from(request_oldest_block),
base_fee_per_gas: vec![],
gas_used_ratio: vec![],
reward: payloads.iter().map(|_| vec![]).collect::<Vec<Vec<U256>>>(),
};
for block_id in request_oldest_block..=request_latest_block {
let execution_payload = payloads
.get(&block_id)
.ok_or(ExecutionError::EmptyExecutionPayload())?;
let converted_base_fee_per_gas = ethers::types::U256::from_little_endian(
&execution_payload.base_fee_per_gas.to_bytes_le(),
);
fee_history
.base_fee_per_gas
.push(converted_base_fee_per_gas);
let gas_used_ratio_helios = ((execution_payload.gas_used as f64
/ execution_payload.gas_limit as f64)
* 10.0_f64.powi(12))
.round()
/ 10.0_f64.powi(12);
fee_history.gas_used_ratio.push(gas_used_ratio_helios);
}
// TODO: Maybe place behind a query option param?
// Optionally verify the computed fee history using the rpc
// verify_fee_history(
// &self.rpc,
// &fee_history,
// fee_history.base_fee_per_gas.len(),
// request_latest_block,
// reward_percentiles,
// ).await?;
Ok(Some(fee_history))
}
}
/// Verifies a fee history against an rpc.
pub async fn verify_fee_history(
rpc: &impl ExecutionRpc,
calculated_fee_history: &FeeHistory,
block_count: u64,
request_latest_block: u64,
reward_percentiles: &[f64],
) -> Result<()> {
let fee_history = rpc
.get_fee_history(block_count, request_latest_block, reward_percentiles)
.await?;
for (_pos, _base_fee_per_gas) in fee_history.base_fee_per_gas.iter().enumerate() {
// Break at last iteration
// Otherwise, this would add an additional block
if _pos == block_count as usize {
continue;
}
// Check base fee per gas
let block_to_check = (fee_history.oldest_block + _pos as u64).as_u64();
let fee_to_check = calculated_fee_history.base_fee_per_gas[_pos];
let gas_ratio_to_check = calculated_fee_history.gas_used_ratio[_pos];
if *_base_fee_per_gas != fee_to_check {
return Err(ExecutionError::InvalidBaseGaseFee(
fee_to_check,
*_base_fee_per_gas,
block_to_check,
)
.into());
}
// Check gas used ratio
let rpc_gas_used_rounded =
(fee_history.gas_used_ratio[_pos] * 10.0_f64.powi(12)).round() / 10.0_f64.powi(12);
if gas_ratio_to_check != rpc_gas_used_rounded {
return Err(ExecutionError::InvalidGasUsedRatio(
gas_ratio_to_check,
rpc_gas_used_rounded,
block_to_check,
)
.into());
}
}
Ok(())
}
fn encode_receipt(receipt: &TransactionReceipt) -> Vec<u8> {

View File

@ -1,18 +1,18 @@
use std::str::FromStr;
use async_trait::async_trait;
use common::errors::RpcError;
use ethers::prelude::{Address, Http};
use ethers::providers::{HttpRateLimitRetryPolicy, Middleware, Provider, RetryClient};
use ethers::types::transaction::eip2718::TypedTransaction;
use ethers::types::transaction::eip2930::AccessList;
use ethers::types::{
BlockId, Bytes, EIP1186ProofResponse, Eip1559TransactionRequest, Filter, Log, Transaction,
TransactionReceipt, H256, U256,
BlockId, BlockNumber, Bytes, EIP1186ProofResponse, Eip1559TransactionRequest, FeeHistory,
Filter, Log, Transaction, TransactionReceipt, H256, U256,
};
use eyre::Result;
use crate::types::CallOpts;
use common::errors::RpcError;
use super::ExecutionRpc;
@ -27,13 +27,16 @@ impl Clone for HttpRpc {
}
}
#[async_trait]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl ExecutionRpc for HttpRpc {
fn new(rpc: &str) -> Result<Self> {
let http = Http::from_str(rpc)?;
let mut client = RetryClient::new(http, Box::new(HttpRateLimitRetryPolicy), 100, 50);
client.set_compute_units(300);
let provider = Provider::new(client);
Ok(HttpRpc {
url: rpc.to_string(),
provider,
@ -64,7 +67,7 @@ impl ExecutionRpc for HttpRpc {
let block = Some(BlockId::from(block));
let mut raw_tx = Eip1559TransactionRequest::new();
raw_tx.to = Some(opts.to.into());
raw_tx.to = Some(opts.to.unwrap_or_default().into());
raw_tx.from = opts.from;
raw_tx.value = opts.value;
raw_tx.gas = Some(opts.gas.unwrap_or(U256::from(100_000_000)));
@ -132,4 +135,27 @@ impl ExecutionRpc for HttpRpc {
.await
.map_err(|e| RpcError::new("get_logs", e))?)
}
async fn chain_id(&self) -> Result<u64> {
Ok(self
.provider
.get_chainid()
.await
.map_err(|e| RpcError::new("chain_id", e))?
.as_u64())
}
async fn get_fee_history(
&self,
block_count: u64,
last_block: u64,
reward_percentiles: &[f64],
) -> Result<FeeHistory> {
let block = BlockNumber::from(last_block);
Ok(self
.provider
.fee_history(block_count, block, reward_percentiles)
.await
.map_err(|e| RpcError::new("fee_history", e))?)
}
}

View File

@ -3,8 +3,8 @@ use std::{fs::read_to_string, path::PathBuf};
use async_trait::async_trait;
use common::utils::hex_str_to_bytes;
use ethers::types::{
transaction::eip2930::AccessList, Address, EIP1186ProofResponse, Filter, Log, Transaction,
TransactionReceipt, H256,
transaction::eip2930::AccessList, Address, EIP1186ProofResponse, FeeHistory, Filter, Log,
Transaction, TransactionReceipt, H256,
};
use eyre::{eyre, Result};
@ -17,7 +17,8 @@ pub struct MockRpc {
path: PathBuf,
}
#[async_trait]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl ExecutionRpc for MockRpc {
fn new(rpc: &str) -> Result<Self> {
let path = PathBuf::from(rpc);
@ -65,4 +66,18 @@ impl ExecutionRpc for MockRpc {
let logs = read_to_string(self.path.join("logs.json"))?;
Ok(serde_json::from_str(&logs)?)
}
async fn chain_id(&self) -> Result<u64> {
Err(eyre!("not implemented"))
}
async fn get_fee_history(
&self,
_block_count: u64,
_last_block: u64,
_reward_percentiles: &[f64],
) -> Result<FeeHistory> {
let fee_history = read_to_string(self.path.join("fee_history.json"))?;
Ok(serde_json::from_str(&fee_history)?)
}
}

View File

@ -1,7 +1,7 @@
use async_trait::async_trait;
use ethers::types::{
transaction::eip2930::AccessList, Address, EIP1186ProofResponse, Filter, Log, Transaction,
TransactionReceipt, H256,
transaction::eip2930::AccessList, Address, EIP1186ProofResponse, FeeHistory, Filter, Log,
Transaction, TransactionReceipt, H256,
};
use eyre::Result;
@ -13,7 +13,8 @@ pub mod ws_rpc;
pub use ws_rpc::*;
pub mod mock_rpc;
#[async_trait]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait ExecutionRpc: Send + Clone + Sync + 'static {
fn new(rpc: &str) -> Result<Self>
where
@ -35,4 +36,11 @@ pub trait ExecutionRpc: Send + Clone + Sync + 'static {
async fn get_transaction_receipt(&self, tx_hash: &H256) -> Result<Option<TransactionReceipt>>;
async fn get_transaction(&self, tx_hash: &H256) -> Result<Option<Transaction>>;
async fn get_logs(&self, filter: &Filter) -> Result<Vec<Log>>;
async fn chain_id(&self) -> Result<u64>;
async fn get_fee_history(
&self,
block_count: u64,
last_block: u64,
reward_percentiles: &[f64],
) -> Result<FeeHistory>;
}

View File

@ -19,7 +19,7 @@ pub struct Account {
pub slots: HashMap<H256, U256>,
}
#[derive(Deserialize, Serialize, Debug)]
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionBlock {
#[serde(serialize_with = "serialize_u64_string")]
@ -54,17 +54,17 @@ pub struct ExecutionBlock {
pub uncles: Vec<H256>,
}
#[derive(Deserialize, Serialize, Debug)]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum Transactions {
Hashes(Vec<H256>),
Full(Vec<Transaction>),
}
#[derive(Deserialize, Serialize)]
#[derive(Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CallOpts {
pub from: Option<Address>,
pub to: Address,
pub to: Option<Address>,
pub gas: Option<U256>,
pub gas_price: Option<U256>,
pub value: Option<U256>,
@ -90,7 +90,7 @@ where
let bytes: Option<String> = serde::Deserialize::deserialize(deserializer)?;
match bytes {
Some(bytes) => {
let bytes = hex::decode(bytes.strip_prefix("0x").unwrap()).unwrap();
let bytes = hex::decode(bytes.strip_prefix("0x").unwrap_or("")).unwrap_or_default();
Ok(Some(bytes.to_vec()))
}
None => Ok(None),

35
execution/testdata/fee_history.json vendored Normal file
View File

@ -0,0 +1,35 @@
{
"id": "1",
"jsonrpc": "2.0",
"result": {
"oldestBlock": 10762137,
"reward": [
[
"0x4a817c7ee",
"0x4a817c7ee"
], [
"0x773593f0",
"0x773593f5"
], [
"0x0",
"0x0"
], [
"0x773593f5",
"0x773bae75"
]
],
"baseFeePerGas": [
"0x12",
"0x10",
"0x10",
"0xe",
"0xd"
],
"gasUsedRatio": [
0.026089875,
0.406803,
0,
0.0866665
]
}
}

View File

@ -23,7 +23,7 @@ async fn test_get_account() {
hex_str_to_bytes("0xaa02f5db2ee75e3da400d10f3c30e894b6016ce8a2501680380a907b6674ce0d")
.unwrap(),
),
..Default::default()
..ExecutionPayload::default()
};
let account = execution
@ -200,3 +200,23 @@ async fn test_get_block() {
assert_eq!(block.number, 12345);
}
#[tokio::test]
async fn test_get_tx_by_block_hash_and_index() {
let execution = get_client();
let tx_hash =
H256::from_str("2dac1b27ab58b493f902dda8b63979a112398d747f1761c0891777c0983e591f").unwrap();
let mut payload = ExecutionPayload {
block_number: 7530933,
..ExecutionPayload::default()
};
payload.transactions.push(List::from_iter(hex_str_to_bytes("0x02f8b20583623355849502f900849502f91082ea6094326c977e6efc84e512bb9c30f76e30c160ed06fb80b844a9059cbb0000000000000000000000007daccf9b3c1ae2fa5c55f1c978aeef700bc83be0000000000000000000000000000000000000000000000001158e460913d00000c080a0e1445466b058b6f883c0222f1b1f3e2ad9bee7b5f688813d86e3fa8f93aa868ca0786d6e7f3aefa8fe73857c65c32e4884d8ba38d0ecfb947fbffb82e8ee80c167").unwrap()));
let tx = execution
.get_transaction_by_block_hash_and_index(&payload, 0)
.await
.unwrap()
.unwrap();
assert_eq!(tx.hash(), tx_hash);
}

30
helios-ts/Cargo.toml Normal file
View File

@ -0,0 +1,30 @@
[package]
name = "helios-ts"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.84"
wasm-bindgen-futures = "0.4.33"
serde-wasm-bindgen = "0.4.5"
console_error_panic_hook = "0.1.7"
ethers = "1.0.0"
hex = "0.4.3"
serde = { version = "1.0.143", features = ["derive"] }
serde_json = "1.0.85"
client = { path = "../client" }
common = { path = "../common" }
consensus = { path = "../consensus" }
execution = { path = "../execution" }
config = { path = "../config" }
[dependencies.web-sys]
version = "0.3"
features = [
"console",
]

24
helios-ts/index.html Normal file
View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>hello-wasm example</title>
</head>
<body>
<script src="./dist/lib.js"></script>
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"></script>
<script>
const config = {
executionRpc:"http://localhost:9001/proxy",
consensusRpc: "http://localhost:9002/proxy",
checkpoint: "0x372342db81e3a42527e08dc19e33cd4f91f440f45b9ddb0a9865d407eceb08e4",
};
helios.createHeliosProvider(config).then(heliosProvider => {
heliosProvider.sync().then(() => {
window.provider = new ethers.providers.Web3Provider(heliosProvider);
});
});
</script>
</body>
</html>

111
helios-ts/lib.ts Normal file
View File

@ -0,0 +1,111 @@
import init, { Client } from "./pkg/index";
export async function createHeliosProvider(config: Config): Promise<HeliosProvider> {
const wasmData = require("./pkg/index_bg.wasm");
await init(wasmData);
return new HeliosProvider(config);
}
/// An EIP-1193 compliant Ethereum provider. Treat this the same as you
/// would window.ethereum when constructing an ethers or web3 provider.
export class HeliosProvider {
#client;
#chainId;
/// Do not use this constructor. Instead use the createHeliosProvider function.
constructor(config: Config) {
const executionRpc = config.executionRpc;
const consensusRpc = config.consensusRpc;
const checkpoint = config.checkpoint;
const network = config.network ?? Network.MAINNET;
this.#client = new Client(executionRpc, consensusRpc, network, checkpoint);
this.#chainId = this.#client.chain_id();
}
async sync() {
await this.#client.sync();
}
async request(req: Request): Promise<any> {
switch(req.method) {
case "eth_getBalance": {
return this.#client.get_balance(req.params[0], req.params[1]);
};
case "eth_chainId": {
return this.#chainId;
};
case "eth_blockNumber": {
return this.#client.get_block_number();
};
case "eth_getTransactionByHash": {
let tx = await this.#client.get_transaction_by_hash(req.params[0]);
return mapToObj(tx);
};
case "eth_getTransactionCount": {
return this.#client.get_transaction_count(req.params[0], req.params[1]);
};
case "eth_getBlockTransactionCountByHash": {
return this.#client.get_block_transaction_count_by_hash(req.params[0]);
};
case "eth_getBlockTransactionCountByNumber": {
return this.#client.get_block_transaction_count_by_number(req.params[0]);
};
case "eth_getCode": {
return this.#client.get_code(req.params[0], req.params[1]);
};
case "eth_call": {
return this.#client.call(req.params[0], req.params[1]);
};
case "eth_estimateGas": {
return this.#client.estimate_gas(req.params[0]);
};
case "eth_gasPrice": {
return this.#client.gas_price();
};
case "eth_maxPriorityFeePerGas": {
return this.#client.max_priority_fee_per_gas();
};
case "eth_sendRawTransaction": {
return this.#client.send_raw_transaction(req.params[0]);
};
case "eth_getTransactionReceipt": {
return this.#client.get_transaction_receipt(req.params[0]);
};
case "eth_getLogs": {
return this.#client.get_logs(req.params[0]);
};
case "net_version": {
return this.#chainId;
};
}
}
}
export type Config = {
executionRpc: string,
consensusRpc?: string,
checkpoint?: string,
network?: Network,
}
export enum Network {
MAINNET = "mainnet",
GOERLI = "goerli",
}
type Request = {
method: string,
params: any[],
}
function mapToObj(map: Map<any, any> | undefined): Object | undefined {
if(!map) return undefined;
return Array.from(map).reduce((obj: any, [key, value]) => {
obj[key] = value;
return obj;
}, {});
}

4117
helios-ts/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
helios-ts/package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "helios",
"version": "0.1.0",
"main": "./dist/lib.js",
"types": "./dist/lib.d.ts",
"scripts": {
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "^1.6.0",
"ts-loader": "^9.4.1",
"typescript": "^4.9.3",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.0"
},
"dependencies": {
"ethers": "^5.7.2"
}
}

7
helios-ts/run.sh Executable file
View File

@ -0,0 +1,7 @@
set -e
(&>/dev/null lcp --proxyUrl https://eth-mainnet.g.alchemy.com/v2/23IavJytUwkTtBMpzt_TZKwgwAarocdT --port 9001 &)
(&>/dev/null lcp --proxyUrl https://www.lightclientdata.org --port 9002 &)
npm run build
simple-http-server

185
helios-ts/src/lib.rs Normal file
View File

@ -0,0 +1,185 @@
extern crate console_error_panic_hook;
extern crate web_sys;
use std::str::FromStr;
use common::types::BlockTag;
use ethers::types::{Address, Filter, H256};
use execution::types::CallOpts;
use wasm_bindgen::prelude::*;
use client::database::ConfigDB;
use config::{networks, Config};
#[allow(unused_macros)]
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&format!( $( $t )* ).into());
}
}
#[wasm_bindgen]
pub struct Client {
inner: client::Client<ConfigDB>,
chain_id: u64,
}
#[wasm_bindgen]
impl Client {
#[wasm_bindgen(constructor)]
pub fn new(
execution_rpc: String,
consensus_rpc: Option<String>,
network: String,
checkpoint: Option<String>,
) -> Self {
console_error_panic_hook::set_once();
let base = match network.as_str() {
"mainnet" => networks::mainnet(),
"goerli" => networks::goerli(),
_ => panic!("invalid network"),
};
let chain_id = base.chain.chain_id;
let checkpoint = Some(
checkpoint
.as_ref()
.map(|c| c.strip_prefix("0x").unwrap_or(c.as_str()))
.map(|c| hex::decode(c).unwrap())
.unwrap_or(base.default_checkpoint),
);
let consensus_rpc = consensus_rpc.unwrap_or(base.consensus_rpc.unwrap());
let config = Config {
execution_rpc,
consensus_rpc,
checkpoint,
chain: base.chain,
forks: base.forks,
..Default::default()
};
let inner: client::Client<ConfigDB> =
client::ClientBuilder::new().config(config).build().unwrap();
Self { inner, chain_id }
}
#[wasm_bindgen]
pub async fn sync(&mut self) {
self.inner.start().await.unwrap()
}
#[wasm_bindgen]
pub fn chain_id(&self) -> u32 {
self.chain_id as u32
}
#[wasm_bindgen]
pub async fn get_block_number(&self) -> u32 {
self.inner.get_block_number().await.unwrap() as u32
}
#[wasm_bindgen]
pub async fn get_balance(&self, addr: JsValue, block: JsValue) -> String {
let addr: Address = serde_wasm_bindgen::from_value(addr).unwrap();
let block: BlockTag = serde_wasm_bindgen::from_value(block).unwrap();
self.inner
.get_balance(&addr, block)
.await
.unwrap()
.to_string()
}
#[wasm_bindgen]
pub async fn get_transaction_by_hash(&self, hash: String) -> JsValue {
let hash = H256::from_str(&hash).unwrap();
let tx = self.inner.get_transaction_by_hash(&hash).await.unwrap();
serde_wasm_bindgen::to_value(&tx).unwrap()
}
#[wasm_bindgen]
pub async fn get_transaction_count(&self, addr: JsValue, block: JsValue) -> u32 {
let addr: Address = serde_wasm_bindgen::from_value(addr).unwrap();
let block: BlockTag = serde_wasm_bindgen::from_value(block).unwrap();
self.inner.get_nonce(&addr, block).await.unwrap() as u32
}
#[wasm_bindgen]
pub async fn get_block_transaction_count_by_hash(&self, hash: JsValue) -> u32 {
let hash: H256 = serde_wasm_bindgen::from_value(hash).unwrap();
self.inner
.get_block_transaction_count_by_hash(&hash.as_bytes().to_vec())
.await
.unwrap() as u32
}
#[wasm_bindgen]
pub async fn get_block_transaction_count_by_number(&self, block: JsValue) -> u32 {
let block: BlockTag = serde_wasm_bindgen::from_value(block).unwrap();
self.inner
.get_block_transaction_count_by_number(block)
.await
.unwrap() as u32
}
#[wasm_bindgen]
pub async fn get_code(&self, addr: JsValue, block: JsValue) -> String {
let addr: Address = serde_wasm_bindgen::from_value(addr).unwrap();
let block: BlockTag = serde_wasm_bindgen::from_value(block).unwrap();
let code = self.inner.get_code(&addr, block).await.unwrap();
format!("0x{}", hex::encode(code))
}
#[wasm_bindgen]
pub async fn call(&self, opts: JsValue, block: JsValue) -> String {
let opts: CallOpts = serde_wasm_bindgen::from_value(opts).unwrap();
let block: BlockTag = serde_wasm_bindgen::from_value(block).unwrap();
let res = self.inner.call(&opts, block).await.unwrap();
format!("0x{}", hex::encode(res))
}
#[wasm_bindgen]
pub async fn estimate_gas(&self, opts: JsValue) -> u32 {
let opts: CallOpts = serde_wasm_bindgen::from_value(opts).unwrap();
self.inner.estimate_gas(&opts).await.unwrap() as u32
}
#[wasm_bindgen]
pub async fn gas_price(&self) -> JsValue {
let price = self.inner.get_gas_price().await.unwrap();
serde_wasm_bindgen::to_value(&price).unwrap()
}
#[wasm_bindgen]
pub async fn max_priority_fee_per_gas(&self) -> JsValue {
let price = self.inner.get_priority_fee().await.unwrap();
serde_wasm_bindgen::to_value(&price).unwrap()
}
#[wasm_bindgen]
pub async fn send_raw_transaction(&self, tx: String) -> JsValue {
let tx = hex::decode(tx).unwrap();
let hash = self.inner.send_raw_transaction(&tx).await.unwrap();
serde_wasm_bindgen::to_value(&hash).unwrap()
}
#[wasm_bindgen]
pub async fn get_transaction_receipt(&self, tx: JsValue) -> JsValue {
let tx: H256 = serde_wasm_bindgen::from_value(tx).unwrap();
let receipt = self.inner.get_transaction_receipt(&tx).await.unwrap();
serde_wasm_bindgen::to_value(&receipt).unwrap()
}
#[wasm_bindgen]
pub async fn get_logs(&self, filter: JsValue) -> JsValue {
let filter: Filter = serde_wasm_bindgen::from_value(filter).unwrap();
let logs = self.inner.get_logs(&filter).await.unwrap();
serde_wasm_bindgen::to_value(&logs).unwrap()
}
}

13
helios-ts/tsconfig.json Normal file
View File

@ -0,0 +1,13 @@
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es6",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node",
"sourceMap": true,
"declaration": true
}
}

View File

@ -0,0 +1,40 @@
const path = require("path");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: "./lib.ts",
module: {
rules: [
{
test: /\.ts?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.wasm$/,
type: "asset/inline",
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
output: {
filename: "lib.js",
globalObject: 'this',
path: path.resolve(__dirname, "dist"),
library: {
name: "helios",
type: "umd",
}
},
experiments: {
asyncWebAssembly: true,
},
plugins: [
new WasmPackPlugin({
extraArgs: "--target web",
crateDirectory: path.resolve(__dirname),
}),
],
};

27
rpc.md Normal file
View File

@ -0,0 +1,27 @@
# Helios Remote Procedure Calls
Helios provides a variety of RPC methods for interacting with the Ethereum network. These methods are exposed via the `Client` struct. The RPC methods follow the [Ethereum JSON RPC Spec](https://ethereum.github.io/execution-apis/api-documentation). See [examples](./examples/readme.rs) of running remote procedure calls with Helios.
## RPC Methods
| RPC Method | Client Function | Description | Example |
| ---------- | --------------- | ----------- | ------- |
| `eth_getBalance` | `get_balance` | Returns the balance of the account given an address. | `client.get_balance(&self, address: &str, block: BlockTag)` |
| `eth_getTransactionCount` | `get_nonce` | Returns the number of transactions sent from the given address. | `client.get_nonce(&self, address: &str, block: BlockTag)` |
| `eth_getCode` | `get_code` | Returns the code at a given address. | `client.get_code(&self, address: &str, block: BlockTag)` |
| `eth_call` | `call` | Executes a new message call immediately without creating a transaction on the blockchain. | `client.call(&self, opts: CallOpts, block: BlockTag)` |
| `eth_estimateGas` | `estimate_gas` | Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. | `client.estimate_gas(&self, opts: CallOpts)` |
| `eth_getChainId` | `chain_id` | Returns the chain ID of the current network. | `client.chain_id(&self)` |
| `eth_gasPrice` | `gas_price` | Returns the current price per gas in wei. | `client.gas_price(&self)` |
| `eth_maxPriorityFeePerGas` | `max_priority_fee_per_gas` | Returns the current max priority fee per gas in wei. | `client.max_priority_fee_per_gas(&self)` |
| `eth_blockNumber` | `block_number` | Returns the number of the most recent block. | `client.block_number(&self)` |
| `eth_getBlockByNumber` | `get_block_by_number` | Returns the information of a block by number. | `get_block_by_number(&self, block: BlockTag, full_tx: bool)` |
| `eth_getBlockByHash` | `get_block_by_hash` | Returns the information of a block by hash. | `get_block_by_hash(&self, hash: &str, full_tx: bool)` |
| `eth_sendRawTransaction` | `send_raw_transaction` | Submits a raw transaction to the network. | `client.send_raw_transaction(&self, bytes: &str)` |
| `eth_getTransactionReceipt` | `get_transaction_receipt` | Returns the receipt of a transaction by transaction hash. | `client.get_transaction_receipt(&self, hash: &str)` |
| `eth_getLogs` | `get_logs` | Returns an array of logs matching the filter. | `client.get_logs(&self, filter: Filter)` |
| `eth_getStorageAt` | `get_storage_at` | Returns the value from a storage position at a given address. | `client.get_storage_at(&self, address: &str, slot: H256, block: BlockTag)` |
| `eth_getBlockTransactionCountByHash` | `get_block_transaction_count_by_hash` | Returns the number of transactions in a block from a block matching the transaction hash. | `client.get_block_transaction_count_by_hash(&self, hash: &str)` |
| `eth_getBlockTransactionCountByNumber` | `get_block_transaction_count_by_number` | Returns the number of transactions in a block from a block matching the block number. | `client.get_block_transaction_count_by_number(&self, block: BlockTag)` |
| `eth_coinbase` | `get_coinbase` | Returns the client coinbase address. | `client.get_coinbase(&self)` |
| `eth_syncing` | `syncing` | Returns an object with data about the sync status or false. | `client.syncing(&self)` |

View File

@ -1 +1 @@
nightly
nightly-2023-01-23

View File

@ -51,16 +51,18 @@
//! Errors used across helios.
pub mod client {
pub use client::{database::FileDB, Client, ClientBuilder};
#[cfg(not(target_arch = "wasm32"))]
pub use client::database::FileDB;
pub use client::{database::ConfigDB, Client, ClientBuilder};
}
pub mod config {
pub use config::{networks, Config};
pub use config::{checkpoints, networks, Config};
}
pub mod types {
pub use common::types::BlockTag;
pub use execution::types::CallOpts;
pub use execution::types::{Account, CallOpts, ExecutionBlock, Transactions};
}
pub mod errors {

122
tests/feehistory.rs Normal file
View File

@ -0,0 +1,122 @@
use env_logger::Env;
use eyre::Result;
use helios::{config::networks::Network, prelude::*};
use std::time::Duration;
use std::{env, path::PathBuf};
#[tokio::test]
async fn feehistory() -> Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
// Client Configuration
let api_key = env::var("MAINNET_RPC_URL").expect("MAINNET_RPC_URL env variable missing");
let checkpoint = "0x4d9b87a319c52e54068b7727a93dd3d52b83f7336ed93707bcdf7b37aefce700";
let consensus_rpc = "https://www.lightclientdata.org";
let data_dir = "/tmp/helios";
log::info!("Using consensus RPC URL: {}", consensus_rpc);
// Instantiate Client
let mut client: Client<FileDB> = ClientBuilder::new()
.network(Network::MAINNET)
.consensus_rpc(consensus_rpc)
.execution_rpc(&api_key)
.checkpoint(checkpoint)
.load_external_fallback()
.data_dir(PathBuf::from(data_dir))
.build()?;
log::info!(
"Built client on \"{}\" with external checkpoint fallbacks",
Network::MAINNET
);
client.start().await?;
// Wait for syncing
std::thread::sleep(Duration::from_secs(5));
// Get inputs for fee_history calls
let head_block_num = client.get_block_number().await?;
log::info!("head_block_num: {}", &head_block_num);
let block = BlockTag::Latest;
let block_number = BlockTag::Number(head_block_num);
log::info!("block {:?} and block_number {:?}", block, block_number);
let reward_percentiles: Vec<f64> = vec![];
// Get fee history for 1 block back from latest
let fee_history = client
.get_fee_history(1, head_block_num, &reward_percentiles)
.await?
.unwrap();
assert_eq!(fee_history.base_fee_per_gas.len(), 2);
assert_eq!(fee_history.oldest_block.as_u64(), head_block_num - 1);
// Fetch 10000 delta, helios will return as many as it can
let fee_history = match client
.get_fee_history(10_000, head_block_num, &reward_percentiles)
.await?
{
Some(fee_history) => fee_history,
None => panic!(
"empty gas fee returned with inputs: Block count: {:?}, Head Block #: {:?}, Reward Percentiles: {:?}",
10_000, head_block_num, &reward_percentiles
),
};
assert!(
!fee_history.base_fee_per_gas.is_empty(),
"fee_history.base_fee_per_gas.len() {:?}",
fee_history.base_fee_per_gas.len()
);
// Fetch 10000 blocks in the past
// Helios will error since it won't have those historical blocks
let fee_history = client
.get_fee_history(1, head_block_num - 10_000, &reward_percentiles)
.await;
assert!(fee_history.is_err(), "fee_history() {fee_history:?}");
// Fetch 20 block away
// Should return array of size 21: our 20 block of interest + the next one
// The oldest block should be 19 block away, including it
let fee_history = client
.get_fee_history(20, head_block_num, &reward_percentiles)
.await?
.unwrap();
assert_eq!(
fee_history.base_fee_per_gas.len(),
21,
"fee_history.base_fee_per_gas.len() {:?} vs 21",
fee_history.base_fee_per_gas.len()
);
assert_eq!(
fee_history.oldest_block.as_u64(),
head_block_num - 20,
"fee_history.oldest_block.as_u64() {:?} vs head_block_num {:?} - 19",
fee_history.oldest_block.as_u64(),
head_block_num
);
// Fetch whatever blocks ahead, but that will fetch one block behind.
// This should return an answer of size two as Helios will cap this request to the newest block it knows
// we refresh parameters to make sure head_block_num is in line with newest block of our payload
let head_block_num = client.get_block_number().await?;
let fee_history = client
.get_fee_history(1, head_block_num + 1000, &reward_percentiles)
.await?
.unwrap();
assert_eq!(
fee_history.base_fee_per_gas.len(),
2,
"fee_history.base_fee_per_gas.len() {:?} vs 2",
fee_history.base_fee_per_gas.len()
);
assert_eq!(
fee_history.oldest_block.as_u64(),
head_block_num - 1,
"fee_history.oldest_block.as_u64() {:?} vs head_block_num {:?}",
fee_history.oldest_block.as_u64(),
head_block_num
);
Ok(())
}