1use 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#[cfg(feature = "kzg")]
16pub(crate) const VERSIONED_HASH_VERSION_KZG: u8 = 0x01;
17
18#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub struct IndexedBlobHash {
22 pub index: u64,
24 pub hash: B256,
26}
27
28#[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 #[cfg_attr(
38 all(debug_assertions, feature = "serde"),
39 serde(deserialize_with = "deserialize_blobs")
40 )]
41 pub blobs: Vec<Blob>,
42 pub commitments: Vec<Bytes48>,
44 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 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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
106#[repr(C)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
108pub struct BlobTransactionSidecarItem {
109 #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
111 pub index: u64,
112 #[cfg_attr(feature = "serde", serde(deserialize_with = "super::deserialize_blob"))]
114 pub blob: Box<Blob>,
115 pub kzg_commitment: Bytes48,
117 pub kzg_proof: Bytes48,
119}
120
121#[cfg(feature = "kzg")]
122impl BlobTransactionSidecarItem {
123 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 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 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 pub const fn new(blobs: Vec<Blob>, commitments: Vec<Bytes48>, proofs: Vec<Bytes48>) -> Self {
201 Self { blobs, commitments, proofs }
202 }
203
204 #[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 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 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 #[cfg(feature = "kzg")]
240 pub fn validate(
241 &self,
242 blob_versioned_hashes: &[B256],
243 proof_settings: &c_kzg::KzgSettings,
244 ) -> Result<(), BlobTransactionValidationError> {
245 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 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 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 let res = unsafe {
273 proof_settings.verify_blob_kzg_proof_batch(
274 core::mem::transmute::<&[Blob], &[c_kzg::Blob]>(self.blobs.as_slice()),
276 core::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(self.commitments.as_slice()),
278 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 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 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 #[inline]
300 pub fn size(&self) -> usize {
301 self.blobs.len() * BYTES_PER_BLOB + self.commitments.len() * BYTES_PER_COMMITMENT + self.proofs.len() * BYTES_PER_PROOF }
305
306 #[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 #[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 #[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 #[doc(hidden)]
369 pub fn rlp_encoded_fields_length(&self) -> usize {
370 self.blobs.length() + self.commitments.length() + self.proofs.length()
371 }
372
373 #[inline]
380 #[doc(hidden)]
381 pub fn rlp_encode_fields(&self, out: &mut dyn BufMut) {
382 self.blobs.encode(out);
384 self.commitments.encode(out);
385 self.proofs.encode(out);
386 }
387
388 fn rlp_header(&self) -> Header {
390 Header { list: true, payload_length: self.rlp_encoded_fields_length() }
391 }
392
393 pub fn rlp_encoded_length(&self) -> usize {
396 self.rlp_header().length() + self.rlp_encoded_fields_length()
397 }
398
399 pub fn rlp_encode(&self, out: &mut dyn BufMut) {
401 self.rlp_header().encode(out);
402 self.rlp_encode_fields(out);
403 }
404
405 #[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 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 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 fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
449 Self::rlp_decode(buf)
450 }
451}
452
453#[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#[derive(Debug)]
471#[cfg(feature = "kzg")]
472pub enum BlobTransactionValidationError {
473 InvalidProof,
475 KZGError(c_kzg::Error),
477 NotBlobTransaction(u8),
479 MissingSidecar,
481 WrongVersionedHash {
483 have: B256,
485 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}