alloy-eips 2.4.1

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
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
use crate::{
    eip4844::{
        Blob, BlobAndProofV2, BlobTransactionSidecar, Bytes48, BYTES_PER_BLOB,
        BYTES_PER_COMMITMENT, BYTES_PER_PROOF,
    },
    eip7594::{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};
use crate::eip4844::VersionedHashIter;
#[cfg(feature = "kzg")]
use crate::eip4844::{AsAlloy, AsCkzg, BlobTransactionValidationError};

/// This represents a set of blobs, and its corresponding commitments and proofs.
/// Proof type depends on the sidecar variant.
///
/// Its [`Encodable`] and [`Decodable`] implementations include an outer RLP list header. The
/// field-level [`Encodable7594`] and [`Decodable7594`] codecs omit that 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,
        }
    }

    /// Clears EIP-7594 blob payloads while retaining commitments and cell proofs.
    ///
    /// This prepares the sidecar for inclusion in an eth/72 `PooledTransactions` response as
    /// specified by [EIP-8070]. This has no effect on EIP-4844 sidecars.
    ///
    /// [EIP-8070]: https://eips.ethereum.org/EIPS/eip-8070
    pub fn clear_eip7594_blobs(&mut self) {
        if let Self::Eip7594(sidecar) = self {
            sidecar.clear_eip7594_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 selected sidecar as an RLP list, including its outer 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 an RLP list, including its outer 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.
///
/// A well-formed sidecar has one commitment per blob and `CELLS_PER_EXT_BLOB` cell proofs per
/// blob. Public fields and [`Self::new`] do not enforce these cardinalities or validate proofs.
/// With the `kzg` feature, prefer `try_from_blobs_with_settings` or call `validate` before
/// use.
///
/// Its [`Encodable`] and [`Decodable`] implementations include an outer RLP list header. The
/// field-level [`Encodable7594`] and [`Decodable7594`] codecs omit that 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()
    }
}

impl BlobTransactionSidecarEip7594 {
    /// Constructs a sidecar without validating cardinalities, commitments, or cell proofs.
    pub const fn new(
        blobs: Vec<Blob>,
        commitments: Vec<Bytes48>,
        cell_proofs: Vec<Bytes48>,
    ) -> Self {
        Self { blobs, commitments, cell_proofs }
    }

    /// Recovers a sidecar from a common set of EIP-7594 cells for every blob.
    ///
    /// `cell_mask` identifies the cells supplied for each commitment. `cells` must be flattened in
    /// blob-major order: all selected cells for `commitments[0]`, followed by all selected cells
    /// for `commitments[1]`, and so on. At least half of the 128 extended blob cells must be
    /// selected. The recovered sidecar contains the complete blob data and all 128 cell proofs.
    ///
    /// Recovery authenticates each reconstructed blob by recomputing and comparing its
    /// commitment. It does not verify proofs for the input cells; callers accepting untrusted
    /// cells and proofs should batch-verify them before recovery when early rejection is useful.
    ///
    /// This uses the default KZG settings.
    #[cfg(feature = "kzg")]
    pub fn try_recover_from_cells(
        commitments: Vec<Bytes48>,
        cell_mask: BlobCellMask,
        cells: &[crate::eip7594::Cell],
    ) -> Result<Self, BlobCellRecoveryError> {
        use crate::eip4844::env_settings::EnvKzgSettings;

        Self::try_recover_from_cells_with_settings(
            commitments,
            cell_mask,
            cells,
            EnvKzgSettings::Default.get(),
        )
    }

    /// Recovers a sidecar from EIP-7594 cells using custom KZG settings.
    ///
    /// See [`Self::try_recover_from_cells`] for the expected cell layout and verification
    /// boundary.
    #[cfg(feature = "kzg")]
    pub fn try_recover_from_cells_with_settings(
        commitments: Vec<Bytes48>,
        cell_mask: BlobCellMask,
        cells: &[crate::eip7594::Cell],
        settings: &c_kzg::KzgSettings,
    ) -> Result<Self, BlobCellRecoveryError> {
        let cells_per_blob = cell_mask.count();
        if !commitments.is_empty() && cells_per_blob < CELLS_PER_EXT_BLOB / 2 {
            return Err(BlobCellRecoveryError::InsufficientCells {
                provided: cells_per_blob,
                required: CELLS_PER_EXT_BLOB / 2,
            });
        }

        let expected_cells = commitments
            .len()
            .checked_mul(cells_per_blob)
            .ok_or(BlobCellRecoveryError::CellCountOverflow)?;
        if cells.len() != expected_cells {
            return Err(BlobCellRecoveryError::CellCountMismatch {
                provided: cells.len(),
                expected: expected_cells,
            });
        }
        if commitments.is_empty() {
            return Ok(Self::new(Vec::new(), commitments, Vec::new()));
        }

        let cell_indices =
            cell_mask.selected_indices().map(|index| index as u64).collect::<Vec<_>>();
        let mut blobs = Vec::with_capacity(commitments.len());
        let cell_proof_capacity = commitments
            .len()
            .checked_mul(CELLS_PER_EXT_BLOB)
            .ok_or(BlobCellRecoveryError::CellCountOverflow)?;
        let mut cell_proofs = Vec::with_capacity(cell_proof_capacity);

        for (blob_index, (blob_cells, expected_commitment)) in
            cells.chunks_exact(cells_per_blob).zip(&commitments).enumerate()
        {
            let ckzg_cells = crate::eip7594::Cell::slice_as_ckzg(blob_cells);
            let (recovered_cells, recovered_proofs) =
                settings.recover_cells_and_kzg_proofs(&cell_indices, ckzg_cells)?;
            let blob = reconstruct_blob(recovered_cells.as_ref());

            let commitment = settings.blob_to_kzg_commitment(blob.as_ckzg())?;
            let commitment = Bytes48::from_ckzg(commitment.to_bytes());
            if commitment != *expected_commitment {
                return Err(BlobCellRecoveryError::CommitmentMismatch { blob_index });
            }

            blobs.push(blob);
            cell_proofs
                .extend_from_slice(c_kzg::KzgProof::slice_as_alloy(recovered_proofs.as_ref()));
        }

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

    /// Clears blob payloads while retaining commitments and cell proofs.
    ///
    /// This prepares the sidecar for inclusion in an eth/72 `PooledTransactions` response as
    /// specified by [EIP-8070].
    ///
    /// [EIP-8070]: https://eips.ethereum.org/EIPS/eip-8070
    pub fn clear_eip7594_blobs(&mut self) {
        self.blobs.clear();
    }

    /// 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> {
        if let [blob] = blobs.as_slice() {
            let blob = blob.as_ckzg();
            let commitment = settings.blob_to_kzg_commitment(blob)?;
            let (_cells, kzg_proofs) = settings.compute_cells_and_kzg_proofs(blob)?;
            let commitments = vec![Bytes48::from_ckzg(commitment.to_bytes())];
            let proofs = c_kzg::KzgProof::boxed_slice_as_alloy(kzg_proofs).into();
            return Ok(Self::new(blobs, commitments, proofs));
        }

        let mut commitments = Vec::with_capacity(blobs.len());
        let mut proofs = Vec::with_capacity(blobs.len() * CELLS_PER_EXT_BLOB);
        for blob in &blobs {
            let blob = blob.as_ckzg();
            let commitment = settings.blob_to_kzg_commitment(blob)?;
            let (_cells, kzg_proofs) = settings.compute_cells_and_kzg_proofs(blob)?;

            commitments.push(Bytes48::from_ckzg(commitment.to_bytes()));
            proofs.extend_from_slice(c_kzg::KzgProof::slice_as_alloy(kzg_proofs.as_ref()));
        }

        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 use the same blob-major flattened layout as [`Self::cell_proofs`]:
    /// every blob contributes one contiguous [`CELLS_PER_EXT_BLOB`]-cell chunk. For blob index
    /// `i` and cell index `j`, the cell is at `i * CELLS_PER_EXT_BLOB + j`.
    ///
    /// In other words, the layout is `[blob0_cell0, ..., blob0_cell127, blob1_cell0, ...]`.
    #[cfg(feature = "kzg")]
    pub fn compute_cells(&self) -> Result<Vec<crate::eip7594::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 use the same blob-major flattened layout as [`Self::cell_proofs`]:
    /// every blob contributes one contiguous [`CELLS_PER_EXT_BLOB`]-cell chunk. For blob index
    /// `i` and cell index `j`, the cell is at `i * CELLS_PER_EXT_BLOB + j`.
    ///
    /// In other words, the layout is `[blob0_cell0, ..., blob0_cell127, blob1_cell0, ...]`.
    #[cfg(feature = "kzg")]
    pub fn compute_cells_with_settings(
        &self,
        settings: &c_kzg::KzgSettings,
    ) -> Result<Vec<crate::eip7594::Cell>, c_kzg::Error> {
        if let [blob] = self.blobs.as_slice() {
            let blob_cells = settings.compute_cells(blob.as_ckzg())?;
            return Ok(c_kzg::Cell::boxed_slice_as_alloy(blob_cells).into());
        }

        let mut cells = Vec::with_capacity(self.blobs.len() * CELLS_PER_EXT_BLOB);
        for blob in &self.blobs {
            let blob_cells = settings.compute_cells(blob.as_ckzg())?;
            cells.extend_from_slice(c_kzg::Cell::slice_as_alloy(blob_cells.as_ref()));
        }
        Ok(cells)
    }

    /// Computes the EIP-7594 cells for all blobs and returns only the cells selected by
    /// `cell_mask`.
    ///
    /// The returned cells keep the blob-major order from [`Self::compute_cells`] but omit cells
    /// whose indices are not selected by `cell_mask`.
    ///
    /// This uses the default KZG settings.
    #[cfg(feature = "kzg")]
    pub fn compute_matching_cells(
        &self,
        cell_mask: BlobCellMask,
    ) -> Result<Vec<crate::eip7594::Cell>, c_kzg::Error> {
        use crate::eip4844::env_settings::EnvKzgSettings;

        self.compute_matching_cells_with_settings(cell_mask, EnvKzgSettings::Default.get())
    }

    /// Computes the EIP-7594 cells for all blobs with the given KZG settings and returns only the
    /// cells selected by `cell_mask`.
    ///
    /// The returned cells keep the blob-major order from [`Self::compute_cells_with_settings`] but
    /// omit cells whose indices are not selected by `cell_mask`.
    #[cfg(feature = "kzg")]
    pub fn compute_matching_cells_with_settings(
        &self,
        cell_mask: BlobCellMask,
        settings: &c_kzg::KzgSettings,
    ) -> Result<Vec<crate::eip7594::Cell>, c_kzg::Error> {
        let cells = self.compute_cells_with_settings(settings)?;
        Ok(cell_mask
            .matching_cells_from_computed_cells(&cells)
            .expect("computed cells must contain full extended blob cell chunks"))
    }

    /// 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));
        }

        let cells = if let [blob] = self.blobs.as_slice() {
            let cells: Box<[c_kzg::Cell]> = proof_settings.compute_cells(blob.as_ckzg())?;
            cells.into()
        } else {
            let mut cells = Vec::with_capacity(blobs_len * CELLS_PER_EXT_BLOB);
            for blob in &self.blobs {
                let blob_cells = proof_settings.compute_cells(blob.as_ckzg())?;
                cells.extend_from_slice(blob_cells.as_ref());
            }
            cells
        };

        let res = proof_settings.verify_cell_kzg_proof_batch(
            Bytes48::slice_as_ckzg(&commitments),
            &cell_indices,
            &cells,
            Bytes48::slice_as_ckzg(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<crate::eip4844::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<crate::eip4844::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(crate::eip4844::BlobCellsAndProofsV1::default()));
        }

        let cells = settings.compute_cells(blob.as_ckzg())?;

        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],
    ) -> crate::eip4844::BlobCellsAndProofsV1 {
        // The response needs two owned vectors, and `count()` exactly matches
        // `selected_indices()`, so this avoids reallocations while staying simple.
        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(cells.get(cell_index).map(|cell| crate::eip7594::Cell::new(cell.to_bytes())));
            selected_proofs.push(proofs.get(cell_index).copied());
        }

        crate::eip4844::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 = self
                        .cell_proofs
                        .get(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, [`crate::eip4844::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, crate::eip4844::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, [`crate::eip4844::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, crate::eip4844::BlobCellsAndProofsV1)> + 'a,
        c_kzg::Error,
    > {
        let mut matches = Vec::new();
        let mut cells_and_proofs_by_blob =
            Vec::<(usize, crate::eip4844::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 {
                    crate::eip4844::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 {
                    let cells = settings.compute_cells(blob.as_ckzg())?;
                    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)
    }
}

/// An error that can occur while recovering blobs from EIP-7594 cells.
#[cfg(feature = "kzg")]
#[derive(Debug)]
pub enum BlobCellRecoveryError {
    /// Fewer than half of the extended blob cells were selected.
    InsufficientCells {
        /// The number of cells supplied for each blob.
        provided: usize,
        /// The minimum number of cells required for recovery.
        required: usize,
    },
    /// The flattened cell slice does not match the commitments and cell mask.
    CellCountMismatch {
        /// The number of cells supplied.
        provided: usize,
        /// The number of cells implied by the commitments and cell mask.
        expected: usize,
    },
    /// The expected cell count cannot be represented as a `usize`.
    CellCountOverflow,
    /// A reconstructed blob does not match its supplied commitment.
    CommitmentMismatch {
        /// The index of the blob whose commitment did not match.
        blob_index: usize,
    },
    /// An error returned by [`c_kzg`].
    Kzg(c_kzg::Error),
}

#[cfg(feature = "kzg")]
impl core::fmt::Display for BlobCellRecoveryError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InsufficientCells { provided, required } => {
                write!(f, "need at least {required} cells per blob for recovery, got {provided}")
            }
            Self::CellCountMismatch { provided, expected } => {
                write!(f, "expected {expected} cells, got {provided}")
            }
            Self::CellCountOverflow => f.write_str("the expected cell count overflows usize"),
            Self::CommitmentMismatch { blob_index } => {
                write!(f, "reconstructed blob {blob_index} does not match its commitment")
            }
            Self::Kzg(err) => write!(f, "KZG error: {err:?}"),
        }
    }
}

#[cfg(feature = "kzg")]
impl core::error::Error for BlobCellRecoveryError {}

#[cfg(feature = "kzg")]
impl From<c_kzg::Error> for BlobCellRecoveryError {
    fn from(source: c_kzg::Error) -> Self {
        Self::Kzg(source)
    }
}

#[cfg(feature = "kzg")]
fn reconstruct_blob(recovered_cells: &[c_kzg::Cell; CELLS_PER_EXT_BLOB]) -> Blob {
    // `RecoverCells` returns cells in the canonical EIP-7594 order. The first half is the
    // original blob data; the remaining cells are the extension used for sampling and proofs.
    // The KZG backend performs the recovery, while this wrapper only materializes the original
    // blob cells.
    let mut blob = [0u8; BYTES_PER_BLOB];
    for (cell_index, cell) in recovered_cells.iter().take(CELLS_PER_EXT_BLOB / 2).enumerate() {
        let start = cell_index * crate::eip7594::BYTES_PER_CELL;
        let end = start + crate::eip7594::BYTES_PER_CELL;
        blob[start..end].copy_from_slice(cell.as_alloy().as_slice());
    }
    Blob::new(blob)
}

impl Encodable for BlobTransactionSidecarEip7594 {
    /// Encodes the sidecar as an RLP list, including its outer 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 an RLP list, including its outer 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)
    }
}

/// 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)
        })
    }

    /// Returns the selected cells from precomputed blob-major flattened cells.
    ///
    /// The `cells` slice must use the layout returned by `compute_cells`: each blob contributes
    /// one contiguous [`CELLS_PER_EXT_BLOB`]-cell chunk, so `cells.len()` must be evenly divisible
    /// by [`CELLS_PER_EXT_BLOB`] (128). This method returns `None` if `cells` ends with an
    /// incomplete chunk.
    ///
    /// The returned cells keep the same chunk order and include only the cell indices selected by
    /// this mask.
    pub fn matching_cells_from_computed_cells(
        self,
        cells: &[crate::eip7594::Cell],
    ) -> Option<Vec<crate::eip7594::Cell>> {
        let (chunks, remainder) = cells.as_chunks::<CELLS_PER_EXT_BLOB>();
        if !remainder.is_empty() {
            return None;
        }

        let mut matching_cells = Vec::with_capacity(chunks.len() * self.count());
        for blob_cells in chunks {
            for cell_index in self.selected_indices() {
                let cell = blob_cells
                    .get(cell_index)
                    .expect("cell mask index must be within extended blob cells");
                matching_cells.push(*cell);
            }
        }

        Some(matching_cells)
    }
}

/// 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 clear_eip7594_blobs_preserves_metadata() {
        let commitments = vec![Bytes48::repeat_byte(0x01)];
        let cell_proofs = vec![Bytes48::repeat_byte(0x02); CELLS_PER_EXT_BLOB];
        let sidecar = BlobTransactionSidecarEip7594::new(
            vec![Blob::repeat_byte(0x03)],
            commitments.clone(),
            cell_proofs.clone(),
        );
        let mut variant = BlobTransactionSidecarVariant::Eip7594(sidecar);

        variant.clear_eip7594_blobs();

        let sidecar = variant.as_eip7594().unwrap();
        assert!(sidecar.blobs.is_empty());
        assert_eq!(sidecar.commitments, commitments);
        assert_eq!(sidecar.cell_proofs, cell_proofs);
    }

    #[test]
    fn clear_eip7594_blobs_ignores_eip4844_variant() {
        let sidecar = BlobTransactionSidecar::new(
            vec![Blob::repeat_byte(0x01)],
            vec![Bytes48::repeat_byte(0x02)],
            vec![Bytes48::repeat_byte(0x03)],
        );
        let mut variant = BlobTransactionSidecarVariant::Eip4844(sidecar.clone());

        variant.clear_eip7594_blobs();

        assert_eq!(variant, BlobTransactionSidecarVariant::Eip4844(sidecar));
    }

    #[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);

        let cell_mask = BlobCellMask::from_bits((1u128 << 0) | (1u128 << 7));
        let matching_cells =
            sidecar.compute_matching_cells_with_settings(cell_mask, settings).unwrap();
        let expected_matching_cells = cells
            .as_chunks::<CELLS_PER_EXT_BLOB>()
            .0
            .iter()
            .flat_map(|blob_cells| [blob_cells[0], blob_cells[7]])
            .collect::<Vec<_>>();
        assert_eq!(
            cell_mask.matching_cells_from_computed_cells(&cells),
            Some(expected_matching_cells.clone())
        );
        assert_eq!(matching_cells, expected_matching_cells);
        assert_eq!(sidecar.compute_matching_cells(cell_mask).unwrap(), expected_matching_cells);
        assert!(sidecar.compute_matching_cells(BlobCellMask::default()).unwrap().is_empty());

        for (blob_index, blob) in sidecar.blobs.iter().enumerate() {
            let expected_cells = settings.compute_cells(blob.as_ckzg()).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, crate::eip7594::Cell::new(expected_cell.to_bytes()));
            }
        }
    }

    #[cfg(feature = "kzg")]
    fn sparse_cells_for_mask(
        sidecar: &BlobTransactionSidecarEip7594,
        cell_mask: BlobCellMask,
        settings: &c_kzg::KzgSettings,
    ) -> Vec<crate::eip7594::Cell> {
        let cells = sidecar.compute_cells_with_settings(settings).unwrap();
        cell_mask.matching_cells_from_computed_cells(&cells).unwrap()
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn recover_sidecar_from_complete_cells() {
        let settings = EnvKzgSettings::Default.get();
        assert_eq!(
            BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
                Vec::new(),
                BlobCellMask::default(),
                &[],
                settings,
            )
            .unwrap(),
            BlobTransactionSidecarEip7594::default()
        );

        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();
        let cell_mask = BlobCellMask::from_bits(u128::MAX);

        let recovered = BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
            sidecar.commitments.clone(),
            cell_mask,
            &cells,
            settings,
        )
        .unwrap();
        assert_eq!(recovered, sidecar);

        assert_eq!(
            BlobTransactionSidecarEip7594::try_recover_from_cells(
                recovered.commitments.clone(),
                cell_mask,
                &cells,
            )
            .unwrap(),
            recovered
        );
    }

    /// Multiple blobs are recovered from a shared, non-contiguous set containing the minimum
    /// number of cells required for each blob.
    #[test]
    #[cfg(feature = "kzg")]
    fn recover_sparse_blobs_from_minimum_cells() {
        let settings = EnvKzgSettings::Default.get();
        let sidecar = BlobTransactionSidecarEip7594::try_from_blobs_with_settings(
            vec![Blob::repeat_byte(0x01), Blob::repeat_byte(0x02), Blob::repeat_byte(0x03)],
            settings,
        )
        .unwrap();

        let cell_mask = BlobCellMask::from_bits(
            (0..CELLS_PER_EXT_BLOB).step_by(2).fold(0, |mask, index| mask | (1u128 << index)),
        );
        assert_eq!(cell_mask.count(), CELLS_PER_EXT_BLOB / 2);
        let sparse_cells = sparse_cells_for_mask(&sidecar, cell_mask, settings);

        let recovered = BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
            sidecar.commitments.clone(),
            cell_mask,
            &sparse_cells,
            settings,
        )
        .unwrap();

        assert_eq!(recovered.blobs, sidecar.blobs);
        assert_eq!(recovered.commitments, sidecar.commitments);
        assert_eq!(recovered.cell_proofs, sidecar.cell_proofs);
    }

    /// A sparse set above the minimum cell count follows the same recovery path.
    #[test]
    #[cfg(feature = "kzg")]
    fn recover_sparse_blobs_with_more_than_minimum_cells() {
        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 cell_mask = BlobCellMask::from_bits(
            ((1u128 << (CELLS_PER_EXT_BLOB / 2)) - 1) | (1u128 << (CELLS_PER_EXT_BLOB - 1)),
        );
        assert_eq!(cell_mask.count(), CELLS_PER_EXT_BLOB / 2 + 1);
        let sparse_cells = sparse_cells_for_mask(&sidecar, cell_mask, settings);

        let recovered = BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
            sidecar.commitments.clone(),
            cell_mask,
            &sparse_cells,
            settings,
        )
        .unwrap();

        assert_eq!(recovered.blobs, sidecar.blobs);
        assert_eq!(recovered.cell_proofs, sidecar.cell_proofs);
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn recover_sparse_blobs_rejects_insufficient_cells() {
        let settings = EnvKzgSettings::Default.get();
        let cell_mask = BlobCellMask::from_bits((1u128 << (CELLS_PER_EXT_BLOB / 2 - 1)) - 1);
        let cells = vec![crate::eip7594::Cell::repeat_byte(0); cell_mask.count()];

        let err = BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
            vec![Bytes48::ZERO],
            cell_mask,
            &cells,
            settings,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            BlobCellRecoveryError::InsufficientCells {
                provided,
                required,
            } if provided == CELLS_PER_EXT_BLOB / 2 - 1
                && required == CELLS_PER_EXT_BLOB / 2
        ));
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn recover_sparse_blobs_rejects_mismatched_cell_count() {
        let settings = EnvKzgSettings::Default.get();
        let cell_mask = BlobCellMask::from_bits((1u128 << (CELLS_PER_EXT_BLOB / 2)) - 1);
        let cells = vec![crate::eip7594::Cell::repeat_byte(0); cell_mask.count() - 1];

        let err = BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
            vec![Bytes48::ZERO, Bytes48::ZERO],
            cell_mask,
            &cells,
            settings,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            BlobCellRecoveryError::CellCountMismatch {
                provided,
                expected,
            } if provided == CELLS_PER_EXT_BLOB / 2 - 1 && expected == CELLS_PER_EXT_BLOB
        ));
    }

    #[test]
    #[cfg(feature = "kzg")]
    fn recover_sparse_blobs_rejects_commitment_mismatch() {
        let settings = EnvKzgSettings::Default.get();
        let sidecar = BlobTransactionSidecarEip7594::try_from_blobs_with_settings(
            vec![Blob::repeat_byte(0x01)],
            settings,
        )
        .unwrap();
        let cell_mask = BlobCellMask::from_bits((1u128 << (CELLS_PER_EXT_BLOB / 2)) - 1);
        let sparse_cells = sparse_cells_for_mask(&sidecar, cell_mask, settings);

        let err = BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
            vec![Bytes48::ZERO],
            cell_mask,
            &sparse_cells,
            settings,
        )
        .unwrap_err();
        assert!(matches!(err, BlobCellRecoveryError::CommitmentMismatch { blob_index: 0 }));
    }

    /// A cell that no longer matches the commitment must not produce a sidecar.
    #[test]
    #[cfg(feature = "kzg")]
    fn recover_sparse_blobs_rejects_corrupted_cells() {
        let settings = EnvKzgSettings::Default.get();
        let sidecar = BlobTransactionSidecarEip7594::try_from_blobs_with_settings(
            vec![Blob::repeat_byte(0x01), Blob::repeat_byte(0x02), Blob::repeat_byte(0x03)],
            settings,
        )
        .unwrap();
        let cell_mask = BlobCellMask::from_bits((1u128 << (CELLS_PER_EXT_BLOB / 2)) - 1);
        let mut sparse_cells = sparse_cells_for_mask(&sidecar, cell_mask, settings);
        sparse_cells[0][0] ^= 0xff;

        assert!(BlobTransactionSidecarEip7594::try_recover_from_cells_with_settings(
            sidecar.commitments,
            cell_mask,
            &sparse_cells,
            settings,
        )
        .is_err());
    }

    #[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]);

        let cells = (0..CELLS_PER_EXT_BLOB * 2)
            .map(|i| crate::eip7594::Cell::repeat_byte(i as u8))
            .collect::<Vec<_>>();
        assert_eq!(
            mask.matching_cells_from_computed_cells(&cells),
            Some(vec![
                cells[0],
                cells[7],
                cells[CELLS_PER_EXT_BLOB],
                cells[CELLS_PER_EXT_BLOB + 7]
            ])
        );
        assert_eq!(mask.matching_cells_from_computed_cells(&cells[..cells.len() - 1]), None);
    }

    #[test]
    fn match_versioned_hashes_skips_incomplete_proof_chunks() {
        let sidecar = BlobTransactionSidecarEip7594::new(
            vec![Blob::repeat_byte(0x01)],
            vec![Bytes48::repeat_byte(0x02)],
            vec![Bytes48::repeat_byte(0x03)],
        );
        let versioned_hash = sidecar.versioned_hashes().next().unwrap();

        let matches = sidecar.match_versioned_hashes(&[versioned_hash]).collect::<Vec<_>>();
        assert!(matches.is_empty());
    }

    #[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])]
        );

        let expected_cells = settings.compute_cells(sidecar.blobs[0].as_ckzg()).unwrap();
        assert_eq!(
            cells_and_proofs.blob_cells,
            vec![
                Some(crate::eip7594::Cell::new(expected_cells[0].to_bytes())),
                Some(crate::eip7594::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);
        assert!(settings.compute_cells(invalid_blob.as_ckzg()).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)]);
    }
}