alloy_eips/eip4844/
sidecar.rs

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