Skip to content

Commit

Permalink
fix: Change Arc<KzgSettings> to EnvKzgSettings (#9054)
Browse files Browse the repository at this point in the history
  • Loading branch information
ochenane authored Jun 24, 2024
1 parent 81b5fbf commit c5aee02
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 74 deletions.
17 changes: 8 additions & 9 deletions bin/reth/src/commands/debug_cmd/build_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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)
}
}

Expand Down
9 changes: 5 additions & 4 deletions crates/e2e-test-utils/src/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
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};
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;

Expand Down Expand Up @@ -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"),
Expand Down
9 changes: 4 additions & 5 deletions crates/node-core/src/node_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
10 changes: 5 additions & 5 deletions crates/node/builder/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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.
Expand Down
16 changes: 7 additions & 9 deletions crates/primitives/benches/validate_blob_tx.rs
Original file line number Diff line number Diff line change
@@ -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,
};
Expand All @@ -11,31 +11,27 @@ 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");

/// 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);
}
}

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();
Expand Down Expand Up @@ -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:?}");
}
});
Expand Down
24 changes: 1 addition & 23 deletions crates/primitives/src/constants/eip4844.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`].
///
Expand All @@ -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);
}
}
}
10 changes: 6 additions & 4 deletions crates/primitives/src/transaction/sidecar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,22 +281,24 @@ 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();

let proofs: Vec<c_kzg::Bytes48> = blobs
.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();
Expand Down
5 changes: 2 additions & 3 deletions crates/rpc/rpc/src/eth/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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()))?;
}

Expand Down
23 changes: 11 additions & 12 deletions crates/transaction-pool/src/validate/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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,

Expand Down Expand Up @@ -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
}
Expand Down

0 comments on commit c5aee02

Please sign in to comment.