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

fix(alloy-eips): SimpleCoder::decode_one() should return Ok(None) #1818

Merged
merged 11 commits into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
37 changes: 32 additions & 5 deletions crates/eips/src/eip4844/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use crate::eip4844::Blob;
use c_kzg::{KzgCommitment, KzgProof};

use crate::eip4844::{
utils::WholeFe, BYTES_PER_BLOB, FIELD_ELEMENTS_PER_BLOB, MAX_BLOBS_PER_BLOCK,
utils::WholeFe, BYTES_PER_BLOB, FIELD_ELEMENTS_PER_BLOB, FIELD_ELEMENT_BYTES,
MAX_BLOBS_PER_BLOCK,
};
use alloc::vec::Vec;

Expand Down Expand Up @@ -192,10 +193,12 @@ impl SimpleCoder {
/// Decode an some bytes from an iterator of valid FEs.
///
/// Returns `Ok(Some(data))` if there is some data.
/// Returns `Ok(None)` if there is no data (length prefix is 0).
/// Returns `Ok(None)` if there is no data (empty iterator, length prefix is 0).
/// Returns `Err(())` if there is an error.
fn decode_one<'a>(mut fes: impl Iterator<Item = WholeFe<'a>>) -> Result<Option<Vec<u8>>, ()> {
let first = fes.next().ok_or(())?;
let Some(first) = fes.next() else {
return Ok(None);
};
Comment on lines +200 to +202
Copy link
Member

Choose a reason for hiding this comment

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

this also makes sense, because before this would always return an error for iters len > 1, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this returned an error when there was no more data left in the iterator. but that's a little different from what we want from decode_all().

let mut num_bytes = u64::from_be_bytes(first.as_ref()[1..9].try_into().unwrap()) as usize;

// if no more bytes is 0, we're done
Expand Down Expand Up @@ -244,8 +247,21 @@ impl SidecarCoder for SimpleCoder {
fn finish(self, _builder: &mut PartialSidecar) {}

fn decode_all(&mut self, blobs: &[Blob]) -> Option<Vec<Vec<u8>>> {
let mut fes =
blobs.iter().flat_map(|blob| blob.chunks(32).map(WholeFe::new)).map(Option::unwrap);
if blobs.len() > MAX_BLOBS_PER_BLOCK {
return None;
}

if blobs
.iter()
.flat_map(|blob| blob.chunks(FIELD_ELEMENT_BYTES).map(WholeFe::new))
.any(|fe| fe.is_none())
{
return None;
}

let mut fes = blobs
.iter()
.flat_map(|blob| blob.chunks(FIELD_ELEMENT_BYTES).map(WholeFe::new_unchecked));
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Previously it didn't work correctly because .map(WholeFe::new)).map(Option::unwrap) was executed lazily (when decode_one() reached the wrong WholeFe, it would panic).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I decided to check this in a non-lazy way to do not pass Option<Option<Option<Option<WholeFe>> to decode_one().


let mut res = Vec::new();
loop {
Expand Down Expand Up @@ -434,6 +450,17 @@ mod tests {
assert_eq!(decoded, data);
}

#[test]
fn big_ingestion_strategy() {
let data = vec![1u8; 126_945];
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Blob has size of 128 * 1024 bytes. First 32 bytes are used as length, thus leaving 4095 FEs / 4096 FEs. This constant was calculated as 128 * 1024 - 32 - 4095 (4095 zeros in each FE).

let builder = SidecarBuilder::<SimpleCoder>::from_slice(&data);

let blobs = builder.take();
let decoded = SimpleCoder.decode_all(&blobs).unwrap().concat();

assert_eq!(decoded, data);
}

#[test]
fn it_ingests() {
// test ingesting a lot of data.
Expand Down
2 changes: 1 addition & 1 deletion crates/eips/src/eip4844/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub const BLS_MODULUS_BYTES: B256 =
pub const BLS_MODULUS: U256 = U256::from_be_bytes(BLS_MODULUS_BYTES.0);

/// Size a single field element in bytes.
pub const FIELD_ELEMENT_BYTES: u64 = 32;
mattsse marked this conversation as resolved.
Show resolved Hide resolved
pub const FIELD_ELEMENT_BYTES: usize = 32;

/// How many field elements are stored in a single data blob.
pub const FIELD_ELEMENTS_PER_BLOB: u64 = 4096;
Expand Down
12 changes: 7 additions & 5 deletions crates/eips/src/eip4844/utils.rs
Copy link
Member

Choose a reason for hiding this comment

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

no functional changes here, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I could leave it u64, but then I'd have to make as usize in all usages, which isn't very convenient. Maybe it makes sense to introduce FIELD_ELEMENT_BYTES_USIZE: usize = FIELD_ELEMENT_BYTES as usize? Yes, there are no other functional changes.

Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
//!
//! [`SidecarCoder`]: crate::eip4844::builder::SidecarCoder

use crate::eip4844::USABLE_BITS_PER_FIELD_ELEMENT;
use crate::eip4844::{FIELD_ELEMENT_BYTES, USABLE_BITS_PER_FIELD_ELEMENT};

/// Determine whether a slice of bytes can be contained in a field element.
pub const fn fits_in_fe(data: &[u8]) -> bool {
const FIELD_ELEMENT_BYTES_PLUS_ONE: usize = FIELD_ELEMENT_BYTES + 1;

match data.len() {
33.. => false,
32 => data[0] & 0b1100_0000 == 0, // first two bits must be zero
FIELD_ELEMENT_BYTES_PLUS_ONE.. => false,
FIELD_ELEMENT_BYTES => data[0] & 0b1100_0000 == 0, // first two bits must be zero
_ => true,
}
}
Expand All @@ -30,14 +32,14 @@ pub const fn minimum_fe(data: &[u8]) -> usize {
pub struct WholeFe<'a>(&'a [u8]);

impl<'a> WholeFe<'a> {
const fn new_unchecked(data: &'a [u8]) -> Self {
pub(crate) const fn new_unchecked(data: &'a [u8]) -> Self {
Self(data)
}

/// Instantiate a new `WholeFe` from a slice of bytes, if it is a valid
/// field element.
pub const fn new(data: &'a [u8]) -> Option<Self> {
if data.len() == 32 && fits_in_fe(data) {
if data.len() == FIELD_ELEMENT_BYTES && fits_in_fe(data) {
Some(Self::new_unchecked(data))
} else {
None
Expand Down
Loading