Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Katana: Add state update DA encodings #2474

Merged
merged 4 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion crates/katana/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ anyhow.workspace = true
base64.workspace = true
derive_more.workspace = true
lazy_static.workspace = true
num-traits.workspace = true
rand = { workspace = true, features = [ "small_rng" ] }
serde.workspace = true
serde_json.workspace = true
Expand All @@ -23,10 +24,11 @@ thiserror.workspace = true
alloy-primitives.workspace = true
flate2 = { workspace = true, optional = true }
katana-cairo.workspace = true
num-bigint = "0.4.6"

[dev-dependencies]
num-traits.workspace = true
assert_matches.workspace = true
rstest.workspace = true
similar-asserts.workspace = true

[features]
Expand Down
41 changes: 41 additions & 0 deletions crates/katana/primitives/src/da/blob.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use num_bigint::BigUint;
use num_traits::Num;

use super::eip4844::{BLOB_LEN, BLS_MODULUS, GENERATOR};
use super::math::{fft, ifft};

/// Recovers the original data from a given blob.
///
/// This function takes a vector of `BigUint` representing the data of a blob and
/// returns the recovered original data as a vector of `BigUint`.
///
/// # Arguments
///
/// * `data` - A vector of `BigUint` representing the blob data.
///
/// # Returns
///
/// A vector of `BigUint` representing the recovered original data.
pub fn recover(data: Vec<BigUint>) -> Vec<BigUint> {
let xs: Vec<BigUint> = (0..BLOB_LEN)
.map(|i| {
let bin = format!("{:012b}", i);
let bin_rev = bin.chars().rev().collect::<String>();
GENERATOR.modpow(&BigUint::from_str_radix(&bin_rev, 2).unwrap(), &BLS_MODULUS)
kariy marked this conversation as resolved.
Show resolved Hide resolved
})
.collect();

ifft(data, xs, &BLS_MODULUS)
}
Comment on lines +19 to +29
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation and handle potential panic

Ohayo, sensei! The recover function looks good overall, but I have two suggestions to improve its robustness:

  1. Add input validation to ensure the correct data length:
 pub fn recover(data: Vec<BigUint>) -> Vec<BigUint> {
+    if data.len() != BLOB_LEN {
+        panic!("Invalid data length: expected {}, got {}", BLOB_LEN, data.len());
+    }
     let xs: Vec<BigUint> = (0..BLOB_LEN)
  1. Handle the potential panic from unwrap():
         .map(|i| {
             let bin = format!("{:012b}", i);
             let bin_rev = bin.chars().rev().collect::<String>();
-            GENERATOR.modpow(&BigUint::from_str_radix(&bin_rev, 2).unwrap(), &BLS_MODULUS)
+            let exponent = BigUint::from_str_radix(&bin_rev, 2)
+                .expect("Failed to parse reversed binary string into BigUint");
+            GENERATOR.modpow(&exponent, &BLS_MODULUS)
         })

These changes will make the function more robust and easier to debug if issues arise.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn recover(data: Vec<BigUint>) -> Vec<BigUint> {
let xs: Vec<BigUint> = (0..BLOB_LEN)
.map(|i| {
let bin = format!("{:012b}", i);
let bin_rev = bin.chars().rev().collect::<String>();
GENERATOR.modpow(&BigUint::from_str_radix(&bin_rev, 2).unwrap(), &BLS_MODULUS)
})
.collect();
ifft(data, xs, &BLS_MODULUS)
}
pub fn recover(data: Vec<BigUint>) -> Vec<BigUint> {
if data.len() != BLOB_LEN {
panic!("Invalid data length: expected {}, got {}", BLOB_LEN, data.len());
}
let xs: Vec<BigUint> = (0..BLOB_LEN)
.map(|i| {
let bin = format!("{:012b}", i);
let bin_rev = bin.chars().rev().collect::<String>();
let exponent = BigUint::from_str_radix(&bin_rev, 2)
.expect("Failed to parse reversed binary string into BigUint");
GENERATOR.modpow(&exponent, &BLS_MODULUS)
})
.collect();
ifft(data, xs, &BLS_MODULUS)
}


pub fn transform(data: Vec<BigUint>) -> Vec<BigUint> {
let xs: Vec<BigUint> = (0..BLOB_LEN)
.map(|i| {
let bin = format!("{:012b}", i);
let bin_rev = bin.chars().rev().collect::<String>();
GENERATOR.modpow(&BigUint::from_str_radix(&bin_rev, 2).unwrap(), &BLS_MODULUS)
})
.collect();

fft(data, xs, &BLS_MODULUS)
}
Comment on lines +31 to +41
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Improve robustness and reduce code duplication

Ohayo, sensei! The transform function looks good, but we can make it more robust and reduce code duplication:

  1. Add input validation and handle potential panic (similar to recover):
 pub fn transform(data: Vec<BigUint>) -> Vec<BigUint> {
+    if data.len() != BLOB_LEN {
+        panic!("Invalid data length: expected {}, got {}", BLOB_LEN, data.len());
+    }
     let xs: Vec<BigUint> = (0..BLOB_LEN)
         .map(|i| {
             let bin = format!("{:012b}", i);
             let bin_rev = bin.chars().rev().collect::<String>();
-            GENERATOR.modpow(&BigUint::from_str_radix(&bin_rev, 2).unwrap(), &BLS_MODULUS)
+            let exponent = BigUint::from_str_radix(&bin_rev, 2)
+                .expect("Failed to parse reversed binary string into BigUint");
+            GENERATOR.modpow(&exponent, &BLS_MODULUS)
         })
         .collect();

     fft(data, xs, &BLS_MODULUS)
 }
  1. To reduce code duplication, consider extracting the common logic into a separate function:
fn generate_xs() -> Vec<BigUint> {
    (0..BLOB_LEN)
        .map(|i| {
            let bin = format!("{:012b}", i);
            let bin_rev = bin.chars().rev().collect::<String>();
            let exponent = BigUint::from_str_radix(&bin_rev, 2)
                .expect("Failed to parse reversed binary string into BigUint");
            GENERATOR.modpow(&exponent, &BLS_MODULUS)
        })
        .collect()
}

pub fn recover(data: Vec<BigUint>) -> Vec<BigUint> {
    if data.len() != BLOB_LEN {
        panic!("Invalid data length: expected {}, got {}", BLOB_LEN, data.len());
    }
    let xs = generate_xs();
    ifft(data, xs, &BLS_MODULUS)
}

pub fn transform(data: Vec<BigUint>) -> Vec<BigUint> {
    if data.len() != BLOB_LEN {
        panic!("Invalid data length: expected {}, got {}", BLOB_LEN, data.len());
    }
    let xs = generate_xs();
    fft(data, xs, &BLS_MODULUS)
}

These changes will improve the robustness of both functions and make the code more maintainable.

26 changes: 26 additions & 0 deletions crates/katana/primitives/src/da/eip4844.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use std::str::FromStr;

use lazy_static::lazy_static;
use num_bigint::{BigUint, ToBigUint};

// ****************************************************************************
// * PARAMETERS & CONSTANTS *
// ****************************************************************************
/// Length of the blob.
pub const BLOB_LEN: usize = 4096;

lazy_static! {
/// EIP-4844 BLS12-381 modulus.
///
/// As defined in https://eips.ethereum.org/EIPS/eip-4844
pub static ref BLS_MODULUS: BigUint = BigUint::from_str(
"52435875175126190479447740508185965837690552500527637822603658699938581184513",
)
.unwrap();
/// Generator of the group of evaluation points (EIP-4844 parameter).
pub static ref GENERATOR: BigUint = BigUint::from_str(
"39033254847818212395286706435128746857159659164139250548781411570340225835782",
)
.unwrap();
pub static ref TWO: BigUint = 2u32.to_biguint().unwrap();
}
Loading
Loading