From b710e57f9ade775cc27e8983f3cfc092c62a2853 Mon Sep 17 00:00:00 2001 From: Matthias Seitz Date: Mon, 21 Aug 2023 14:10:15 +0200 Subject: [PATCH] feat: add load_trusted_setup_from_bytes (#4290) --- crates/primitives/src/constants/eip4844.rs | 44 +++++++++++++++++++--- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/primitives/src/constants/eip4844.rs b/crates/primitives/src/constants/eip4844.rs index 602229d2cc..69f6cbce76 100644 --- a/crates/primitives/src/constants/eip4844.rs +++ b/crates/primitives/src/constants/eip4844.rs @@ -28,15 +28,47 @@ pub const TARGET_BLOBS_PER_BLOCK: u64 = TARGET_DATA_GAS_PER_BLOCK / DATA_GAS_PER /// Used to determine the price for next data blob pub const BLOB_GASPRICE_UPDATE_FRACTION: u64 = 3_338_477u64; // 3338477 +/// Commitment version of a KZG commitment +pub const VERSIONED_HASH_VERSION_KZG: u8 = 0x01; + /// KZG Trusted setup raw -const TRUSTED_SETUP_RAW: &str = include_str!("../../res/eip4844/trusted_setup.txt"); +const TRUSTED_SETUP_RAW: &[u8] = include_bytes!("../../res/eip4844/trusted_setup.txt"); /// KZG trusted setup pub static KZG_TRUSTED_SETUP: Lazy> = Lazy::new(|| { - let mut file = tempfile::NamedTempFile::new().unwrap(); - file.write_all(TRUSTED_SETUP_RAW.as_bytes()).unwrap(); - Arc::new(KzgSettings::load_trusted_setup_file(file.path().into()).unwrap()) + Arc::new( + load_trusted_setup_from_bytes(TRUSTED_SETUP_RAW).expect("Failed to load trusted setup"), + ) }); -/// Commitment version of a KZG commitment -pub const VERSIONED_HASH_VERSION_KZG: u8 = 0x01; +/// Loads the trusted setup parameters from the given bytes and returns the [KzgSettings]. +/// +/// This creates a temp file to store the bytes and then loads the [KzgSettings] from the file via +/// [KzgSettings::load_trusted_setup_file]. +pub fn load_trusted_setup_from_bytes(bytes: &[u8]) -> Result { + let mut file = tempfile::NamedTempFile::new().map_err(LoadKzgSettingsError::TempFileErr)?; + file.write_all(bytes).map_err(LoadKzgSettingsError::TempFileErr)?; + KzgSettings::load_trusted_setup_file(file.path().into()).map_err(LoadKzgSettingsError::KzgError) +} + +/// Error type for loading the trusted setup. +#[derive(Debug, thiserror::Error)] +pub enum LoadKzgSettingsError { + /// Failed to create temp file to store bytes for loading [KzgSettings] via + /// [KzgSettings::load_trusted_setup_file]. + #[error("Failed to setup temp file: {0:?}")] + TempFileErr(#[from] std::io::Error), + /// Kzg error + #[error("Kzg error: {0:?}")] + KzgError(c_kzg::Error), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ensure_load_kzg_settings() { + let _settings = Arc::clone(&KZG_TRUSTED_SETUP); + } +}