fix: Change Arc<KzgSettings> to EnvKzgSettings (#9054)

This commit is contained in:
Omid Chenane
2024-06-24 18:26:53 +03:30
committed by GitHub
parent 81b5fbf573
commit c5aee02ff7
9 changed files with 49 additions and 74 deletions

View File

@ -24,16 +24,15 @@ use reth_fs_util as fs;
use reth_node_api::PayloadBuilderAttributes;
use reth_payload_builder::database::CachedReads;
use reth_primitives::{
constants::eip4844::{LoadKzgSettingsError, MAINNET_KZG_TRUSTED_SETUP},
revm_primitives::KzgSettings,
Address, BlobTransaction, BlobTransactionSidecar, Bytes, PooledTransactionsElement,
SealedBlock, SealedBlockWithSenders, Transaction, TransactionSigned, TxEip4844, B256, U256,
constants::eip4844::LoadKzgSettingsError, revm_primitives::KzgSettings, Address,
BlobTransaction, BlobTransactionSidecar, Bytes, PooledTransactionsElement, SealedBlock,
SealedBlockWithSenders, Transaction, TransactionSigned, TxEip4844, B256, U256,
};
use reth_provider::{
providers::BlockchainProvider, BlockHashReader, BlockReader, BlockWriter, ChainSpecProvider,
ProviderFactory, StageCheckpointReader, StateProviderFactory,
};
use reth_revm::database::StateProviderDatabase;
use reth_revm::{database::StateProviderDatabase, primitives::EnvKzgSettings};
use reth_rpc_types::engine::{BlobsBundleV1, PayloadAttributes};
use reth_stages::StageId;
use reth_transaction_pool::{
@ -103,14 +102,14 @@ impl Command {
}
/// Loads the trusted setup params from a given file path or falls back to
/// `MAINNET_KZG_TRUSTED_SETUP`.
fn kzg_settings(&self) -> eyre::Result<Arc<KzgSettings>> {
/// `EnvKzgSettings::Default`.
fn kzg_settings(&self) -> eyre::Result<EnvKzgSettings> {
if let Some(ref trusted_setup_file) = self.trusted_setup_file {
let trusted_setup = KzgSettings::load_trusted_setup_file(trusted_setup_file)
.map_err(LoadKzgSettingsError::KzgError)?;
Ok(Arc::new(trusted_setup))
Ok(EnvKzgSettings::Custom(Arc::new(trusted_setup)))
} else {
Ok(Arc::clone(&MAINNET_KZG_TRUSTED_SETUP))
Ok(EnvKzgSettings::Default)
}
}

View File

@ -1,5 +1,6 @@
use alloy_consensus::{
BlobTransactionSidecar, SidecarBuilder, SimpleCoder, TxEip4844Variant, TxEnvelope,
BlobTransactionSidecar, EnvKzgSettings, SidecarBuilder, SimpleCoder, TxEip4844Variant,
TxEnvelope,
};
use alloy_network::{eip2718::Encodable2718, EthereumWallet, TransactionBuilder};
use alloy_rpc_types::{TransactionInput, TransactionRequest};
@ -7,7 +8,7 @@ use alloy_signer_local::PrivateKeySigner;
use eyre::Ok;
use reth_primitives::{hex, Address, Bytes, U256};
use reth_primitives::{constants::eip4844::MAINNET_KZG_TRUSTED_SETUP, B256};
use reth_primitives::B256;
pub struct TransactionTestContext;
@ -71,12 +72,12 @@ impl TransactionTestContext {
/// Validates the sidecar of a given tx envelope and returns the versioned hashes
pub fn validate_sidecar(tx: TxEnvelope) -> Vec<B256> {
let proof_setting = MAINNET_KZG_TRUSTED_SETUP.clone();
let proof_setting = EnvKzgSettings::Default;
match tx {
TxEnvelope::Eip4844(signed) => match signed.tx() {
TxEip4844Variant::TxEip4844WithSidecar(tx) => {
tx.validate_blob(&proof_setting).unwrap();
tx.validate_blob(proof_setting.get()).unwrap();
tx.sidecar.versioned_hashes().collect()
}
_ => panic!("Expected Eip4844 transaction with sidecar"),

View File

@ -16,8 +16,7 @@ use reth_config::config::PruneConfig;
use reth_db_api::{database::Database, database_metrics::DatabaseMetrics};
use reth_network_p2p::headers::client::HeadersClient;
use reth_primitives::{
constants::eip4844::MAINNET_KZG_TRUSTED_SETUP, kzg::KzgSettings, BlockHashOrNumber,
BlockNumber, Head, SealedHeader, B256,
revm_primitives::EnvKzgSettings, BlockHashOrNumber, BlockNumber, Head, SealedHeader, B256,
};
use reth_provider::{
providers::StaticFileProvider, BlockHashReader, HeaderProvider, ProviderFactory,
@ -267,9 +266,9 @@ impl NodeConfig {
Ok(max_block)
}
/// Loads '`MAINNET_KZG_TRUSTED_SETUP`'
pub fn kzg_settings(&self) -> eyre::Result<Arc<KzgSettings>> {
Ok(Arc::clone(&MAINNET_KZG_TRUSTED_SETUP))
/// Loads '`EnvKzgSettings::Default`'
pub const fn kzg_settings(&self) -> eyre::Result<EnvKzgSettings> {
Ok(EnvKzgSettings::Default)
}
/// Installs the prometheus recorder.

View File

@ -30,10 +30,10 @@ use reth_node_core::{
cli::config::{PayloadBuilderConfig, RethTransactionPoolConfig},
dirs::{ChainPath, DataDirPath, MaybePlatformPath},
node_config::NodeConfig,
primitives::{kzg::KzgSettings, Head},
primitives::Head,
utils::write_peers_to_file,
};
use reth_primitives::constants::eip4844::MAINNET_KZG_TRUSTED_SETUP;
use reth_primitives::revm_primitives::EnvKzgSettings;
use reth_provider::{providers::BlockchainProvider, ChainSpecProvider};
use reth_tasks::TaskExecutor;
use reth_transaction_pool::{PoolConfig, TransactionPool};
@ -469,9 +469,9 @@ impl<Node: FullNodeTypes> BuilderContext<Node> {
self.config().txpool.pool_config()
}
/// Loads `MAINNET_KZG_TRUSTED_SETUP`.
pub fn kzg_settings(&self) -> eyre::Result<Arc<KzgSettings>> {
Ok(Arc::clone(&MAINNET_KZG_TRUSTED_SETUP))
/// Loads `EnvKzgSettings::Default`.
pub const fn kzg_settings(&self) -> eyre::Result<EnvKzgSettings> {
Ok(EnvKzgSettings::Default)
}
/// Returns the config for payload building.

View File

@ -1,7 +1,7 @@
#![allow(missing_docs)]
use alloy_eips::eip4844::env_settings::EnvKzgSettings;
use alloy_primitives::hex;
use c_kzg::KzgSettings;
use criterion::{
criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion,
};
@ -11,11 +11,8 @@ use proptest::{
test_runner::{RngAlgorithm, TestRng, TestRunner},
};
use proptest_arbitrary_interop::arb;
use reth_primitives::{
constants::eip4844::MAINNET_KZG_TRUSTED_SETUP, BlobTransactionSidecar, TxEip4844,
};
use reth_primitives::{BlobTransactionSidecar, TxEip4844};
use revm_primitives::MAX_BLOB_NUMBER_PER_BLOCK;
use std::sync::Arc;
// constant seed to use for the rng
const SEED: [u8; 32] = hex!("1337133713371337133713371337133713371337133713371337133713371337");
@ -23,11 +20,10 @@ const SEED: [u8; 32] = hex!("133713371337133713371337133713371337133713371337133
/// Benchmarks EIP-48444 blob validation.
fn blob_validation(c: &mut Criterion) {
let mut group = c.benchmark_group("Blob Transaction KZG validation");
let kzg_settings = MAINNET_KZG_TRUSTED_SETUP.clone();
for num_blobs in 1..=MAX_BLOB_NUMBER_PER_BLOCK {
println!("Benchmarking validation for tx with {num_blobs} blobs");
validate_blob_tx(&mut group, "ValidateBlob", num_blobs, kzg_settings.clone());
validate_blob_tx(&mut group, "ValidateBlob", num_blobs, EnvKzgSettings::Default);
}
}
@ -35,7 +31,7 @@ fn validate_blob_tx(
group: &mut BenchmarkGroup<'_, WallTime>,
description: &str,
num_blobs: u64,
kzg_settings: Arc<KzgSettings>,
kzg_settings: EnvKzgSettings,
) {
let setup = || {
let config = ProptestConfig::default();
@ -73,7 +69,9 @@ fn validate_blob_tx(
// for now we just use the default SubPoolLimit
group.bench_function(group_id, |b| {
b.iter_with_setup(setup, |(tx, blob_sidecar)| {
if let Err(err) = std::hint::black_box(tx.validate_blob(&blob_sidecar, &kzg_settings)) {
if let Err(err) =
std::hint::black_box(tx.validate_blob(&blob_sidecar, kzg_settings.get()))
{
println!("Validation failed: {err:?}");
}
});

View File

@ -11,19 +11,7 @@ pub use alloy_eips::eip4844::{
#[cfg(feature = "c-kzg")]
mod trusted_setup {
use crate::kzg::KzgSettings;
use once_cell::sync::Lazy;
use std::{io::Write, sync::Arc};
/// KZG trusted setup
pub static MAINNET_KZG_TRUSTED_SETUP: Lazy<Arc<KzgSettings>> = Lazy::new(|| {
Arc::new(
c_kzg::KzgSettings::load_trusted_setup(
&revm_primitives::kzg::G1_POINTS.0,
&revm_primitives::kzg::G2_POINTS.0,
)
.expect("failed to load trusted setup"),
)
});
use std::io::Write;
/// Loads the trusted setup parameters from the given bytes and returns the [`KzgSettings`].
///
@ -48,14 +36,4 @@ mod trusted_setup {
#[error("KZG error: {0:?}")]
KzgError(#[from] c_kzg::Error),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ensure_load_kzg_settings() {
let _settings = Arc::clone(&MAINNET_KZG_TRUSTED_SETUP);
}
}
}

View File

@ -281,14 +281,16 @@ impl BlobTransaction {
/// Generates a [`BlobTransactionSidecar`] structure containing blobs, commitments, and proofs.
#[cfg(all(feature = "c-kzg", any(test, feature = "arbitrary")))]
pub fn generate_blob_sidecar(blobs: Vec<c_kzg::Blob>) -> BlobTransactionSidecar {
use crate::constants::eip4844::MAINNET_KZG_TRUSTED_SETUP;
use alloy_eips::eip4844::env_settings::EnvKzgSettings;
use c_kzg::{KzgCommitment, KzgProof};
let kzg_settings = MAINNET_KZG_TRUSTED_SETUP.clone();
let kzg_settings = EnvKzgSettings::Default;
let commitments: Vec<c_kzg::Bytes48> = blobs
.iter()
.map(|blob| KzgCommitment::blob_to_kzg_commitment(&blob.clone(), &kzg_settings).unwrap())
.map(|blob| {
KzgCommitment::blob_to_kzg_commitment(&blob.clone(), kzg_settings.get()).unwrap()
})
.map(|commitment| commitment.to_bytes())
.collect();
@ -296,7 +298,7 @@ pub fn generate_blob_sidecar(blobs: Vec<c_kzg::Blob>) -> BlobTransactionSidecar
.iter()
.zip(commitments.iter())
.map(|(blob, commitment)| {
KzgProof::compute_blob_kzg_proof(blob, commitment, &kzg_settings).unwrap()
KzgProof::compute_blob_kzg_proof(blob, commitment, kzg_settings.get()).unwrap()
})
.map(|proof| proof.to_bytes())
.collect();

View File

@ -8,7 +8,6 @@ use crate::eth::{
};
use jsonrpsee::core::RpcResult;
use reth_primitives::{
constants::eip4844::MAINNET_KZG_TRUSTED_SETUP,
keccak256,
revm_primitives::db::{DatabaseCommit, DatabaseRef},
PooledTransactionsElement, U256,
@ -21,7 +20,7 @@ use revm::{
db::CacheDB,
primitives::{ResultAndState, TxEnv},
};
use revm_primitives::{EnvWithHandlerCfg, MAX_BLOB_GAS_PER_BLOCK};
use revm_primitives::{EnvKzgSettings, EnvWithHandlerCfg, MAX_BLOB_GAS_PER_BLOCK};
use std::sync::Arc;
/// `Eth` bundle implementation.
@ -126,7 +125,7 @@ where
// Verify that the given blob data, commitments, and proofs are all valid for
// this transaction.
if let PooledTransactionsElement::BlobTransaction(ref tx) = tx {
tx.validate(MAINNET_KZG_TRUSTED_SETUP.as_ref())
tx.validate(EnvKzgSettings::Default.get())
.map_err(|e| EthApiError::InvalidParams(e.to_string()))?;
}

View File

@ -11,17 +11,16 @@ use crate::{
};
use reth_chainspec::ChainSpec;
use reth_primitives::{
constants::{
eip4844::{MAINNET_KZG_TRUSTED_SETUP, MAX_BLOBS_PER_BLOCK},
ETHEREUM_BLOCK_GAS_LIMIT,
},
kzg::KzgSettings,
constants::{eip4844::MAX_BLOBS_PER_BLOCK, ETHEREUM_BLOCK_GAS_LIMIT},
Address, GotExpected, InvalidTransactionError, SealedBlock, TxKind, EIP1559_TX_TYPE_ID,
EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, LEGACY_TX_TYPE_ID, U256,
};
use reth_provider::{AccountReader, BlockReaderIdExt, StateProviderFactory};
use reth_tasks::TaskSpawner;
use revm::{interpreter::gas::validate_initial_tx_gas, primitives::SpecId};
use revm::{
interpreter::gas::validate_initial_tx_gas,
primitives::{EnvKzgSettings, SpecId},
};
use std::{
marker::PhantomData,
sync::{atomic::AtomicBool, Arc},
@ -125,7 +124,7 @@ pub(crate) struct EthTransactionValidatorInner<Client, T> {
/// Minimum priority fee to enforce for acceptance into the pool.
minimum_priority_fee: Option<u128>,
/// Stores the setup and parameters needed for validating KZG proofs.
kzg_settings: Arc<KzgSettings>,
kzg_settings: EnvKzgSettings,
/// How to handle [`TransactionOrigin::Local`](TransactionOrigin) transactions.
local_transactions_config: LocalTransactionConfig,
/// Maximum size in bytes a single transaction can have in order to be accepted into the pool.
@ -369,7 +368,7 @@ where
}
EthBlobTransactionSidecar::Present(blob) => {
// validate the blob
if let Err(err) = transaction.validate_blob(&blob, &self.kzg_settings) {
if let Err(err) = transaction.validate_blob(&blob, self.kzg_settings.get()) {
return TransactionValidationOutcome::Invalid(
transaction,
InvalidPoolTransactionError::Eip4844(
@ -435,7 +434,7 @@ pub struct EthTransactionValidatorBuilder {
additional_tasks: usize,
/// Stores the setup and parameters needed for validating KZG proofs.
kzg_settings: Arc<KzgSettings>,
kzg_settings: EnvKzgSettings,
/// How to handle [`TransactionOrigin::Local`](TransactionOrigin) transactions.
local_transactions_config: LocalTransactionConfig,
/// Max size in bytes of a single transaction allowed
@ -457,7 +456,7 @@ impl EthTransactionValidatorBuilder {
block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT,
minimum_priority_fee: None,
additional_tasks: 1,
kzg_settings: Arc::clone(&MAINNET_KZG_TRUSTED_SETUP),
kzg_settings: EnvKzgSettings::Default,
local_transactions_config: Default::default(),
max_tx_input_bytes: DEFAULT_MAX_TX_INPUT_BYTES,
@ -538,8 +537,8 @@ impl EthTransactionValidatorBuilder {
self
}
/// Sets the [`KzgSettings`] to use for validating KZG proofs.
pub fn kzg_settings(mut self, kzg_settings: Arc<KzgSettings>) -> Self {
/// Sets the [`EnvKzgSettings`] to use for validating KZG proofs.
pub fn kzg_settings(mut self, kzg_settings: EnvKzgSettings) -> Self {
self.kzg_settings = kzg_settings;
self
}