alloy_eips/eip4844/
sidecar.rs

1//! EIP-4844 sidecar type
2
3use crate::{
4    eip4844::{
5        kzg_to_versioned_hash, Blob, BlobAndProofV1, Bytes48, BYTES_PER_BLOB, BYTES_PER_COMMITMENT,
6        BYTES_PER_PROOF,
7    },
8    eip7594::{Decodable7594, Encodable7594},
9};
10use alloc::{boxed::Box, vec::Vec};
11use alloy_primitives::{bytes::BufMut, B256};
12use alloy_rlp::{Decodable, Encodable, Header};
13
14#[cfg(any(test, feature = "arbitrary"))]
15use crate::eip4844::MAX_BLOBS_PER_BLOCK_DENCUN;
16
17/// The versioned hash version for KZG.
18#[cfg(feature = "kzg")]
19pub(crate) const VERSIONED_HASH_VERSION_KZG: u8 = 0x01;
20
21/// A Blob hash
22#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct IndexedBlobHash {
25    /// The index of the blob
26    pub index: u64,
27    /// The hash of the blob
28    pub hash: B256,
29}
30
31/// This represents a set of blobs, and its corresponding commitments and proofs.
32///
33/// This type encodes and decodes the fields without an rlp header.
34#[derive(Clone, Default, PartialEq, Eq, Hash)]
35#[repr(C)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
38#[doc(alias = "BlobTxSidecar")]
39pub struct BlobTransactionSidecar {
40    /// The blob data.
41    #[cfg_attr(feature = "serde", serde(deserialize_with = "crate::eip4844::deserialize_blobs"))]
42    pub blobs: Vec<Blob>,
43    /// The blob commitments.
44    pub commitments: Vec<Bytes48>,
45    /// The blob proofs.
46    pub proofs: Vec<Bytes48>,
47}
48
49impl core::fmt::Debug for BlobTransactionSidecar {
50    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
51        f.debug_struct("BlobTransactionSidecar")
52            .field("blobs", &self.blobs.len())
53            .field("commitments", &self.commitments)
54            .field("proofs", &self.proofs)
55            .finish()
56    }
57}
58
59impl BlobTransactionSidecar {
60    /// Matches versioned hashes and returns an iterator of (index, [`BlobAndProofV1`]) pairs
61    /// where index is the position in `versioned_hashes` that matched the versioned hash in the
62    /// sidecar.
63    ///
64    /// This is used for the `engine_getBlobsV1` RPC endpoint of the engine API
65    pub fn match_versioned_hashes<'a>(
66        &'a self,
67        versioned_hashes: &'a [B256],
68    ) -> impl Iterator<Item = (usize, BlobAndProofV1)> + 'a {
69        self.versioned_hashes().enumerate().flat_map(move |(i, blob_versioned_hash)| {
70            versioned_hashes.iter().enumerate().filter_map(move |(j, target_hash)| {
71                if blob_versioned_hash == *target_hash {
72                    if let Some((blob, proof)) =
73                        self.blobs.get(i).copied().zip(self.proofs.get(i).copied())
74                    {
75                        return Some((j, BlobAndProofV1 { blob: Box::new(blob), proof }));
76                    }
77                }
78                None
79            })
80        })
81    }
82
83    /// Converts this EIP-4844 sidecar into an EIP-7594 sidecar.
84    ///
85    /// This requires computing cell KZG proofs from the blob data using the KZG trusted setup.
86    /// Each blob produces `CELLS_PER_EXT_BLOB` cell proofs.
87    #[cfg(feature = "kzg")]
88    pub fn try_into_7594(
89        self,
90        settings: &c_kzg::KzgSettings,
91    ) -> Result<crate::eip7594::BlobTransactionSidecarEip7594, c_kzg::Error> {
92        use crate::eip7594::CELLS_PER_EXT_BLOB;
93
94        let mut cell_proofs = Vec::with_capacity(self.blobs.len() * CELLS_PER_EXT_BLOB);
95
96        for blob in self.blobs.iter() {
97            // SAFETY: Blob and c_kzg::Blob have the same memory layout
98            let blob_kzg = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(blob) };
99
100            // Compute cells and their KZG proofs for this blob
101            let (_cells, kzg_proofs) = settings.compute_cells_and_kzg_proofs(blob_kzg)?;
102
103            // SAFETY: same size
104            unsafe {
105                for kzg_proof in kzg_proofs.iter() {
106                    cell_proofs.push(core::mem::transmute::<c_kzg::Bytes48, Bytes48>(
107                        kzg_proof.to_bytes(),
108                    ));
109                }
110            }
111        }
112
113        Ok(crate::eip7594::BlobTransactionSidecarEip7594::new(
114            self.blobs,
115            self.commitments,
116            cell_proofs,
117        ))
118    }
119}
120
121impl IntoIterator for BlobTransactionSidecar {
122    type Item = BlobTransactionSidecarItem;
123    type IntoIter = alloc::vec::IntoIter<BlobTransactionSidecarItem>;
124
125    fn into_iter(self) -> Self::IntoIter {
126        self.blobs
127            .into_iter()
128            .zip(self.commitments)
129            .zip(self.proofs)
130            .enumerate()
131            .map(|(index, ((blob, commitment), proof))| BlobTransactionSidecarItem {
132                index: index as u64,
133                blob: Box::new(blob),
134                kzg_commitment: commitment,
135                kzg_proof: proof,
136            })
137            .collect::<Vec<_>>()
138            .into_iter()
139    }
140}
141
142/// A single blob sidecar.
143#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
144#[repr(C)]
145#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
146pub struct BlobTransactionSidecarItem {
147    /// The index of this item within the [BlobTransactionSidecar].
148    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
149    pub index: u64,
150    /// The blob in this sidecar item.
151    #[cfg_attr(feature = "serde", serde(deserialize_with = "super::deserialize_blob"))]
152    pub blob: Box<Blob>,
153    /// The KZG commitment.
154    pub kzg_commitment: Bytes48,
155    /// The KZG proof.
156    pub kzg_proof: Bytes48,
157}
158
159#[cfg(feature = "kzg")]
160impl BlobTransactionSidecarItem {
161    /// `VERSIONED_HASH_VERSION_KZG ++ sha256(commitment)[1..]`
162    pub fn to_kzg_versioned_hash(&self) -> [u8; 32] {
163        use sha2::Digest;
164        let commitment = self.kzg_commitment.as_slice();
165        let mut hash: [u8; 32] = sha2::Sha256::digest(commitment).into();
166        hash[0] = VERSIONED_HASH_VERSION_KZG;
167        hash
168    }
169
170    /// Verifies the KZG proof of a blob to ensure its integrity and correctness.
171    pub fn verify_blob_kzg_proof(&self) -> Result<(), BlobTransactionValidationError> {
172        let binding = crate::eip4844::env_settings::EnvKzgSettings::Default;
173        let settings = binding.get();
174
175        let blob = c_kzg::Blob::from_bytes(self.blob.as_slice())
176            .map_err(BlobTransactionValidationError::KZGError)?;
177
178        let commitment = c_kzg::Bytes48::from_bytes(self.kzg_commitment.as_slice())
179            .map_err(BlobTransactionValidationError::KZGError)?;
180
181        let proof = c_kzg::Bytes48::from_bytes(self.kzg_proof.as_slice())
182            .map_err(BlobTransactionValidationError::KZGError)?;
183
184        let result = settings
185            .verify_blob_kzg_proof(&blob, &commitment, &proof)
186            .map_err(BlobTransactionValidationError::KZGError)?;
187
188        result.then_some(()).ok_or(BlobTransactionValidationError::InvalidProof)
189    }
190
191    /// Verify the blob sidecar against its [IndexedBlobHash].
192    pub fn verify_blob(
193        &self,
194        hash: &IndexedBlobHash,
195    ) -> Result<(), BlobTransactionValidationError> {
196        if self.index != hash.index {
197            let blob_hash_part = B256::from_slice(&self.blob[0..32]);
198            return Err(BlobTransactionValidationError::WrongVersionedHash {
199                have: blob_hash_part,
200                expected: hash.hash,
201            });
202        }
203
204        let computed_hash = self.to_kzg_versioned_hash();
205        if computed_hash != hash.hash {
206            return Err(BlobTransactionValidationError::WrongVersionedHash {
207                have: computed_hash.into(),
208                expected: hash.hash,
209            });
210        }
211
212        self.verify_blob_kzg_proof()
213    }
214}
215
216#[cfg(any(test, feature = "arbitrary"))]
217impl<'a> arbitrary::Arbitrary<'a> for BlobTransactionSidecar {
218    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
219        let num_blobs = u.int_in_range(1..=MAX_BLOBS_PER_BLOCK_DENCUN)?;
220        let mut blobs = Vec::with_capacity(num_blobs);
221        for _ in 0..num_blobs {
222            blobs.push(Blob::arbitrary(u)?);
223        }
224
225        let mut commitments = Vec::with_capacity(num_blobs);
226        let mut proofs = Vec::with_capacity(num_blobs);
227        for _ in 0..num_blobs {
228            commitments.push(Bytes48::arbitrary(u)?);
229            proofs.push(Bytes48::arbitrary(u)?);
230        }
231
232        Ok(Self { blobs, commitments, proofs })
233    }
234}
235
236impl BlobTransactionSidecar {
237    /// Constructs a new [BlobTransactionSidecar] from a set of blobs, commitments, and proofs.
238    pub const fn new(blobs: Vec<Blob>, commitments: Vec<Bytes48>, proofs: Vec<Bytes48>) -> Self {
239        Self { blobs, commitments, proofs }
240    }
241
242    /// Creates a new instance from the given KZG types.
243    #[cfg(feature = "kzg")]
244    pub fn from_kzg(
245        blobs: Vec<c_kzg::Blob>,
246        commitments: Vec<c_kzg::Bytes48>,
247        proofs: Vec<c_kzg::Bytes48>,
248    ) -> Self {
249        // transmutes the vec of items, see also [core::mem::transmute](https://doc.rust-lang.org/std/mem/fn.transmute.html)
250        unsafe fn transmute_vec<U, T>(input: Vec<T>) -> Vec<U> {
251            let mut v = core::mem::ManuallyDrop::new(input);
252            Vec::from_raw_parts(v.as_mut_ptr() as *mut U, v.len(), v.capacity())
253        }
254
255        // SAFETY: all types have the same size and alignment
256        unsafe {
257            let blobs = transmute_vec::<Blob, c_kzg::Blob>(blobs);
258            let commitments = transmute_vec::<Bytes48, c_kzg::Bytes48>(commitments);
259            let proofs = transmute_vec::<Bytes48, c_kzg::Bytes48>(proofs);
260            Self { blobs, commitments, proofs }
261        }
262    }
263
264    /// Verifies that the versioned hashes are valid for this sidecar's blob data, commitments, and
265    /// proofs.
266    ///
267    /// Takes as input the [KzgSettings](c_kzg::KzgSettings), which should contain the parameters
268    /// derived from the KZG trusted setup.
269    ///
270    /// This ensures that the blob transaction payload has the same number of blob data elements,
271    /// commitments, and proofs. Each blob data element is verified against its commitment and
272    /// proof.
273    ///
274    /// Returns [BlobTransactionValidationError::InvalidProof] if any blob KZG proof in the response
275    /// fails to verify, or if the versioned hashes in the transaction do not match the actual
276    /// commitment versioned hashes.
277    #[cfg(feature = "kzg")]
278    pub fn validate(
279        &self,
280        blob_versioned_hashes: &[B256],
281        proof_settings: &c_kzg::KzgSettings,
282    ) -> Result<(), BlobTransactionValidationError> {
283        // Ensure the versioned hashes and commitments have the same length.
284        if blob_versioned_hashes.len() != self.commitments.len() {
285            return Err(c_kzg::Error::MismatchLength(format!(
286                "There are {} versioned commitment hashes and {} commitments",
287                blob_versioned_hashes.len(),
288                self.commitments.len()
289            ))
290            .into());
291        }
292
293        // calculate versioned hashes by zipping & iterating
294        for (versioned_hash, commitment) in
295            blob_versioned_hashes.iter().zip(self.commitments.iter())
296        {
297            // calculate & verify versioned hash
298            let calculated_versioned_hash = kzg_to_versioned_hash(commitment.as_slice());
299            if *versioned_hash != calculated_versioned_hash {
300                return Err(BlobTransactionValidationError::WrongVersionedHash {
301                    have: *versioned_hash,
302                    expected: calculated_versioned_hash,
303                });
304            }
305        }
306
307        // SAFETY: ALL types have the same size
308        let res = unsafe {
309            proof_settings.verify_blob_kzg_proof_batch(
310                // blobs
311                core::mem::transmute::<&[Blob], &[c_kzg::Blob]>(self.blobs.as_slice()),
312                // commitments
313                core::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(self.commitments.as_slice()),
314                // proofs
315                core::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(self.proofs.as_slice()),
316            )
317        }
318        .map_err(BlobTransactionValidationError::KZGError)?;
319
320        res.then_some(()).ok_or(BlobTransactionValidationError::InvalidProof)
321    }
322
323    /// Returns an iterator over the versioned hashes of the commitments.
324    pub fn versioned_hashes(&self) -> VersionedHashIter<'_> {
325        VersionedHashIter::new(&self.commitments)
326    }
327
328    /// Returns the versioned hash for the blob at the given index, if it
329    /// exists.
330    pub fn versioned_hash_for_blob(&self, blob_index: usize) -> Option<B256> {
331        self.commitments.get(blob_index).map(|c| kzg_to_versioned_hash(c.as_slice()))
332    }
333
334    /// Returns the index of the versioned hash in the commitments vector.
335    pub fn versioned_hash_index(&self, hash: &B256) -> Option<usize> {
336        self.commitments
337            .iter()
338            .position(|commitment| kzg_to_versioned_hash(commitment.as_slice()) == *hash)
339    }
340
341    /// Returns the blob corresponding to the versioned hash, if it exists.
342    pub fn blob_by_versioned_hash(&self, hash: &B256) -> Option<&Blob> {
343        self.versioned_hash_index(hash).and_then(|index| self.blobs.get(index))
344    }
345
346    /// Calculates a size heuristic for the in-memory size of the [BlobTransactionSidecar].
347    #[inline]
348    pub const fn size(&self) -> usize {
349        self.blobs.len() * BYTES_PER_BLOB + // blobs
350            self.commitments.len() * BYTES_PER_COMMITMENT + // commitments
351            self.proofs.len() * BYTES_PER_PROOF // proofs
352    }
353
354    /// Tries to create a new [`BlobTransactionSidecar`] from the hex encoded blob str.
355    ///
356    /// See also [`Blob::from_hex`](c_kzg::Blob::from_hex)
357    #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
358    pub fn try_from_blobs_hex<I, B>(blobs: I) -> Result<Self, c_kzg::Error>
359    where
360        I: IntoIterator<Item = B>,
361        B: AsRef<str>,
362    {
363        let mut b = Vec::new();
364        for blob in blobs {
365            b.push(c_kzg::Blob::from_hex(blob.as_ref())?)
366        }
367        Self::try_from_blobs(b)
368    }
369
370    /// Tries to create a new [`BlobTransactionSidecar`] from the given blob bytes.
371    ///
372    /// See also [`Blob::from_bytes`](c_kzg::Blob::from_bytes)
373    #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
374    pub fn try_from_blobs_bytes<I, B>(blobs: I) -> Result<Self, c_kzg::Error>
375    where
376        I: IntoIterator<Item = B>,
377        B: AsRef<[u8]>,
378    {
379        let mut b = Vec::new();
380        for blob in blobs {
381            b.push(c_kzg::Blob::from_bytes(blob.as_ref())?)
382        }
383        Self::try_from_blobs(b)
384    }
385
386    /// Tries to create a new [`BlobTransactionSidecar`] from the given blobs.
387    ///
388    /// This uses the global/default KZG settings, see also
389    /// [`EnvKzgSettings::Default`](crate::eip4844::env_settings::EnvKzgSettings).
390    #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
391    pub fn try_from_blobs(blobs: Vec<c_kzg::Blob>) -> Result<Self, c_kzg::Error> {
392        use crate::eip4844::env_settings::EnvKzgSettings;
393
394        let kzg_settings = EnvKzgSettings::Default;
395
396        let commitments = blobs
397            .iter()
398            .map(|blob| {
399                kzg_settings.get().blob_to_kzg_commitment(&blob.clone()).map(|blob| blob.to_bytes())
400            })
401            .collect::<Result<Vec<_>, _>>()?;
402
403        let proofs = blobs
404            .iter()
405            .zip(commitments.iter())
406            .map(|(blob, commitment)| {
407                kzg_settings
408                    .get()
409                    .compute_blob_kzg_proof(blob, commitment)
410                    .map(|blob| blob.to_bytes())
411            })
412            .collect::<Result<Vec<_>, _>>()?;
413
414        Ok(Self::from_kzg(blobs, commitments, proofs))
415    }
416
417    /// Outputs the RLP length of the [BlobTransactionSidecar] fields, without
418    /// a RLP header.
419    #[doc(hidden)]
420    pub fn rlp_encoded_fields_length(&self) -> usize {
421        self.blobs.length() + self.commitments.length() + self.proofs.length()
422    }
423
424    /// Encodes the inner [BlobTransactionSidecar] fields as RLP bytes, __without__ a RLP header.
425    ///
426    /// This encodes the fields in the following order:
427    /// - `blobs`
428    /// - `commitments`
429    /// - `proofs`
430    #[inline]
431    #[doc(hidden)]
432    pub fn rlp_encode_fields(&self, out: &mut dyn BufMut) {
433        // Encode the blobs, commitments, and proofs
434        self.blobs.encode(out);
435        self.commitments.encode(out);
436        self.proofs.encode(out);
437    }
438
439    /// Creates an RLP header for the [BlobTransactionSidecar].
440    fn rlp_header(&self) -> Header {
441        Header { list: true, payload_length: self.rlp_encoded_fields_length() }
442    }
443
444    /// Calculates the length of the [BlobTransactionSidecar] when encoded as
445    /// RLP.
446    pub fn rlp_encoded_length(&self) -> usize {
447        self.rlp_header().length() + self.rlp_encoded_fields_length()
448    }
449
450    /// Encodes the [BlobTransactionSidecar] as RLP bytes.
451    pub fn rlp_encode(&self, out: &mut dyn BufMut) {
452        self.rlp_header().encode(out);
453        self.rlp_encode_fields(out);
454    }
455
456    /// RLP decode the fields of a [BlobTransactionSidecar].
457    #[doc(hidden)]
458    pub fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
459        Ok(Self {
460            blobs: Decodable::decode(buf)?,
461            commitments: Decodable::decode(buf)?,
462            proofs: Decodable::decode(buf)?,
463        })
464    }
465
466    /// Decodes the [BlobTransactionSidecar] from RLP bytes.
467    pub fn rlp_decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
468        let header = Header::decode(buf)?;
469        if !header.list {
470            return Err(alloy_rlp::Error::UnexpectedString);
471        }
472        if buf.len() < header.payload_length {
473            return Err(alloy_rlp::Error::InputTooShort);
474        }
475        let remaining = buf.len();
476        let this = Self::rlp_decode_fields(buf)?;
477
478        if buf.len() + header.payload_length != remaining {
479            return Err(alloy_rlp::Error::UnexpectedLength);
480        }
481
482        Ok(this)
483    }
484}
485
486impl Encodable for BlobTransactionSidecar {
487    /// Encodes the inner [BlobTransactionSidecar] fields as RLP bytes, without a RLP header.
488    fn encode(&self, out: &mut dyn BufMut) {
489        self.rlp_encode(out);
490    }
491
492    fn length(&self) -> usize {
493        self.rlp_encoded_length()
494    }
495}
496
497impl Decodable for BlobTransactionSidecar {
498    /// Decodes the inner [BlobTransactionSidecar] fields from RLP bytes, without a RLP header.
499    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
500        Self::rlp_decode(buf)
501    }
502}
503
504impl Encodable7594 for BlobTransactionSidecar {
505    fn encode_7594_len(&self) -> usize {
506        self.rlp_encoded_fields_length()
507    }
508
509    fn encode_7594(&self, out: &mut dyn BufMut) {
510        self.rlp_encode_fields(out);
511    }
512}
513
514impl Decodable7594 for BlobTransactionSidecar {
515    fn decode_7594(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
516        Self::rlp_decode_fields(buf)
517    }
518}
519
520/// Helper function to deserialize boxed blobs from an existing [`MapAccess`]
521///
522/// [`MapAccess`]: serde::de::MapAccess
523#[cfg(all(debug_assertions, feature = "serde"))]
524pub(crate) fn deserialize_blobs_map<'de, M: serde::de::MapAccess<'de>>(
525    map_access: &mut M,
526) -> Result<Vec<Blob>, M::Error> {
527    let raw_blobs: Vec<alloy_primitives::Bytes> = map_access.next_value()?;
528    let mut blobs = Vec::with_capacity(raw_blobs.len());
529    for blob in raw_blobs {
530        blobs.push(Blob::try_from(blob.as_ref()).map_err(serde::de::Error::custom)?);
531    }
532    Ok(blobs)
533}
534
535#[cfg(all(not(debug_assertions), feature = "serde"))]
536#[inline(always)]
537pub(crate) fn deserialize_blobs_map<'de, M: serde::de::MapAccess<'de>>(
538    map_access: &mut M,
539) -> Result<Vec<Blob>, M::Error> {
540    map_access.next_value()
541}
542
543/// An error that can occur when validating a [BlobTransactionSidecar::validate].
544#[derive(Debug)]
545#[cfg(feature = "kzg")]
546pub enum BlobTransactionValidationError {
547    /// Proof validation failed.
548    InvalidProof,
549    /// An error returned by [`c_kzg`].
550    KZGError(c_kzg::Error),
551    /// The inner transaction is not a blob transaction.
552    NotBlobTransaction(u8),
553    /// Error variant for thrown by EIP-4844 tx variants without a sidecar.
554    MissingSidecar,
555    /// The versioned hash is incorrect.
556    WrongVersionedHash {
557        /// The versioned hash we got
558        have: B256,
559        /// The versioned hash we expected
560        expected: B256,
561    },
562}
563
564#[cfg(feature = "kzg")]
565impl core::error::Error for BlobTransactionValidationError {}
566
567#[cfg(feature = "kzg")]
568impl core::fmt::Display for BlobTransactionValidationError {
569    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
570        match self {
571            Self::InvalidProof => f.write_str("invalid KZG proof"),
572            Self::KZGError(err) => {
573                write!(f, "KZG error: {err:?}")
574            }
575            Self::NotBlobTransaction(err) => {
576                write!(f, "unable to verify proof for non blob transaction: {err}")
577            }
578            Self::MissingSidecar => {
579                f.write_str("eip4844 tx variant without sidecar being used for verification.")
580            }
581            Self::WrongVersionedHash { have, expected } => {
582                write!(f, "wrong versioned hash: have {have}, expected {expected}")
583            }
584        }
585    }
586}
587
588#[cfg(feature = "kzg")]
589impl From<c_kzg::Error> for BlobTransactionValidationError {
590    fn from(source: c_kzg::Error) -> Self {
591        Self::KZGError(source)
592    }
593}
594
595/// Iterator that returns versioned hashes from commitments.
596#[derive(Debug, Clone)]
597pub struct VersionedHashIter<'a> {
598    /// The iterator over KZG commitments from which versioned hashes are generated.
599    commitments: core::slice::Iter<'a, Bytes48>,
600}
601
602impl<'a> Iterator for VersionedHashIter<'a> {
603    type Item = B256;
604
605    fn next(&mut self) -> Option<Self::Item> {
606        self.commitments.next().map(|c| kzg_to_versioned_hash(c.as_slice()))
607    }
608}
609
610// Constructor method for VersionedHashIter
611impl<'a> VersionedHashIter<'a> {
612    /// Creates a new iterator over commitments to generate versioned hashes.
613    pub fn new(commitments: &'a [Bytes48]) -> Self {
614        Self { commitments: commitments.iter() }
615    }
616}
617
618#[cfg(test)]
619mod tests {
620    use super::*;
621    use arbitrary::Arbitrary;
622
623    #[test]
624    #[cfg(feature = "serde")]
625    fn deserialize_blob() {
626        let blob = BlobTransactionSidecar {
627            blobs: vec![Blob::default(), Blob::default(), Blob::default(), Blob::default()],
628            commitments: vec![
629                Bytes48::default(),
630                Bytes48::default(),
631                Bytes48::default(),
632                Bytes48::default(),
633            ],
634            proofs: vec![
635                Bytes48::default(),
636                Bytes48::default(),
637                Bytes48::default(),
638                Bytes48::default(),
639            ],
640        };
641
642        let s = serde_json::to_string(&blob).unwrap();
643        let deserialized: BlobTransactionSidecar = serde_json::from_str(&s).unwrap();
644        assert_eq!(blob, deserialized);
645    }
646
647    #[test]
648    fn test_arbitrary_blob() {
649        let mut unstructured = arbitrary::Unstructured::new(b"unstructured blob");
650        let _blob = BlobTransactionSidecar::arbitrary(&mut unstructured).unwrap();
651    }
652
653    #[test]
654    #[cfg(feature = "serde")]
655    fn test_blob_item_serde_roundtrip() {
656        let blob_item = BlobTransactionSidecarItem {
657            index: 0,
658            blob: Box::new(Blob::default()),
659            kzg_commitment: Bytes48::default(),
660            kzg_proof: Bytes48::default(),
661        };
662
663        let s = serde_json::to_string(&blob_item).unwrap();
664        let deserialized: BlobTransactionSidecarItem = serde_json::from_str(&s).unwrap();
665        assert_eq!(blob_item, deserialized);
666    }
667}