alloy-eips 2.0.4

Ethereum Improvement Proprosal (EIP) implementations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
use crate::{
    eip4844::{
        Blob, BlobAndProofV2, BlobCellsAndProofsV1, BlobTransactionSidecar, Bytes48,
        BYTES_PER_BLOB, BYTES_PER_COMMITMENT, BYTES_PER_PROOF,
    },
    eip7594::{Cell, CELLS_PER_EXT_BLOB, EIP_7594_WRAPPER_VERSION},
};
use alloc::{boxed::Box, vec::Vec};
use alloy_primitives::{B128, B256};
use alloy_rlp::{BufMut, Decodable, Encodable, Header};

use super::{Decodable7594, Encodable7594};
#[cfg(feature = "kzg")]
use crate::eip4844::BlobTransactionValidationError;
use crate::eip4844::VersionedHashIter;

/// This represents a set of blobs, and its corresponding commitments and proofs.
/// Proof type depends on the sidecar variant.
///
/// This type encodes and decodes the fields without an rlp header.
#[derive(Clone, PartialEq, Eq, Hash, Debug, derive_more::From)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub enum BlobTransactionSidecarVariant {
    /// EIP-4844 style blob transaction sidecar.
    Eip4844(BlobTransactionSidecar),
    /// EIP-7594 style blob transaction sidecar with cell proofs.
    Eip7594(BlobTransactionSidecarEip7594),
}

impl Default for BlobTransactionSidecarVariant {
    fn default() -> Self {
        Self::Eip4844(BlobTransactionSidecar::default())
    }
}

impl BlobTransactionSidecarVariant {
    /// Returns true if this is a [`BlobTransactionSidecarVariant::Eip4844`].
    pub const fn is_eip4844(&self) -> bool {
        matches!(self, Self::Eip4844(_))
    }

    /// Returns true if this is a [`BlobTransactionSidecarVariant::Eip7594`].
    pub const fn is_eip7594(&self) -> bool {
        matches!(self, Self::Eip7594(_))
    }

    /// Returns the EIP-4844 sidecar if it is [`Self::Eip4844`].
    pub const fn as_eip4844(&self) -> Option<&BlobTransactionSidecar> {
        match self {
            Self::Eip4844(sidecar) => Some(sidecar),
            _ => None,
        }
    }

    /// Returns the EIP-7594 sidecar if it is [`Self::Eip7594`].
    pub const fn as_eip7594(&self) -> Option<&BlobTransactionSidecarEip7594> {
        match self {
            Self::Eip7594(sidecar) => Some(sidecar),
            _ => None,
        }
    }

    /// Converts into EIP-4844 sidecar if it is [`Self::Eip4844`].
    pub fn into_eip4844(self) -> Option<BlobTransactionSidecar> {
        match self {
            Self::Eip4844(sidecar) => Some(sidecar),
            _ => None,
        }
    }

    /// Converts the EIP-7594 sidecar if it is [`Self::Eip7594`].
    pub fn into_eip7594(self) -> Option<BlobTransactionSidecarEip7594> {
        match self {
            Self::Eip7594(sidecar) => Some(sidecar),
            _ => None,
        }
    }

    /// Get a reference to the blobs
    pub fn blobs(&self) -> &[Blob] {
        match self {
            Self::Eip4844(sidecar) => &sidecar.blobs,
            Self::Eip7594(sidecar) => &sidecar.blobs,
        }
    }

    /// Consume self and return the blobs
    pub fn into_blobs(self) -> Vec<Blob> {
        match self {
            Self::Eip4844(sidecar) => sidecar.blobs,
            Self::Eip7594(sidecar) => sidecar.blobs,
        }
    }

    /// Calculates a size heuristic for the in-memory size of the [BlobTransactionSidecarVariant].
    #[inline]
    pub const fn size(&self) -> usize {
        match self {
            Self::Eip4844(sidecar) => sidecar.size(),
            Self::Eip7594(sidecar) => sidecar.size(),
        }
    }

    /// Attempts to convert this sidecar into the EIP-7594 format using default KZG settings.
    ///
    /// This method converts an EIP-4844 sidecar to EIP-7594 by computing cell KZG proofs from
    /// the blob data. If the sidecar is already in EIP-7594 format, it returns itself unchanged.
    ///
    /// The conversion requires computing `CELLS_PER_EXT_BLOB` cell proofs for each blob using
    /// the KZG trusted setup. The default KZG settings are loaded from the environment.
    ///
    /// # Returns
    ///
    /// - `Ok(Self)` - The sidecar in EIP-7594 format (either converted or unchanged)
    /// - `Err(c_kzg::Error)` - If KZG proof computation fails
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use alloy_eips::eip7594::BlobTransactionSidecarVariant;
    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
    /// # fn example(sidecar: BlobTransactionSidecarVariant) -> Result<(), c_kzg::Error> {
    /// // Convert an EIP-4844 sidecar to EIP-7594 format
    /// let eip7594_sidecar = sidecar.try_convert_into_eip7594()?;
    ///
    /// // Verify it's now in EIP-7594 format
    /// assert!(eip7594_sidecar.is_eip7594());
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "kzg")]
    pub fn try_convert_into_eip7594(self) -> Result<Self, c_kzg::Error> {
        self.try_convert_into_eip7594_with_settings(
            crate::eip4844::env_settings::EnvKzgSettings::Default.get(),
        )
    }

    /// Attempts to convert this sidecar into the EIP-7594 format using custom KZG settings.
    ///
    /// This method converts an EIP-4844 sidecar to EIP-7594 by computing cell KZG proofs from
    /// the blob data using the provided KZG settings. If the sidecar is already in EIP-7594
    /// format, it returns itself unchanged.
    ///
    /// The conversion requires computing `CELLS_PER_EXT_BLOB` cell proofs for each blob using
    /// the provided KZG trusted setup parameters.
    ///
    /// Use this method when you need to specify custom KZG settings rather than using the
    /// defaults. For most use cases, [`try_convert_into_eip7594`](Self::try_convert_into_eip7594)
    /// is sufficient.
    ///
    /// # Arguments
    ///
    /// * `settings` - The KZG settings to use for computing cell proofs
    ///
    /// # Returns
    ///
    /// - `Ok(Self)` - The sidecar in EIP-7594 format (either converted or unchanged)
    /// - `Err(c_kzg::Error)` - If KZG proof computation fails
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use alloy_eips::eip7594::BlobTransactionSidecarVariant;
    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
    /// # use alloy_eips::eip4844::env_settings::EnvKzgSettings;
    /// # fn example(sidecar: BlobTransactionSidecarVariant) -> Result<(), c_kzg::Error> {
    /// // Load custom KZG settings
    /// let kzg_settings = EnvKzgSettings::Default.get();
    ///
    /// // Convert using custom settings
    /// let eip7594_sidecar = sidecar.try_convert_into_eip7594_with_settings(kzg_settings)?;
    ///
    /// // Verify it's now in EIP-7594 format
    /// assert!(eip7594_sidecar.is_eip7594());
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "kzg")]
    pub fn try_convert_into_eip7594_with_settings(
        self,
        settings: &c_kzg::KzgSettings,
    ) -> Result<Self, c_kzg::Error> {
        match self {
            Self::Eip4844(legacy) => legacy.try_into_7594(settings).map(Self::Eip7594),
            sidecar @ Self::Eip7594(_) => Ok(sidecar),
        }
    }

    /// Consumes this sidecar and returns a [`BlobTransactionSidecarEip7594`] using default KZG
    /// settings.
    ///
    /// This method converts an EIP-4844 sidecar to EIP-7594 by computing cell KZG proofs from
    /// the blob data. If the sidecar is already in EIP-7594 format, it extracts and returns the
    /// inner [`BlobTransactionSidecarEip7594`].
    ///
    /// Unlike [`try_convert_into_eip7594`](Self::try_convert_into_eip7594), this method returns
    /// the concrete [`BlobTransactionSidecarEip7594`] type rather than the enum variant.
    ///
    /// The conversion requires computing `CELLS_PER_EXT_BLOB` cell proofs for each blob using
    /// the KZG trusted setup. The default KZG settings are loaded from the environment.
    ///
    /// # Returns
    ///
    /// - `Ok(BlobTransactionSidecarEip7594)` - The sidecar in EIP-7594 format
    /// - `Err(c_kzg::Error)` - If KZG proof computation fails
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use alloy_eips::eip7594::BlobTransactionSidecarVariant;
    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
    /// # fn example(sidecar: BlobTransactionSidecarVariant) -> Result<(), c_kzg::Error> {
    /// // Convert and extract the EIP-7594 sidecar
    /// let eip7594_sidecar = sidecar.try_into_eip7594()?;
    ///
    /// // Now we have the concrete BlobTransactionSidecarEip7594 type
    /// assert_eq!(eip7594_sidecar.blobs.len(), eip7594_sidecar.commitments.len());
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "kzg")]
    pub fn try_into_eip7594(self) -> Result<BlobTransactionSidecarEip7594, c_kzg::Error> {
        self.try_into_eip7594_with_settings(
            crate::eip4844::env_settings::EnvKzgSettings::Default.get(),
        )
    }

    /// Consumes this sidecar and returns a [`BlobTransactionSidecarEip7594`] using custom KZG
    /// settings.
    ///
    /// This method converts an EIP-4844 sidecar to EIP-7594 by computing cell KZG proofs from
    /// the blob data using the provided KZG settings. If the sidecar is already in EIP-7594
    /// format, it extracts and returns the inner [`BlobTransactionSidecarEip7594`].
    ///
    /// Unlike [`try_convert_into_eip7594_with_settings`](Self::try_convert_into_eip7594_with_settings),
    /// this method returns the concrete [`BlobTransactionSidecarEip7594`] type rather than the
    /// enum variant.
    ///
    /// The conversion requires computing `CELLS_PER_EXT_BLOB` cell proofs for each blob using
    /// the provided KZG trusted setup parameters.
    ///
    /// Use this method when you need to specify custom KZG settings rather than using the
    /// defaults. For most use cases, [`try_into_eip7594`](Self::try_into_eip7594) is sufficient.
    ///
    /// # Arguments
    ///
    /// * `settings` - The KZG settings to use for computing cell proofs
    ///
    /// # Returns
    ///
    /// - `Ok(BlobTransactionSidecarEip7594)` - The sidecar in EIP-7594 format
    /// - `Err(c_kzg::Error)` - If KZG proof computation fails
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use alloy_eips::eip7594::BlobTransactionSidecarVariant;
    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
    /// # use alloy_eips::eip4844::env_settings::EnvKzgSettings;
    /// # fn example(sidecar: BlobTransactionSidecarVariant) -> Result<(), c_kzg::Error> {
    /// // Load custom KZG settings
    /// let kzg_settings = EnvKzgSettings::Default.get();
    ///
    /// // Convert and extract using custom settings
    /// let eip7594_sidecar = sidecar.try_into_eip7594_with_settings(kzg_settings)?;
    ///
    /// // Now we have the concrete BlobTransactionSidecarEip7594 type
    /// assert_eq!(eip7594_sidecar.blobs.len(), eip7594_sidecar.commitments.len());
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "kzg")]
    pub fn try_into_eip7594_with_settings(
        self,
        settings: &c_kzg::KzgSettings,
    ) -> Result<BlobTransactionSidecarEip7594, c_kzg::Error> {
        match self {
            Self::Eip4844(legacy) => legacy.try_into_7594(settings),
            Self::Eip7594(sidecar) => Ok(sidecar),
        }
    }

    /// Verifies that the sidecar is valid. See relevant methods for each variant for more info.
    #[cfg(feature = "kzg")]
    pub fn validate(
        &self,
        blob_versioned_hashes: &[B256],
        proof_settings: &c_kzg::KzgSettings,
    ) -> Result<(), BlobTransactionValidationError> {
        match self {
            Self::Eip4844(sidecar) => sidecar.validate(blob_versioned_hashes, proof_settings),
            Self::Eip7594(sidecar) => sidecar.validate(blob_versioned_hashes, proof_settings),
        }
    }

    /// Returns the commitments of the sidecar.
    pub fn commitments(&self) -> &[Bytes48] {
        match self {
            Self::Eip4844(sidecar) => &sidecar.commitments,
            Self::Eip7594(sidecar) => &sidecar.commitments,
        }
    }

    /// Returns an iterator over the versioned hashes of the commitments.
    pub fn versioned_hashes(&self) -> VersionedHashIter<'_> {
        VersionedHashIter::new(self.commitments())
    }

    /// Returns the index of the versioned hash in the commitments vector.
    pub fn versioned_hash_index(&self, hash: &B256) -> Option<usize> {
        match self {
            Self::Eip4844(s) => s.versioned_hash_index(hash),
            Self::Eip7594(s) => s.versioned_hash_index(hash),
        }
    }

    /// Returns the blob corresponding to the versioned hash, if it exists.
    pub fn blob_by_versioned_hash(&self, hash: &B256) -> Option<&Blob> {
        match self {
            Self::Eip4844(s) => s.blob_by_versioned_hash(hash),
            Self::Eip7594(s) => s.blob_by_versioned_hash(hash),
        }
    }

    /// Outputs the RLP length of the [BlobTransactionSidecarVariant] fields, without a RLP header.
    #[doc(hidden)]
    pub fn rlp_encoded_fields_length(&self) -> usize {
        match self {
            Self::Eip4844(sidecar) => sidecar.rlp_encoded_fields_length(),
            Self::Eip7594(sidecar) => sidecar.rlp_encoded_fields_length(),
        }
    }

    /// Returns the [`Self::rlp_encode_fields`] RLP bytes.
    #[inline]
    #[doc(hidden)]
    pub fn rlp_encoded_fields(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.rlp_encoded_fields_length());
        self.rlp_encode_fields(&mut buf);
        buf
    }

    /// Encodes the inner [BlobTransactionSidecarVariant] fields as RLP bytes, __without__ a RLP
    /// header.
    #[inline]
    #[doc(hidden)]
    pub fn rlp_encode_fields(&self, out: &mut dyn BufMut) {
        match self {
            Self::Eip4844(sidecar) => sidecar.rlp_encode_fields(out),
            Self::Eip7594(sidecar) => sidecar.rlp_encode_fields(out),
        }
    }

    /// RLP decode the fields of a [BlobTransactionSidecarVariant] based on the wrapper version.
    #[doc(hidden)]
    pub fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        Self::decode_7594(buf)
    }
}

impl Encodable for BlobTransactionSidecarVariant {
    /// Encodes the [BlobTransactionSidecar] fields as RLP bytes, without a RLP header.
    fn encode(&self, out: &mut dyn BufMut) {
        match self {
            Self::Eip4844(sidecar) => sidecar.encode(out),
            Self::Eip7594(sidecar) => sidecar.encode(out),
        }
    }

    fn length(&self) -> usize {
        match self {
            Self::Eip4844(sidecar) => sidecar.rlp_encoded_length(),
            Self::Eip7594(sidecar) => sidecar.rlp_encoded_length(),
        }
    }
}

impl Decodable for BlobTransactionSidecarVariant {
    /// Decodes the inner [BlobTransactionSidecar] fields from RLP bytes, without a RLP header.
    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        let header = Header::decode(buf)?;
        if !header.list {
            return Err(alloy_rlp::Error::UnexpectedString);
        }
        if buf.len() < header.payload_length {
            return Err(alloy_rlp::Error::InputTooShort);
        }
        let remaining = buf.len();
        let this = Self::rlp_decode_fields(buf)?;
        if buf.len() + header.payload_length != remaining {
            return Err(alloy_rlp::Error::UnexpectedLength);
        }

        Ok(this)
    }
}

impl Encodable7594 for BlobTransactionSidecarVariant {
    fn encode_7594_len(&self) -> usize {
        self.rlp_encoded_fields_length()
    }

    fn encode_7594(&self, out: &mut dyn BufMut) {
        self.rlp_encode_fields(out);
    }
}

impl Decodable7594 for BlobTransactionSidecarVariant {
    fn decode_7594(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        if buf.first() == Some(&EIP_7594_WRAPPER_VERSION) {
            Ok(Self::Eip7594(Decodable7594::decode_7594(buf)?))
        } else {
            Ok(Self::Eip4844(Decodable7594::decode_7594(buf)?))
        }
    }
}

#[cfg(feature = "kzg")]
impl TryFrom<BlobTransactionSidecarVariant> for BlobTransactionSidecarEip7594 {
    type Error = c_kzg::Error;

    fn try_from(value: BlobTransactionSidecarVariant) -> Result<Self, Self::Error> {
        value.try_into_eip7594()
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for BlobTransactionSidecarVariant {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use core::fmt;

        #[derive(serde::Deserialize, fmt::Debug)]
        #[serde(field_identifier, rename_all = "camelCase")]
        enum Field {
            Blobs,
            Commitments,
            Proofs,
            CellProofs,
        }

        struct VariantVisitor;

        impl<'de> serde::de::Visitor<'de> for VariantVisitor {
            type Value = BlobTransactionSidecarVariant;

            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                formatter
                    .write_str("a valid blob transaction sidecar (EIP-4844 or EIP-7594 variant)")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: serde::de::MapAccess<'de>,
            {
                let mut blobs = None;
                let mut commitments = None;
                let mut proofs = None;
                let mut cell_proofs = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Blobs => {
                            blobs = Some(crate::eip4844::deserialize_blobs_map(&mut map)?);
                        }
                        Field::Commitments => commitments = Some(map.next_value()?),
                        Field::Proofs => proofs = Some(map.next_value()?),
                        Field::CellProofs => cell_proofs = Some(map.next_value()?),
                    }
                }

                let blobs = blobs.ok_or_else(|| serde::de::Error::missing_field("blobs"))?;
                let commitments =
                    commitments.ok_or_else(|| serde::de::Error::missing_field("commitments"))?;

                match (cell_proofs, proofs) {
                    (Some(cp), None) => {
                        Ok(BlobTransactionSidecarVariant::Eip7594(BlobTransactionSidecarEip7594 {
                            blobs,
                            commitments,
                            cell_proofs: cp,
                        }))
                    }
                    (None, Some(pf)) => {
                        Ok(BlobTransactionSidecarVariant::Eip4844(BlobTransactionSidecar {
                            blobs,
                            commitments,
                            proofs: pf,
                        }))
                    }
                    (None, None) => {
                        Err(serde::de::Error::custom("Missing 'cellProofs' or 'proofs'"))
                    }
                    (Some(_), Some(_)) => Err(serde::de::Error::custom(
                        "Both 'cellProofs' and 'proofs' cannot be present",
                    )),
                }
            }
        }

        const FIELDS: &[&str] = &["blobs", "commitments", "proofs", "cellProofs"];
        deserializer.deserialize_struct("BlobTransactionSidecarVariant", FIELDS, VariantVisitor)
    }
}

/// This represents a set of blobs, and its corresponding commitments and cell proofs.
///
/// This type encodes and decodes the fields without an rlp header.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct BlobTransactionSidecarEip7594 {
    /// The blob data.
    #[cfg_attr(feature = "serde", serde(deserialize_with = "crate::eip4844::deserialize_blobs"))]
    pub blobs: Vec<Blob>,
    /// The blob commitments.
    pub commitments: Vec<Bytes48>,
    /// List of cell proofs for all blobs in the sidecar, including the proofs for the extension
    /// indices, for a total of `CELLS_PER_EXT_BLOB` proofs per blob (`CELLS_PER_EXT_BLOB` is the
    /// number of cells for an extended blob, defined in
    /// [the consensus specs](https://github.com/ethereum/consensus-specs/tree/9d377fd53d029536e57cfda1a4d2c700c59f86bf/specs/fulu/polynomial-commitments-sampling.md#cells))
    pub cell_proofs: Vec<Bytes48>,
}

impl core::fmt::Debug for BlobTransactionSidecarEip7594 {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("BlobTransactionSidecarEip7594")
            .field("blobs", &self.blobs.len())
            .field("commitments", &self.commitments)
            .field("cell_proofs", &self.cell_proofs)
            .finish()
    }
}

/// Cell indices requested by `engine_getBlobsV4`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct BlobCellMask {
    value: u128,
}

impl BlobCellMask {
    /// Creates a mask from the Engine API 16-byte, big-endian bitarray.
    #[inline]
    pub fn new(indices_bitarray: B128) -> Self {
        Self { value: u128::from(indices_bitarray) }
    }

    /// Creates a mask from the raw bit representation.
    #[inline]
    pub const fn from_bits(value: u128) -> Self {
        Self { value }
    }

    /// Returns the raw bit representation.
    #[inline]
    pub const fn bits(self) -> u128 {
        self.value
    }

    /// Returns the number of selected cells.
    #[inline]
    pub const fn count(self) -> usize {
        self.value.count_ones() as usize
    }

    /// Returns true if the given cell index is selected.
    #[inline]
    pub const fn contains(self, index: usize) -> bool {
        index < CELLS_PER_EXT_BLOB && self.value & (1u128 << index) != 0
    }

    /// Iterates selected cell indices in ascending order.
    #[inline]
    pub fn selected_indices(self) -> impl Iterator<Item = usize> {
        let mut bits = self.value;
        core::iter::from_fn(move || {
            if bits == 0 {
                return None;
            }

            let index = bits.trailing_zeros() as usize;
            bits &= bits - 1;
            Some(index)
        })
    }
}

impl BlobTransactionSidecarEip7594 {
    /// Constructs a new [BlobTransactionSidecarEip7594] from a set of blobs, commitments, and
    /// cell proofs.
    pub const fn new(
        blobs: Vec<Blob>,
        commitments: Vec<Bytes48>,
        cell_proofs: Vec<Bytes48>,
    ) -> Self {
        Self { blobs, commitments, cell_proofs }
    }

    /// Calculates a size heuristic for the in-memory size of the [BlobTransactionSidecarEip7594].
    #[inline]
    pub const fn size(&self) -> usize {
        self.blobs.capacity() * BYTES_PER_BLOB
            + self.commitments.capacity() * BYTES_PER_COMMITMENT
            + self.cell_proofs.capacity() * BYTES_PER_PROOF
    }

    /// Shrinks the sidecar vectors to fit their current contents.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.blobs.shrink_to_fit();
        self.commitments.shrink_to_fit();
        self.cell_proofs.shrink_to_fit();
    }

    /// Tries to create a new [`BlobTransactionSidecarEip7594`] from the hex encoded blob str.
    ///
    /// See also [`Blob::from_hex`](c_kzg::Blob::from_hex)
    #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
    pub fn try_from_blobs_hex<I, B>(blobs: I) -> Result<Self, c_kzg::Error>
    where
        I: IntoIterator<Item = B>,
        B: AsRef<str>,
    {
        let mut converted = Vec::new();
        for blob in blobs {
            converted.push(crate::eip4844::utils::hex_to_blob(blob)?);
        }
        Self::try_from_blobs(converted)
    }

    /// Tries to create a new [`BlobTransactionSidecarEip7594`] from the given blob
    /// bytes.
    ///
    /// See also [`Blob::from_bytes`](c_kzg::Blob::from_bytes)
    #[cfg(all(feature = "kzg", any(test, feature = "arbitrary")))]
    pub fn try_from_blobs_bytes<I, B>(blobs: I) -> Result<Self, c_kzg::Error>
    where
        I: IntoIterator<Item = B>,
        B: AsRef<[u8]>,
    {
        let mut converted = Vec::new();
        for blob in blobs {
            converted.push(crate::eip4844::utils::bytes_to_blob(blob)?);
        }
        Self::try_from_blobs(converted)
    }

    /// Tries to create a new [`BlobTransactionSidecarEip7594`] from the given
    /// blobs and KZG settings.
    #[cfg(feature = "kzg")]
    pub fn try_from_blobs_with_settings(
        blobs: Vec<Blob>,
        settings: &c_kzg::KzgSettings,
    ) -> Result<Self, c_kzg::Error> {
        let mut commitments = Vec::with_capacity(blobs.len());
        let mut proofs = Vec::with_capacity(blobs.len());
        for blob in &blobs {
            // SAFETY: same size
            let blob = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(blob) };
            let commitment = settings.blob_to_kzg_commitment(blob)?;
            let (_cells, kzg_proofs) = settings.compute_cells_and_kzg_proofs(blob)?;

            // SAFETY: same size
            unsafe {
                commitments
                    .push(core::mem::transmute::<c_kzg::Bytes48, Bytes48>(commitment.to_bytes()));
                for kzg_proof in kzg_proofs.iter() {
                    proofs.push(core::mem::transmute::<c_kzg::Bytes48, Bytes48>(
                        kzg_proof.to_bytes(),
                    ));
                }
            }
        }

        Ok(Self::new(blobs, commitments, proofs))
    }

    /// Tries to create a new [`BlobTransactionSidecarEip7594`] from the given
    /// blobs.
    ///
    /// This uses the global/default KZG settings, see also
    /// [`EnvKzgSettings::Default`](crate::eip4844::env_settings::EnvKzgSettings).
    #[cfg(feature = "kzg")]
    pub fn try_from_blobs(blobs: Vec<Blob>) -> Result<Self, c_kzg::Error> {
        use crate::eip4844::env_settings::EnvKzgSettings;

        Self::try_from_blobs_with_settings(blobs, EnvKzgSettings::Default.get())
    }

    /// Computes the EIP-7594 cells for all blobs using the default KZG settings.
    ///
    /// The returned cells are flattened by blob and each blob contributes
    /// [`CELLS_PER_EXT_BLOB`] cells. For blob index `i` and cell index `j`, the cell is at
    /// `i * CELLS_PER_EXT_BLOB + j`, matching the [`Self::cell_proofs`] layout.
    #[cfg(feature = "kzg")]
    pub fn compute_cells(&self) -> Result<Vec<Cell>, c_kzg::Error> {
        use crate::eip4844::env_settings::EnvKzgSettings;

        self.compute_cells_with_settings(EnvKzgSettings::Default.get())
    }

    /// Computes the EIP-7594 cells for all blobs using the given KZG settings.
    ///
    /// The returned cells are flattened by blob and each blob contributes
    /// [`CELLS_PER_EXT_BLOB`] cells. For blob index `i` and cell index `j`, the cell is at
    /// `i * CELLS_PER_EXT_BLOB + j`, matching the [`Self::cell_proofs`] layout.
    #[cfg(feature = "kzg")]
    pub fn compute_cells_with_settings(
        &self,
        settings: &c_kzg::KzgSettings,
    ) -> Result<Vec<Cell>, c_kzg::Error> {
        let mut cells = Vec::with_capacity(self.blobs.len() * CELLS_PER_EXT_BLOB);
        for blob in &self.blobs {
            // SAFETY: Blob and c_kzg::Blob have the same memory layout.
            let blob = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(blob) };
            let blob_cells = settings.compute_cells(blob)?;
            cells.extend(blob_cells.iter().map(|cell| Cell::new(cell.to_bytes())));
        }
        Ok(cells)
    }

    /// Verifies that the versioned hashes are valid for this sidecar's blob data, commitments, and
    /// proofs.
    ///
    /// Takes as input the [KzgSettings](c_kzg::KzgSettings), which should contain the parameters
    /// derived from the KZG trusted setup.
    ///
    /// This ensures that the blob transaction payload has the expected number of blob data
    /// elements, commitments, and proofs. The cells are constructed from each blob and verified
    /// against the commitments and proofs.
    ///
    /// Returns [BlobTransactionValidationError::InvalidProof] if any blob KZG proof in the response
    /// fails to verify, or if the versioned hashes in the transaction do not match the actual
    /// commitment versioned hashes.
    #[cfg(feature = "kzg")]
    pub fn validate(
        &self,
        blob_versioned_hashes: &[B256],
        proof_settings: &c_kzg::KzgSettings,
    ) -> Result<(), BlobTransactionValidationError> {
        // Ensure the versioned hashes and commitments have the same length.
        if blob_versioned_hashes.len() != self.commitments.len() {
            return Err(c_kzg::Error::MismatchLength(format!(
                "There are {} versioned commitment hashes and {} commitments",
                blob_versioned_hashes.len(),
                self.commitments.len()
            ))
            .into());
        }

        let blobs_len = self.blobs.len();
        let expected_cell_proofs_len = blobs_len * CELLS_PER_EXT_BLOB;
        if self.cell_proofs.len() != expected_cell_proofs_len {
            return Err(c_kzg::Error::MismatchLength(format!(
                "There are {} cell proofs and {} blobs. Expected {} cell proofs.",
                self.cell_proofs.len(),
                blobs_len,
                expected_cell_proofs_len
            ))
            .into());
        }

        // calculate versioned hashes by zipping & iterating
        for (versioned_hash, commitment) in
            blob_versioned_hashes.iter().zip(self.commitments.iter())
        {
            // calculate & verify versioned hash
            let calculated_versioned_hash =
                crate::eip4844::kzg_to_versioned_hash(commitment.as_slice());
            if *versioned_hash != calculated_versioned_hash {
                return Err(BlobTransactionValidationError::WrongVersionedHash {
                    have: *versioned_hash,
                    expected: calculated_versioned_hash,
                });
            }
        }

        // Repeat cell ranges for each blob.
        let cell_indices =
            Vec::from_iter((0..blobs_len).flat_map(|_| 0..CELLS_PER_EXT_BLOB as u64));

        // Repeat commitments for each cell.
        let mut commitments = Vec::with_capacity(blobs_len * CELLS_PER_EXT_BLOB);
        for commitment in &self.commitments {
            commitments.extend(core::iter::repeat_n(*commitment, CELLS_PER_EXT_BLOB));
        }

        // SAFETY: ALL types have the same size
        let res = unsafe {
            let mut cells = Vec::with_capacity(blobs_len * CELLS_PER_EXT_BLOB);
            for blob in &self.blobs {
                let blob = core::mem::transmute::<&Blob, &c_kzg::Blob>(blob);
                let blob_cells = proof_settings.compute_cells(blob)?;
                cells.extend_from_slice(blob_cells.as_ref());
            }

            proof_settings.verify_cell_kzg_proof_batch(
                // commitments
                core::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(&commitments),
                // cell indices
                &cell_indices,
                // cells
                &cells,
                // proofs
                core::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(self.cell_proofs.as_slice()),
            )?
        };

        res.then_some(()).ok_or(BlobTransactionValidationError::InvalidProof)
    }

    /// Returns an iterator over the versioned hashes of the commitments.
    pub fn versioned_hashes(&self) -> VersionedHashIter<'_> {
        VersionedHashIter::new(&self.commitments)
    }

    /// Returns the index of the versioned hash in the commitments vector.
    pub fn versioned_hash_index(&self, hash: &B256) -> Option<usize> {
        self.commitments.iter().position(|commitment| {
            crate::eip4844::kzg_to_versioned_hash(commitment.as_slice()) == *hash
        })
    }

    /// Returns the blob corresponding to the versioned hash, if it exists.
    pub fn blob_by_versioned_hash(&self, hash: &B256) -> Option<&Blob> {
        self.versioned_hash_index(hash).and_then(|index| self.blobs.get(index))
    }

    /// Returns the requested cells and proofs for the blob at `blob_index`, if it exists.
    ///
    /// This uses the default KZG settings.
    #[cfg(feature = "kzg")]
    pub fn blob_cells_and_proofs(
        &self,
        blob_index: usize,
        cell_mask: BlobCellMask,
    ) -> Result<Option<BlobCellsAndProofsV1>, c_kzg::Error> {
        use crate::eip4844::env_settings::EnvKzgSettings;

        self.blob_cells_and_proofs_with_settings(
            blob_index,
            cell_mask,
            EnvKzgSettings::Default.get(),
        )
    }

    /// Returns the requested cells and proofs for the blob at `blob_index`, if it exists.
    #[cfg(feature = "kzg")]
    pub fn blob_cells_and_proofs_with_settings(
        &self,
        blob_index: usize,
        cell_mask: BlobCellMask,
        settings: &c_kzg::KzgSettings,
    ) -> Result<Option<BlobCellsAndProofsV1>, c_kzg::Error> {
        let Some(blob) = self.blobs.get(blob_index) else { return Ok(None) };

        let proof_start = blob_index * CELLS_PER_EXT_BLOB;
        let Some(proofs) = self.cell_proofs.get(proof_start..proof_start + CELLS_PER_EXT_BLOB)
        else {
            return Ok(None);
        };

        if cell_mask.count() == 0 {
            return Ok(Some(BlobCellsAndProofsV1::default()));
        }

        // SAFETY: Blob and c_kzg::Blob have the same memory layout.
        let blob = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(blob) };
        let cells = settings.compute_cells(blob)?;

        Ok(Some(Self::blob_cells_and_proofs_from_computed_cells(cell_mask, cells.as_ref(), proofs)))
    }

    /// Returns the requested cells and proofs from precomputed cells.
    #[cfg(feature = "kzg")]
    fn blob_cells_and_proofs_from_computed_cells(
        cell_mask: BlobCellMask,
        cells: &[c_kzg::Cell],
        proofs: &[Bytes48],
    ) -> BlobCellsAndProofsV1 {
        let mut blob_cells = Vec::with_capacity(cell_mask.count());
        let mut selected_proofs = Vec::with_capacity(cell_mask.count());
        for cell_index in cell_mask.selected_indices() {
            blob_cells.push(Some(Cell::new(cells[cell_index].to_bytes())));
            selected_proofs.push(Some(proofs[cell_index]));
        }

        BlobCellsAndProofsV1 { blob_cells, proofs: selected_proofs }
    }

    /// Matches versioned hashes and returns an iterator of (index, [`BlobAndProofV2`]) pairs
    /// where index is the position in `versioned_hashes` that matched the versioned hash in the
    /// sidecar.
    ///
    /// This is used for the `engine_getBlobsV2` RPC endpoint of the engine API
    pub fn match_versioned_hashes<'a>(
        &'a self,
        versioned_hashes: &'a [B256],
    ) -> impl Iterator<Item = (usize, BlobAndProofV2)> + 'a {
        self.versioned_hashes().enumerate().flat_map(move |(i, blob_versioned_hash)| {
            versioned_hashes.iter().enumerate().filter_map(move |(j, target_hash)| {
                if blob_versioned_hash == *target_hash {
                    let maybe_blob = self.blobs.get(i);
                    let proof_range = i * CELLS_PER_EXT_BLOB..(i + 1) * CELLS_PER_EXT_BLOB;
                    let maybe_proofs = Some(&self.cell_proofs[proof_range])
                        .filter(|proofs| proofs.len() == CELLS_PER_EXT_BLOB);
                    if let Some((blob, proofs)) = maybe_blob.copied().zip(maybe_proofs) {
                        return Some((
                            j,
                            BlobAndProofV2 { blob: Box::new(blob), proofs: proofs.to_vec() },
                        ));
                    }
                }
                None
            })
        })
    }

    /// Matches versioned hashes and returns (index, [`BlobCellsAndProofsV1`]) pairs where index is
    /// the position in `versioned_hashes` that matched the versioned hash in the sidecar.
    ///
    /// This is used for the `engine_getBlobsV4` RPC endpoint of the engine API.
    ///
    /// This uses the default KZG settings.
    #[cfg(feature = "kzg")]
    pub fn match_versioned_hashes_cells<'a>(
        &'a self,
        versioned_hashes: &'a [B256],
        cell_mask: BlobCellMask,
    ) -> Result<impl Iterator<Item = (usize, BlobCellsAndProofsV1)> + 'a, c_kzg::Error> {
        use crate::eip4844::env_settings::EnvKzgSettings;

        self.match_versioned_hashes_cells_with_settings(
            versioned_hashes,
            cell_mask,
            EnvKzgSettings::Default.get(),
        )
    }

    /// Matches versioned hashes and returns (index, [`BlobCellsAndProofsV1`]) pairs where index is
    /// the position in `versioned_hashes` that matched the versioned hash in the sidecar.
    #[cfg(feature = "kzg")]
    pub fn match_versioned_hashes_cells_with_settings<'a>(
        &'a self,
        versioned_hashes: &'a [B256],
        cell_mask: BlobCellMask,
        settings: &c_kzg::KzgSettings,
    ) -> Result<impl Iterator<Item = (usize, BlobCellsAndProofsV1)> + 'a, c_kzg::Error> {
        let mut matches = Vec::new();
        let mut cells_and_proofs_by_blob = Vec::<(usize, BlobCellsAndProofsV1)>::new();

        for (blob_index, commitment) in self.commitments.iter().enumerate() {
            let blob_versioned_hash = crate::eip4844::kzg_to_versioned_hash(commitment.as_slice());
            for (matched_index, target_hash) in versioned_hashes.iter().enumerate() {
                if blob_versioned_hash != *target_hash {
                    continue;
                }

                let Some(blob) = self.blobs.get(blob_index) else { continue };
                let proof_start = blob_index * CELLS_PER_EXT_BLOB;
                let Some(proofs) =
                    self.cell_proofs.get(proof_start..proof_start + CELLS_PER_EXT_BLOB)
                else {
                    continue;
                };

                let cells_and_proofs = if cell_mask.count() == 0 {
                    BlobCellsAndProofsV1::default()
                } else if let Some((_, cells_and_proofs)) =
                    cells_and_proofs_by_blob.iter().find(|(index, _)| *index == blob_index)
                {
                    cells_and_proofs.clone()
                } else {
                    // SAFETY: Blob and c_kzg::Blob have the same memory layout.
                    let blob = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(blob) };
                    let cells = settings.compute_cells(blob)?;
                    let cells_and_proofs = Self::blob_cells_and_proofs_from_computed_cells(
                        cell_mask,
                        cells.as_ref(),
                        proofs,
                    );
                    cells_and_proofs_by_blob.push((blob_index, cells_and_proofs.clone()));
                    cells_and_proofs
                };

                matches.push((matched_index, cells_and_proofs));
            }
        }

        Ok(matches.into_iter())
    }

    /// Outputs the RLP length of [BlobTransactionSidecarEip7594] fields without a RLP header.
    #[doc(hidden)]
    pub fn rlp_encoded_fields_length(&self) -> usize {
        // wrapper version + blobs + commitments + cell proofs
        1 + self.blobs.length() + self.commitments.length() + self.cell_proofs.length()
    }

    /// Encodes the inner [BlobTransactionSidecarEip7594] fields as RLP bytes, __without__ a
    /// RLP header.
    ///
    /// This encodes the fields in the following order:
    /// - `wrapper_version`
    /// - `blobs`
    /// - `commitments`
    /// - `cell_proofs`
    #[inline]
    #[doc(hidden)]
    pub fn rlp_encode_fields(&self, out: &mut dyn BufMut) {
        // Put version byte.
        out.put_u8(EIP_7594_WRAPPER_VERSION);
        // Encode the blobs, commitments, and cell proofs
        self.blobs.encode(out);
        self.commitments.encode(out);
        self.cell_proofs.encode(out);
    }

    /// Creates an RLP header for the [BlobTransactionSidecarEip7594].
    fn rlp_header(&self) -> Header {
        Header { list: true, payload_length: self.rlp_encoded_fields_length() }
    }

    /// Calculates the length of the [BlobTransactionSidecarEip7594] when encoded as
    /// RLP.
    pub fn rlp_encoded_length(&self) -> usize {
        self.rlp_header().length() + self.rlp_encoded_fields_length()
    }

    /// Encodes the [BlobTransactionSidecarEip7594] as RLP bytes.
    pub fn rlp_encode(&self, out: &mut dyn BufMut) {
        self.rlp_header().encode(out);
        self.rlp_encode_fields(out);
    }

    /// RLP decode the fields of a [BlobTransactionSidecarEip7594].
    #[doc(hidden)]
    pub fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        Ok(Self {
            blobs: Decodable::decode(buf)?,
            commitments: Decodable::decode(buf)?,
            cell_proofs: Decodable::decode(buf)?,
        })
    }

    /// Decodes the [BlobTransactionSidecarEip7594] from RLP bytes.
    pub fn rlp_decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        let header = Header::decode(buf)?;
        if !header.list {
            return Err(alloy_rlp::Error::UnexpectedString);
        }
        if buf.len() < header.payload_length {
            return Err(alloy_rlp::Error::InputTooShort);
        }
        let remaining = buf.len();

        let this = Self::decode_7594(buf)?;
        if buf.len() + header.payload_length != remaining {
            return Err(alloy_rlp::Error::UnexpectedLength);
        }

        Ok(this)
    }
}

impl Encodable for BlobTransactionSidecarEip7594 {
    /// Encodes the inner [BlobTransactionSidecarEip7594] fields as RLP bytes, without a RLP header.
    fn encode(&self, out: &mut dyn BufMut) {
        self.rlp_encode(out);
    }

    fn length(&self) -> usize {
        self.rlp_encoded_length()
    }
}

impl Decodable for BlobTransactionSidecarEip7594 {
    /// Decodes the inner [BlobTransactionSidecarEip7594] fields from RLP bytes, without a RLP
    /// header.
    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        Self::rlp_decode(buf)
    }
}

impl Encodable7594 for BlobTransactionSidecarEip7594 {
    fn encode_7594_len(&self) -> usize {
        self.rlp_encoded_fields_length()
    }

    fn encode_7594(&self, out: &mut dyn BufMut) {
        self.rlp_encode_fields(out);
    }
}

impl Decodable7594 for BlobTransactionSidecarEip7594 {
    fn decode_7594(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        let wrapper_version: u8 = Decodable::decode(buf)?;
        if wrapper_version != EIP_7594_WRAPPER_VERSION {
            return Err(alloy_rlp::Error::Custom("invalid wrapper version"));
        }
        Self::rlp_decode_fields(buf)
    }
}

/// Bincode-compatible [`BlobTransactionSidecarVariant`] serde implementation.
#[cfg(all(feature = "serde", feature = "serde-bincode-compat"))]
pub mod serde_bincode_compat {
    use crate::eip4844::{Blob, Bytes48};
    use alloc::{borrow::Cow, vec::Vec};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use serde_with::{DeserializeAs, SerializeAs};

    /// Bincode-compatible [`super::BlobTransactionSidecarVariant`] serde implementation.
    ///
    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
    /// ```rust
    /// use alloy_eips::eip7594::{serde_bincode_compat, BlobTransactionSidecarVariant};
    /// use serde::{Deserialize, Serialize};
    /// use serde_with::serde_as;
    ///
    /// #[serde_as]
    /// #[derive(Serialize, Deserialize)]
    /// struct Data {
    ///     #[serde_as(as = "serde_bincode_compat::BlobTransactionSidecarVariant")]
    ///     sidecar: BlobTransactionSidecarVariant,
    /// }
    /// ```
    #[derive(Debug, Serialize, Deserialize)]
    pub struct BlobTransactionSidecarVariant<'a> {
        /// The blob data (common to both variants).
        pub blobs: Cow<'a, Vec<Blob>>,
        /// The blob commitments (common to both variants).
        pub commitments: Cow<'a, Vec<Bytes48>>,
        /// The blob proofs (EIP-4844 only).
        pub proofs: Option<Cow<'a, Vec<Bytes48>>>,
        /// The cell proofs (EIP-7594 only).
        pub cell_proofs: Option<Cow<'a, Vec<Bytes48>>>,
    }

    impl<'a> From<&'a super::BlobTransactionSidecarVariant> for BlobTransactionSidecarVariant<'a> {
        fn from(value: &'a super::BlobTransactionSidecarVariant) -> Self {
            match value {
                super::BlobTransactionSidecarVariant::Eip4844(sidecar) => Self {
                    blobs: Cow::Borrowed(&sidecar.blobs),
                    commitments: Cow::Borrowed(&sidecar.commitments),
                    proofs: Some(Cow::Borrowed(&sidecar.proofs)),
                    cell_proofs: None,
                },
                super::BlobTransactionSidecarVariant::Eip7594(sidecar) => Self {
                    blobs: Cow::Borrowed(&sidecar.blobs),
                    commitments: Cow::Borrowed(&sidecar.commitments),
                    proofs: None,
                    cell_proofs: Some(Cow::Borrowed(&sidecar.cell_proofs)),
                },
            }
        }
    }

    impl<'a> BlobTransactionSidecarVariant<'a> {
        fn try_into_inner(self) -> Result<super::BlobTransactionSidecarVariant, &'static str> {
            match (self.proofs, self.cell_proofs) {
                (Some(proofs), None) => Ok(super::BlobTransactionSidecarVariant::Eip4844(
                    crate::eip4844::BlobTransactionSidecar {
                        blobs: self.blobs.into_owned(),
                        commitments: self.commitments.into_owned(),
                        proofs: proofs.into_owned(),
                    },
                )),
                (None, Some(cell_proofs)) => Ok(super::BlobTransactionSidecarVariant::Eip7594(
                    super::BlobTransactionSidecarEip7594 {
                        blobs: self.blobs.into_owned(),
                        commitments: self.commitments.into_owned(),
                        cell_proofs: cell_proofs.into_owned(),
                    },
                )),
                (None, None) => Err("Missing both 'proofs' and 'cell_proofs'"),
                (Some(_), Some(_)) => Err("Both 'proofs' and 'cell_proofs' cannot be present"),
            }
        }
    }

    impl<'a> From<BlobTransactionSidecarVariant<'a>> for super::BlobTransactionSidecarVariant {
        fn from(value: BlobTransactionSidecarVariant<'a>) -> Self {
            value.try_into_inner().expect("Invalid BlobTransactionSidecarVariant")
        }
    }

    impl SerializeAs<super::BlobTransactionSidecarVariant> for BlobTransactionSidecarVariant<'_> {
        fn serialize_as<S>(
            source: &super::BlobTransactionSidecarVariant,
            serializer: S,
        ) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            BlobTransactionSidecarVariant::from(source).serialize(serializer)
        }
    }

    impl<'de> DeserializeAs<'de, super::BlobTransactionSidecarVariant>
        for BlobTransactionSidecarVariant<'de>
    {
        fn deserialize_as<D>(
            deserializer: D,
        ) -> Result<super::BlobTransactionSidecarVariant, D::Error>
        where
            D: Deserializer<'de>,
        {
            let value = BlobTransactionSidecarVariant::deserialize(deserializer)?;
            value.try_into_inner().map_err(serde::de::Error::custom)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "kzg")]
    use crate::eip4844::{
        builder::{SidecarBuilder, SimpleCoder},
        env_settings::EnvKzgSettings,
    };

    #[test]
    fn sidecar_variant_rlp_roundtrip() {
        let mut encoded = Vec::new();

        // 4844
        let empty_sidecar_4844 =
            BlobTransactionSidecarVariant::Eip4844(BlobTransactionSidecar::default());
        empty_sidecar_4844.encode(&mut encoded);
        assert_eq!(
            empty_sidecar_4844,
            BlobTransactionSidecarVariant::decode(&mut &encoded[..]).unwrap()
        );

        let sidecar_4844 = BlobTransactionSidecarVariant::Eip4844(BlobTransactionSidecar::new(
            vec![Blob::default()],
            vec![Bytes48::ZERO],
            vec![Bytes48::ZERO],
        ));
        encoded.clear();
        sidecar_4844.encode(&mut encoded);
        assert_eq!(sidecar_4844, BlobTransactionSidecarVariant::decode(&mut &encoded[..]).unwrap());

        // 7594
        let empty_sidecar_7594 =
            BlobTransactionSidecarVariant::Eip7594(BlobTransactionSidecarEip7594::default());
        encoded.clear();
        empty_sidecar_7594.encode(&mut encoded);
        assert_eq!(
            empty_sidecar_7594,
            BlobTransactionSidecarVariant::decode(&mut &encoded[..]).unwrap()
        );

        let sidecar_7594 =
            BlobTransactionSidecarVariant::Eip7594(BlobTransactionSidecarEip7594::new(
                vec![Blob::default()],
                vec![Bytes48::ZERO],
                core::iter::repeat_n(Bytes48::ZERO, CELLS_PER_EXT_BLOB).collect(),
            ));
        encoded.clear();
        sidecar_7594.encode(&mut encoded);
        assert_eq!(sidecar_7594, BlobTransactionSidecarVariant::decode(&mut &encoded[..]).unwrap());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn sidecar_variant_json_deserialize_sanity() {
        let mut eip4844 = BlobTransactionSidecar::default();
        eip4844.blobs.push(Blob::repeat_byte(0x2));

        let json = serde_json::to_string(&eip4844).unwrap();
        let variant: BlobTransactionSidecarVariant = serde_json::from_str(&json).unwrap();
        assert!(variant.is_eip4844());
        let jsonvariant = serde_json::to_string(&variant).unwrap();
        assert_eq!(json, jsonvariant);

        let mut eip7594 = BlobTransactionSidecarEip7594::default();
        eip7594.blobs.push(Blob::repeat_byte(0x4));
        let json = serde_json::to_string(&eip7594).unwrap();
        let variant: BlobTransactionSidecarVariant = serde_json::from_str(&json).unwrap();
        assert!(variant.is_eip7594());
        let jsonvariant = serde_json::to_string(&variant).unwrap();
        assert_eq!(json, jsonvariant);
    }

    #[test]
    fn rlp_7594_roundtrip() {
        let mut encoded = Vec::new();

        let sidecar_4844 = BlobTransactionSidecar::default();
        sidecar_4844.encode_7594(&mut encoded);
        assert_eq!(sidecar_4844, Decodable7594::decode_7594(&mut &encoded[..]).unwrap());

        let sidecar_variant_4844 = BlobTransactionSidecarVariant::Eip4844(sidecar_4844);
        assert_eq!(sidecar_variant_4844, Decodable7594::decode_7594(&mut &encoded[..]).unwrap());
        encoded.clear();
        sidecar_variant_4844.encode_7594(&mut encoded);
        assert_eq!(sidecar_variant_4844, Decodable7594::decode_7594(&mut &encoded[..]).unwrap());

        let sidecar_7594 = BlobTransactionSidecarEip7594::default();
        encoded.clear();
        sidecar_7594.encode_7594(&mut encoded);
        assert_eq!(sidecar_7594, Decodable7594::decode_7594(&mut &encoded[..]).unwrap());

        let sidecar_variant_7594 = BlobTransactionSidecarVariant::Eip7594(sidecar_7594);
        assert_eq!(sidecar_variant_7594, Decodable7594::decode_7594(&mut &encoded[..]).unwrap());
        encoded.clear();
        sidecar_variant_7594.encode_7594(&mut encoded);
        assert_eq!(sidecar_variant_7594, Decodable7594::decode_7594(&mut &encoded[..]).unwrap());
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn validate_7594_sidecar() {
        let sidecar =
            SidecarBuilder::<SimpleCoder>::from_slice(b"Blobs are fun!").build_7594().unwrap();
        let versioned_hashes = sidecar.versioned_hashes().collect::<Vec<_>>();

        sidecar.validate(&versioned_hashes, EnvKzgSettings::Default.get()).unwrap();
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn compute_cells_for_7594_sidecar() {
        let settings = EnvKzgSettings::Default.get();
        let sidecar = BlobTransactionSidecarEip7594::try_from_blobs_with_settings(
            vec![Blob::repeat_byte(0x01), Blob::repeat_byte(0x02)],
            settings,
        )
        .unwrap();

        let cells = sidecar.compute_cells_with_settings(settings).unwrap();
        assert_eq!(cells.len(), sidecar.blobs.len() * CELLS_PER_EXT_BLOB);
        assert_eq!(sidecar.compute_cells().unwrap(), cells);

        for (blob_index, blob) in sidecar.blobs.iter().enumerate() {
            // SAFETY: Blob and c_kzg::Blob have the same memory layout.
            let blob = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(blob) };
            let expected_cells = settings.compute_cells(blob).unwrap();
            let start = blob_index * CELLS_PER_EXT_BLOB;
            let end = start + CELLS_PER_EXT_BLOB;

            for (cell, expected_cell) in cells[start..end].iter().zip(expected_cells.iter()) {
                assert_eq!(*cell, Cell::new(expected_cell.to_bytes()));
            }
        }
    }

    #[test]
    fn blob_cell_mask_selects_indices() {
        let selected = (1u128 << 0) | (1u128 << 7);
        let mask = BlobCellMask::new(B128::from(selected));

        assert_eq!(mask.bits(), selected);
        assert_eq!(mask.count(), 2);
        assert!(mask.contains(0));
        assert!(mask.contains(7));
        assert!(!mask.contains(1));
        assert_eq!(mask.selected_indices().collect::<Vec<_>>(), vec![0, 7]);
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn match_versioned_hashes_cells_for_7594_sidecar() {
        let settings = EnvKzgSettings::Default.get();
        let sidecar = BlobTransactionSidecarEip7594::try_from_blobs_with_settings(
            vec![Blob::repeat_byte(0x01), Blob::repeat_byte(0x02)],
            settings,
        )
        .unwrap();
        let versioned_hashes = sidecar.versioned_hashes().collect::<Vec<_>>();
        let cell_mask = BlobCellMask::from_bits((1u128 << 0) | (1u128 << 7));

        let cells_and_proofs =
            sidecar.blob_cells_and_proofs_with_settings(0, cell_mask, settings).unwrap().unwrap();
        assert_eq!(cells_and_proofs.blob_cells.len(), 2);
        assert_eq!(cells_and_proofs.proofs.len(), 2);
        assert_eq!(
            cells_and_proofs.proofs,
            vec![Some(sidecar.cell_proofs[0]), Some(sidecar.cell_proofs[7])]
        );

        // SAFETY: Blob and c_kzg::Blob have the same memory layout.
        let blob = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(&sidecar.blobs[0]) };
        let expected_cells = settings.compute_cells(blob).unwrap();
        assert_eq!(
            cells_and_proofs.blob_cells,
            vec![
                Some(Cell::new(expected_cells[0].to_bytes())),
                Some(Cell::new(expected_cells[7].to_bytes()))
            ]
        );

        let request = vec![versioned_hashes[0], B256::ZERO, versioned_hashes[0]];
        let matches = sidecar
            .match_versioned_hashes_cells_with_settings(&request, cell_mask, settings)
            .unwrap()
            .collect::<Vec<_>>();
        assert_eq!(matches.len(), 2);
        assert_eq!(matches[0], (0, cells_and_proofs.clone()));
        assert_eq!(matches[1], (2, cells_and_proofs.clone()));

        let default_matches = sidecar
            .match_versioned_hashes_cells(&[versioned_hashes[0]], cell_mask)
            .unwrap()
            .collect::<Vec<_>>();
        assert_eq!(default_matches, vec![(0, cells_and_proofs)]);
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn match_versioned_hashes_cells_only_computes_matched_blobs() {
        let settings = EnvKzgSettings::Default.get();
        let mut sidecar = BlobTransactionSidecarEip7594::try_from_blobs_with_settings(
            vec![Blob::repeat_byte(0x01)],
            settings,
        )
        .unwrap();
        let versioned_hash = sidecar.versioned_hashes().next().unwrap();
        let cell_mask = BlobCellMask::from_bits(1);

        let invalid_blob = Blob::repeat_byte(0xff);
        // SAFETY: Blob and c_kzg::Blob have the same memory layout.
        let blob = unsafe { core::mem::transmute::<&Blob, &c_kzg::Blob>(&invalid_blob) };
        assert!(settings.compute_cells(blob).is_err());

        sidecar.blobs.push(invalid_blob);
        sidecar.commitments.push(Bytes48::ZERO);
        sidecar.cell_proofs.extend(core::iter::repeat_n(Bytes48::ZERO, CELLS_PER_EXT_BLOB));

        let cells_and_proofs =
            sidecar.blob_cells_and_proofs_with_settings(0, cell_mask, settings).unwrap().unwrap();
        let matches = sidecar
            .match_versioned_hashes_cells_with_settings(&[versioned_hash], cell_mask, settings)
            .unwrap()
            .collect::<Vec<_>>();
        assert_eq!(matches, vec![(0, cells_and_proofs)]);
    }
}