1use 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#[cfg(feature = "kzg")]
19pub(crate) const VERSIONED_HASH_VERSION_KZG: u8 = 0x01;
20
21#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct IndexedBlobHash {
25 pub index: u64,
27 pub hash: B256,
29}
30
31#[derive(Clone, Default, PartialEq, Eq, Hash)]
35#[repr(C)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37#[doc(alias = "BlobTxSidecar")]
38pub struct BlobTransactionSidecar {
39 #[cfg_attr(
41 all(debug_assertions, feature = "serde"),
42 serde(deserialize_with = "deserialize_blobs")
43 )]
44 pub blobs: Vec<Blob>,
45 pub commitments: Vec<Bytes48>,
47 pub proofs: Vec<Bytes48>,
49}
50
51impl core::fmt::Debug for BlobTransactionSidecar {
52 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
53 f.debug_struct("BlobTransactionSidecar")
54 .field("blobs", &self.blobs.len())
55 .field("commitments", &self.commitments)
56 .field("proofs", &self.proofs)
57 .finish()
58 }
59}
60
61impl BlobTransactionSidecar {
62 pub fn match_versioned_hashes<'a>(
68 &'a self,
69 versioned_hashes: &'a [B256],
70 ) -> impl Iterator<Item = (usize, BlobAndProofV1)> + 'a {
71 self.versioned_hashes().enumerate().flat_map(move |(i, blob_versioned_hash)| {
72 versioned_hashes.iter().enumerate().filter_map(move |(j, target_hash)| {
73 if blob_versioned_hash == *target_hash {
74 if let Some((blob, proof)) =
75 self.blobs.get(i).copied().zip(self.proofs.get(i).copied())
76 {
77 return Some((j, BlobAndProofV1 { blob: Box::new(blob), proof }));
78 }
79 }
80 None
81 })
82 })
83 }
84}
85
86impl IntoIterator for BlobTransactionSidecar {
87 type Item = BlobTransactionSidecarItem;
88 type IntoIter = alloc::vec::IntoIter<BlobTransactionSidecarItem>;
89
90 fn into_iter(self) -> Self::IntoIter {
91 self.blobs
92 .into_iter()
93 .zip(self.commitments)
94 .zip(self.proofs)
95 .enumerate()
96 .map(|(index, ((blob, commitment), proof))| BlobTransactionSidecarItem {
97 index: index as u64,
98 blob: Box::new(blob),
99 kzg_commitment: commitment,
100 kzg_proof: proof,
101 })
102 .collect::<Vec<_>>()
103 .into_iter()
104 }
105}
106
107#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
109#[repr(C)]
110#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
111pub struct BlobTransactionSidecarItem {
112 #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
114 pub index: u64,
115 #[cfg_attr(feature = "serde", serde(deserialize_with = "super::deserialize_blob"))]
117 pub blob: Box<Blob>,
118 pub kzg_commitment: Bytes48,
120 pub kzg_proof: Bytes48,
122}
123
124#[cfg(feature = "kzg")]
125impl BlobTransactionSidecarItem {
126 pub fn to_kzg_versioned_hash(&self) -> [u8; 32] {
128 use sha2::Digest;
129 let commitment = self.kzg_commitment.as_slice();
130 let mut hash: [u8; 32] = sha2::Sha256::digest(commitment).into();
131 hash[0] = VERSIONED_HASH_VERSION_KZG;
132 hash
133 }
134
135 pub fn verify_blob_kzg_proof(&self) -> Result<(), BlobTransactionValidationError> {
137 let binding = crate::eip4844::env_settings::EnvKzgSettings::Default;
138 let settings = binding.get();
139
140 let blob = c_kzg::Blob::from_bytes(self.blob.as_slice())
141 .map_err(BlobTransactionValidationError::KZGError)?;
142
143 let commitment = c_kzg::Bytes48::from_bytes(self.kzg_commitment.as_slice())
144 .map_err(BlobTransactionValidationError::KZGError)?;
145
146 let proof = c_kzg::Bytes48::from_bytes(self.kzg_proof.as_slice())
147 .map_err(BlobTransactionValidationError::KZGError)?;
148
149 let result = settings
150 .verify_blob_kzg_proof(&blob, &commitment, &proof)
151 .map_err(BlobTransactionValidationError::KZGError)?;
152
153 result.then_some(()).ok_or(BlobTransactionValidationError::InvalidProof)
154 }
155
156 pub fn verify_blob(
158 &self,
159 hash: &IndexedBlobHash,
160 ) -> Result<(), BlobTransactionValidationError> {
161 if self.index != hash.index {
162 let blob_hash_part = B256::from_slice(&self.blob[0..32]);
163 return Err(BlobTransactionValidationError::WrongVersionedHash {
164 have: blob_hash_part,
165 expected: hash.hash,
166 });
167 }
168
169 let computed_hash = self.to_kzg_versioned_hash();
170 if computed_hash != hash.hash {
171 return Err(BlobTransactionValidationError::WrongVersionedHash {
172 have: computed_hash.into(),
173 expected: hash.hash,
174 });
175 }
176
177 self.verify_blob_kzg_proof()
178 }
179}
180
181#[cfg(any(test, feature = "arbitrary"))]
182impl<'a> arbitrary::Arbitrary<'a> for BlobTransactionSidecar {
183 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
184 let num_blobs = u.int_in_range(1..=MAX_BLOBS_PER_BLOCK_DENCUN)?;
185 let mut blobs = Vec::with_capacity(num_blobs);
186 for _ in 0..num_blobs {
187 blobs.push(Blob::arbitrary(u)?);
188 }
189
190 let mut commitments = Vec::with_capacity(num_blobs);
191 let mut proofs = Vec::with_capacity(num_blobs);
192 for _ in 0..num_blobs {
193 commitments.push(Bytes48::arbitrary(u)?);
194 proofs.push(Bytes48::arbitrary(u)?);
195 }
196
197 Ok(Self { blobs, commitments, proofs })
198 }
199}
200
201impl BlobTransactionSidecar {
202 pub const fn new(blobs: Vec<Blob>, commitments: Vec<Bytes48>, proofs: Vec<Bytes48>) -> Self {
204 Self { blobs, commitments, proofs }
205 }
206
207 #[cfg(feature = "kzg")]
209 pub fn from_kzg(
210 blobs: Vec<c_kzg::Blob>,
211 commitments: Vec<c_kzg::Bytes48>,
212 proofs: Vec<c_kzg::Bytes48>,
213 ) -> Self {
214 unsafe fn transmute_vec<U, T>(input: Vec<T>) -> Vec<U> {
216 let mut v = core::mem::ManuallyDrop::new(input);
217 Vec::from_raw_parts(v.as_mut_ptr() as *mut U, v.len(), v.capacity())
218 }
219
220 unsafe {
222 let blobs = transmute_vec::<Blob, c_kzg::Blob>(blobs);
223 let commitments = transmute_vec::<Bytes48, c_kzg::Bytes48>(commitments);
224 let proofs = transmute_vec::<Bytes48, c_kzg::Bytes48>(proofs);
225 Self { blobs, commitments, proofs }
226 }
227 }
228
229 #[cfg(feature = "kzg")]
243 pub fn validate(
244 &self,
245 blob_versioned_hashes: &[B256],
246 proof_settings: &c_kzg::KzgSettings,
247 ) -> Result<(), BlobTransactionValidationError> {
248 if blob_versioned_hashes.len() != self.commitments.len() {
250 return Err(c_kzg::Error::MismatchLength(format!(
251 "There are {} versioned commitment hashes and {} commitments",
252 blob_versioned_hashes.len(),
253 self.commitments.len()
254 ))
255 .into());
256 }
257
258 for (versioned_hash, commitment) in
260 blob_versioned_hashes.iter().zip(self.commitments.iter())
261 {
262 let commitment = c_kzg::KzgCommitment::from(commitment.0);
263
264 let calculated_versioned_hash = kzg_to_versioned_hash(commitment.as_slice());
266 if *versioned_hash != calculated_versioned_hash {
267 return Err(BlobTransactionValidationError::WrongVersionedHash {
268 have: *versioned_hash,
269 expected: calculated_versioned_hash,
270 });
271 }
272 }
273
274 let res = unsafe {
276 proof_settings.verify_blob_kzg_proof_batch(
277 core::mem::transmute::<&[Blob], &[c_kzg::Blob]>(self.blobs.as_slice()),
279 core::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(self.commitments.as_slice()),
281 core::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(self.proofs.as_slice()),
283 )
284 }
285 .map_err(BlobTransactionValidationError::KZGError)?;
286
287 res.then_some(()).ok_or(BlobTransactionValidationError::InvalidProof)
288 }
289
290 pub fn versioned_hashes(&self) -> impl Iterator<Item = B256> + '_ {
292 self.commitments.iter().map(|c| kzg_to_versioned_hash(c.as_slice()))
293 }
294
295 pub fn versioned_hash_for_blob(&self, blob_index: usize) -> Option<B256> {
298 self.commitments.get(blob_index).map(|c| kzg_to_versioned_hash(c.as_slice()))
299 }
300
301 #[inline]
303 pub fn size(&self) -> usize {
304 self.blobs.len() * BYTES_PER_BLOB + self.commitments.len() * BYTES_PER_COMMITMENT + self.proofs.len() * BYTES_PER_PROOF }
308
309 #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
313 pub fn try_from_blobs_hex<I, B>(blobs: I) -> Result<Self, c_kzg::Error>
314 where
315 I: IntoIterator<Item = B>,
316 B: AsRef<str>,
317 {
318 let mut b = Vec::new();
319 for blob in blobs {
320 b.push(c_kzg::Blob::from_hex(blob.as_ref())?)
321 }
322 Self::try_from_blobs(b)
323 }
324
325 #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
329 pub fn try_from_blobs_bytes<I, B>(blobs: I) -> Result<Self, c_kzg::Error>
330 where
331 I: IntoIterator<Item = B>,
332 B: AsRef<[u8]>,
333 {
334 let mut b = Vec::new();
335 for blob in blobs {
336 b.push(c_kzg::Blob::from_bytes(blob.as_ref())?)
337 }
338 Self::try_from_blobs(b)
339 }
340
341 #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
343 pub fn try_from_blobs(blobs: Vec<c_kzg::Blob>) -> Result<Self, c_kzg::Error> {
344 use crate::eip4844::env_settings::EnvKzgSettings;
345
346 let kzg_settings = EnvKzgSettings::Default;
347
348 let commitments = blobs
349 .iter()
350 .map(|blob| {
351 kzg_settings.get().blob_to_kzg_commitment(&blob.clone()).map(|blob| blob.to_bytes())
352 })
353 .collect::<Result<Vec<_>, _>>()?;
354
355 let proofs = blobs
356 .iter()
357 .zip(commitments.iter())
358 .map(|(blob, commitment)| {
359 kzg_settings
360 .get()
361 .compute_blob_kzg_proof(blob, commitment)
362 .map(|blob| blob.to_bytes())
363 })
364 .collect::<Result<Vec<_>, _>>()?;
365
366 Ok(Self::from_kzg(blobs, commitments, proofs))
367 }
368
369 #[doc(hidden)]
372 pub fn rlp_encoded_fields_length(&self) -> usize {
373 self.blobs.length() + self.commitments.length() + self.proofs.length()
374 }
375
376 #[inline]
383 #[doc(hidden)]
384 pub fn rlp_encode_fields(&self, out: &mut dyn BufMut) {
385 self.blobs.encode(out);
387 self.commitments.encode(out);
388 self.proofs.encode(out);
389 }
390
391 fn rlp_header(&self) -> Header {
393 Header { list: true, payload_length: self.rlp_encoded_fields_length() }
394 }
395
396 pub fn rlp_encoded_length(&self) -> usize {
399 self.rlp_header().length() + self.rlp_encoded_fields_length()
400 }
401
402 pub fn rlp_encode(&self, out: &mut dyn BufMut) {
404 self.rlp_header().encode(out);
405 self.rlp_encode_fields(out);
406 }
407
408 #[doc(hidden)]
410 pub fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
411 Ok(Self {
412 blobs: Decodable::decode(buf)?,
413 commitments: Decodable::decode(buf)?,
414 proofs: Decodable::decode(buf)?,
415 })
416 }
417
418 pub fn rlp_decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
420 let header = Header::decode(buf)?;
421 if !header.list {
422 return Err(alloy_rlp::Error::UnexpectedString);
423 }
424 if buf.len() < header.payload_length {
425 return Err(alloy_rlp::Error::InputTooShort);
426 }
427 let remaining = buf.len();
428 let this = Self::rlp_decode_fields(buf)?;
429
430 if buf.len() + header.payload_length != remaining {
431 return Err(alloy_rlp::Error::UnexpectedLength);
432 }
433
434 Ok(this)
435 }
436}
437
438impl Encodable for BlobTransactionSidecar {
439 fn encode(&self, out: &mut dyn BufMut) {
441 self.rlp_encode(out);
442 }
443
444 fn length(&self) -> usize {
445 self.rlp_encoded_length()
446 }
447}
448
449impl Decodable for BlobTransactionSidecar {
450 fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
452 Self::rlp_decode(buf)
453 }
454}
455
456impl Encodable7594 for BlobTransactionSidecar {
457 fn encode_7594_len(&self) -> usize {
458 self.rlp_encoded_fields_length()
459 }
460
461 fn encode_7594(&self, out: &mut dyn BufMut) {
462 self.rlp_encode_fields(out);
463 }
464}
465
466impl Decodable7594 for BlobTransactionSidecar {
467 fn decode_7594(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
468 Self::rlp_decode_fields(buf)
469 }
470}
471
472#[cfg(all(debug_assertions, feature = "serde"))]
474pub(crate) fn deserialize_blobs<'de, D>(deserializer: D) -> Result<Vec<Blob>, D::Error>
475where
476 D: serde::de::Deserializer<'de>,
477{
478 use serde::Deserialize;
479
480 let raw_blobs = Vec::<alloy_primitives::Bytes>::deserialize(deserializer)?;
481 let mut blobs = Vec::with_capacity(raw_blobs.len());
482 for blob in raw_blobs {
483 blobs.push(Blob::try_from(blob.as_ref()).map_err(serde::de::Error::custom)?);
484 }
485 Ok(blobs)
486}
487
488#[derive(Debug)]
490#[cfg(feature = "kzg")]
491pub enum BlobTransactionValidationError {
492 InvalidProof,
494 KZGError(c_kzg::Error),
496 NotBlobTransaction(u8),
498 MissingSidecar,
500 WrongVersionedHash {
502 have: B256,
504 expected: B256,
506 },
507}
508
509#[cfg(feature = "kzg")]
510impl core::error::Error for BlobTransactionValidationError {}
511
512#[cfg(feature = "kzg")]
513impl core::fmt::Display for BlobTransactionValidationError {
514 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
515 match self {
516 Self::InvalidProof => f.write_str("invalid KZG proof"),
517 Self::KZGError(err) => {
518 write!(f, "KZG error: {err:?}")
519 }
520 Self::NotBlobTransaction(err) => {
521 write!(f, "unable to verify proof for non blob transaction: {err}")
522 }
523 Self::MissingSidecar => {
524 f.write_str("eip4844 tx variant without sidecar being used for verification.")
525 }
526 Self::WrongVersionedHash { have, expected } => {
527 write!(f, "wrong versioned hash: have {have}, expected {expected}")
528 }
529 }
530 }
531}
532
533#[cfg(feature = "kzg")]
534impl From<c_kzg::Error> for BlobTransactionValidationError {
535 fn from(source: c_kzg::Error) -> Self {
536 Self::KZGError(source)
537 }
538}
539
540#[cfg(test)]
541mod tests {
542 use super::*;
543 use arbitrary::Arbitrary;
544
545 #[test]
546 #[cfg(feature = "serde")]
547 fn deserialize_blob() {
548 let blob = BlobTransactionSidecar {
549 blobs: vec![Blob::default(), Blob::default(), Blob::default(), Blob::default()],
550 commitments: vec![
551 Bytes48::default(),
552 Bytes48::default(),
553 Bytes48::default(),
554 Bytes48::default(),
555 ],
556 proofs: vec![
557 Bytes48::default(),
558 Bytes48::default(),
559 Bytes48::default(),
560 Bytes48::default(),
561 ],
562 };
563
564 let s = serde_json::to_string(&blob).unwrap();
565 let deserialized: BlobTransactionSidecar = serde_json::from_str(&s).unwrap();
566 assert_eq!(blob, deserialized);
567 }
568
569 #[test]
570 fn test_arbitrary_blob() {
571 let mut unstructured = arbitrary::Unstructured::new(b"unstructured blob");
572 let _blob = BlobTransactionSidecar::arbitrary(&mut unstructured).unwrap();
573 }
574
575 #[test]
576 #[cfg(feature = "serde")]
577 fn test_blob_item_serde_roundtrip() {
578 let blob_item = BlobTransactionSidecarItem {
579 index: 0,
580 blob: Box::new(Blob::default()),
581 kzg_commitment: Bytes48::default(),
582 kzg_proof: Bytes48::default(),
583 };
584
585 let s = serde_json::to_string(&blob_item).unwrap();
586 let deserialized: BlobTransactionSidecarItem = serde_json::from_str(&s).unwrap();
587 assert_eq!(blob_item, deserialized);
588 }
589}