tidecoin-primitives 0.102.0

Primitive types used by the rust-tidecoin ecosystem
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
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
// SPDX-License-Identifier: CC0-1.0

//! Tidecoin blocks.
//!
//! A block is a bundle of transactions with a proof-of-work attached,
//! which commits to an earlier block to form the blockchain. This
//! module describes structures and functions needed to describe
//! these blocks and the blockchain.

use core::convert::Infallible;
use core::fmt;
#[cfg(feature = "alloc")]
use core::marker::PhantomData;
#[cfg(feature = "alloc")]
use core::mem;

#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use encoding::{ArrayDecoder, Decoder6, Encodable as _, Encoder as _};
#[cfg(feature = "alloc")]
use encoding::{CompactSizeEncoder, Decoder2, Encoder2, SliceEncoder, VecDecoder};
use hashes::{sha256d, HashEngine as _};
use internals::write_err;
#[cfg(feature = "alloc")]
use internals::ToU64 as _;

#[cfg(feature = "hex")]
use crate::hex_codec::{HexPrimitive, ParsePrimitiveError};
#[cfg(feature = "alloc")]
use crate::merkle_tree::WitnessMerkleNode;
use crate::merkle_tree::{TxMerkleNode, TxMerkleNodeDecoder, TxMerkleNodeDecoderError};
use crate::pow::{CompactTargetDecoder, CompactTargetDecoderError};
#[cfg(feature = "alloc")]
use crate::prelude::{Box, Vec};
#[cfg(feature = "alloc")]
use crate::script::{ScriptPubKeyBuf, ScriptSigBuf};
use crate::time::{BlockTimeDecoder, BlockTimeDecoderError};
#[cfg(feature = "alloc")]
use crate::transaction::{check_transaction_sanity, TransactionSanityError};
#[cfg(feature = "alloc")]
use crate::{Amount, Transaction, TxIn, TxOut, Weight, Wtxid};
use crate::{BlockTime, CompactTarget};

#[rustfmt::skip]                // Keep public re-exports separate.
#[doc(inline)]
pub use units::block::{error, BlockHeight, BlockHeightDecoder, BlockHeightEncoder, BlockHeightInterval, BlockMtp, BlockMtpInterval};
// Re-export errors that appear directly in the API - but no doc inline.
#[doc(no_inline)]
pub use units::block::{BlockHeightDecoderError, TooBigForRelativeHeightError};

#[doc(inline)]
pub use crate::hash_types::{
    BlockHash, BlockHashDecoder, BlockHashDecoderError, BlockHashEncoder, WitnessCommitment,
};

/// The maximum allowed legacy signature operation cost in a block.
#[cfg(feature = "alloc")]
pub const MAX_BLOCK_SIGOPS_COST: usize = 80_000;

/// Marker for whether or not a block has been validated.
///
/// We define valid as:
///
/// * The Merkle root of the header matches Merkle root of the transaction list.
/// * The witness commitment in coinbase matches the transaction list.
///
/// See [`Block::validate`].
#[cfg(feature = "alloc")]
pub trait Validation: sealed::Validation + Sync + Send + Sized + Unpin {
    /// Indicates whether this `Validation` is `Checked` or not.
    const IS_CHECKED: bool;
}

/// Tidecoin block.
///
/// A collection of transactions with an attached proof of work.
#[cfg(feature = "alloc")]
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Block<V = Unchecked>
where
    V: Validation,
{
    /// The block header
    header: Header,
    /// List of transactions contained in the block
    transactions: Vec<Transaction>,
    /// Cached witness root if it's been computed.
    witness_root: Option<WitnessMerkleNode>,
    /// Validation marker.
    _marker: PhantomData<V>,
}

#[cfg(feature = "alloc")]
impl Block<Unchecked> {
    /// Constructs a new `Block` without doing any validation.
    #[inline]
    pub fn new_unchecked(header: Header, transactions: Vec<Transaction>) -> Self {
        Self { header, transactions, witness_root: None, _marker: PhantomData::<Unchecked> }
    }

    /// Ignores block validation logic and just assumes you know what you are doing.
    ///
    /// You should only use this function if you trust the block i.e., it comes from a trusted node.
    #[must_use]
    #[inline]
    pub fn assume_checked(self, witness_root: Option<WitnessMerkleNode>) -> Block<Checked> {
        Block {
            header: self.header,
            transactions: self.transactions,
            witness_root,
            _marker: PhantomData::<Checked>,
        }
    }

    /// Decomposes block into its constituent parts.
    #[inline]
    pub fn into_parts(self) -> (Header, Vec<Transaction>) {
        (self.header, self.transactions)
    }

    /// Returns the constituent parts of the block by reference.
    #[inline]
    pub fn as_parts(&self) -> (&Header, &[Transaction]) {
        (&self.header, &self.transactions)
    }

    /// Validates (or checks) a block.
    ///
    /// This performs the node-aligned context-free `CheckBlock` sanity rules,
    /// then verifies witness commitment and full block weight so the returned
    /// checked block can safely cache the witness root.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidBlockError`] if context-free block sanity, witness
    /// commitment validation, or full block weight validation fails.
    pub fn validate(self) -> Result<Block<Checked>, InvalidBlockError> {
        check_block_sanity_inner(&self).map_err(InvalidBlockError::from)?;
        let witness_root =
            check_block_witness_and_weight(&self).map_err(InvalidBlockError::from)?;
        let block = Self::new_unchecked(self.header, self.transactions);
        Ok(block.assume_checked(witness_root))
    }

    /// Checks if Merkle root of header matches Merkle root of the transaction list.
    pub fn check_merkle_root(&self) -> bool {
        match compute_merkle_root(&self.transactions) {
            Some(merkle_root) => self.header.merkle_root == merkle_root,
            None => false,
        }
    }

    /// Computes the witness commitment for a list of transactions.
    pub fn compute_witness_commitment(
        &self,
        witness_reserved_value: &[u8],
    ) -> Option<(WitnessMerkleNode, WitnessCommitment)> {
        compute_witness_root(&self.transactions).map(|witness_root| {
            let mut encoder = sha256d::Hash::engine();
            encoder = hashes::encode_to_engine(&witness_root, encoder);
            encoder.input(witness_reserved_value);
            let witness_commitment = WitnessCommitment::from_byte_array(
                sha256d::Hash::from_engine(encoder).to_byte_array(),
            );
            (witness_root, witness_commitment)
        })
    }

    /// Checks if witness commitment in coinbase matches the transaction list.
    // Returns the Merkle root if it was computed (so it can be cached in `assume_checked`).
    pub fn check_witness_commitment(&self) -> (bool, Option<WitnessMerkleNode>) {
        if self.transactions.is_empty() {
            return (false, None);
        }

        // Witness commitment is optional if there are no transactions using SegWit in the block.
        if self.transactions.iter().all(|t| t.inputs.iter().all(|i| i.witness.is_empty())) {
            return (true, None);
        }

        if self.transactions[0].is_coinbase() {
            let coinbase = self.transactions[0].clone();
            if let Some(commitment) = witness_commitment_from_coinbase(&coinbase) {
                // Witness reserved value is in coinbase input witness.
                let witness_vec: Vec<_> = coinbase.inputs[0].witness.iter().collect();
                if witness_vec.len() == 1 && witness_vec[0].len() == 32 {
                    if let Some((witness_root, witness_commitment)) =
                        self.compute_witness_commitment(witness_vec[0])
                    {
                        if commitment == witness_commitment {
                            return (true, Some(witness_root));
                        }
                    }
                }
            }
        }

        (false, None)
    }
}

/// Checks Tidecoin context-free block sanity rules.
///
/// This mirrors the node's `CheckBlock` rules that do not depend on UTXO state,
/// previous-block context, script execution, or witness commitment state.
/// Header PoW/AuxPoW validation is intentionally separate.
///
/// # Errors
///
/// Returns [`BlockSanityError`] when the block violates a context-free
/// Tidecoin block sanity rule.
#[cfg(feature = "alloc")]
pub fn check_block_sanity(block: &Block<Unchecked>) -> Result<(), BlockSanityError> {
    check_block_sanity_inner(block)
}

#[cfg(feature = "alloc")]
fn check_block_sanity_inner(block: &Block<Unchecked>) -> Result<(), BlockSanityError> {
    if block.transactions.is_empty() {
        return Err(BlockSanityError::NoTransactions);
    }

    if block.transactions.len().to_u64().saturating_mul(Weight::WITNESS_SCALE_FACTOR)
        > Weight::MAX_BLOCK.to_wu()
    {
        return Err(BlockSanityError::SizeLimits);
    }

    if block.base_size().to_u64().saturating_mul(Weight::WITNESS_SCALE_FACTOR)
        > Weight::MAX_BLOCK.to_wu()
    {
        return Err(BlockSanityError::SizeLimits);
    }

    if !block.transactions[0].is_coinbase() {
        return Err(BlockSanityError::MissingCoinbase);
    }

    for (index, tx) in block.transactions.iter().enumerate().skip(1) {
        if tx.is_coinbase() {
            return Err(BlockSanityError::MultipleCoinbase { index });
        }
    }

    match compute_merkle_root(&block.transactions) {
        Some(merkle_root) if block.header.merkle_root == merkle_root => {}
        Some(_) => return Err(BlockSanityError::InvalidMerkleRoot),
        None => return Err(BlockSanityError::MutatedMerkleRoot),
    }

    for (index, tx) in block.transactions.iter().enumerate() {
        check_transaction_sanity(tx)
            .map_err(|err| BlockSanityError::Transaction { index, source: err })?;
    }

    let legacy_sigop_cost = block
        .transactions
        .iter()
        .map(transaction_legacy_sigop_count)
        .sum::<usize>()
        .saturating_mul(Weight::WITNESS_SCALE_FACTOR as usize);
    if legacy_sigop_cost > MAX_BLOCK_SIGOPS_COST {
        return Err(BlockSanityError::TooManyLegacySigops { cost: legacy_sigop_cost });
    }

    Ok(())
}

/// Checks witness commitment and full witness-inclusive block weight.
///
/// The Tidecoin node performs these in `ContextualCheckBlock`, after
/// `CheckBlock`, because witness data can change block weight without changing
/// the block hash.
///
/// # Errors
///
/// Returns [`BlockSanityError::InvalidWitnessCommitment`] if the witness
/// commitment is invalid, or [`BlockSanityError::WeightLimit`] if the
/// witness-inclusive block weight exceeds consensus limits.
#[cfg(feature = "alloc")]
pub fn check_block_witness_and_weight(
    block: &Block<Unchecked>,
) -> Result<Option<WitnessMerkleNode>, BlockSanityError> {
    let (witness_valid, witness_root) = block.check_witness_commitment();
    if !witness_valid {
        return Err(BlockSanityError::InvalidWitnessCommitment);
    }

    if block.weight().to_wu() > Weight::MAX_BLOCK.to_wu() {
        return Err(BlockSanityError::WeightLimit);
    }

    Ok(witness_root)
}

#[cfg(feature = "alloc")]
fn transaction_legacy_sigop_count(tx: &Transaction) -> usize {
    tx.inputs
        .iter()
        .map(|input| input.script_sig.count_sigops_legacy())
        .sum::<usize>()
        .saturating_add(
            tx.outputs
                .iter()
                .map(|output| output.script_pubkey.count_sigops_legacy())
                .sum::<usize>(),
        )
}

#[cfg(feature = "alloc")]
impl Block<Checked> {
    /// Gets a reference to the block header.
    #[inline]
    pub fn header(&self) -> &Header {
        &self.header
    }

    /// Gets a reference to the block's list of transactions.
    #[inline]
    pub fn transactions(&self) -> &[Transaction] {
        &self.transactions
    }

    /// Returns the cached witness root if one is present.
    ///
    /// It is assumed that a block will have the witness root calculated and cached as part of the
    /// validation process.
    #[inline]
    pub fn cached_witness_root(&self) -> Option<WitnessMerkleNode> {
        self.witness_root
    }
}

#[cfg(feature = "alloc")]
impl<V: Validation> Block<V> {
    /// Returns the block hash.
    #[inline]
    pub fn block_hash(&self) -> BlockHash {
        self.header.block_hash()
    }

    /// Returns the block weight.
    ///
    /// Block weight is base size multiplied by three plus total size.
    #[inline]
    pub fn weight(&self) -> Weight {
        Weight::from_wu((self.base_size() * 3 + self.total_size()).to_u64())
    }

    /// Returns the base block size, with transaction witness data stripped.
    #[inline]
    pub fn base_size(&self) -> usize {
        self.header.serialized_len()
            + CompactSizeEncoder::encoded_size(self.transactions.len())
            + self.transactions.iter().map(Transaction::base_size).sum::<usize>()
    }

    /// Returns the total block size under canonical block serialization.
    #[inline]
    pub fn total_size(&self) -> usize {
        self.header.serialized_len()
            + CompactSizeEncoder::encoded_size(self.transactions.len())
            + self.transactions.iter().map(Transaction::total_size).sum::<usize>()
    }
}

#[cfg(feature = "alloc")]
impl From<Block> for BlockHash {
    #[inline]
    fn from(block: Block) -> Self {
        block.block_hash()
    }
}

#[cfg(feature = "alloc")]
impl From<&Block> for BlockHash {
    #[inline]
    fn from(block: &Block) -> Self {
        block.block_hash()
    }
}

/// Marker that the block's merkle root has been successfully validated.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg(feature = "alloc")]
pub enum Checked {}

#[cfg(feature = "alloc")]
impl Validation for Checked {
    const IS_CHECKED: bool = true;
}

/// Marker that the block's merkle root has not been validated.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg(feature = "alloc")]
pub enum Unchecked {}

#[cfg(feature = "alloc")]
impl Validation for Unchecked {
    const IS_CHECKED: bool = false;
}

#[cfg(feature = "alloc")]
mod sealed {
    /// Seals the block validation marker traits.
    pub trait Validation {}
    impl Validation for super::Checked {}
    impl Validation for super::Unchecked {}
}

#[cfg(all(feature = "hex", feature = "alloc"))]
impl core::str::FromStr for Block<Unchecked>
where
    Self: encoding::Decodable,
{
    type Err = ParseBlockError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        HexPrimitive::from_str(s).map_err(ParseBlockError)
    }
}

#[cfg(all(feature = "hex", feature = "alloc"))]
impl<V: Validation> fmt::Display for Block<V>
where
    Self: encoding::Encodable,
{
    #[allow(clippy::use_self)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&HexPrimitive(self), f)
    }
}

#[cfg(all(feature = "hex", feature = "alloc"))]
impl<V: Validation> fmt::LowerHex for Block<V> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::LowerHex::fmt(&HexPrimitive(self), f)
    }
}

#[cfg(all(feature = "hex", feature = "alloc"))]
impl<V: Validation> fmt::UpperHex for Block<V> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::UpperHex::fmt(&HexPrimitive(self), f)
    }
}

/// An error that occurs during parsing of a [`Block`] from a hex string.
#[cfg(all(feature = "hex", feature = "alloc"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseBlockError(ParsePrimitiveError<Block>);

#[cfg(all(feature = "hex", feature = "alloc"))]
impl From<Infallible> for ParseBlockError {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

#[cfg(all(feature = "hex", feature = "alloc"))]
impl fmt::Display for ParseBlockError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_err!(f, "parse block error"; self.0)
    }
}

#[cfg(all(feature = "hex", feature = "alloc", feature = "std"))]
impl std::error::Error for ParseBlockError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

#[cfg(feature = "alloc")]
encoding::encoder_newtype! {
    /// The encoder for the [`Block`] type.
    pub struct BlockEncoder<'e>(
        Encoder2<HeaderEncoder<'e>, Encoder2<CompactSizeEncoder, SliceEncoder<'e, Transaction>>>
    );
}

#[cfg(feature = "alloc")]
impl<V> encoding::Encodable for Block<V>
where
    V: Validation,
{
    type Encoder<'e>
        = Encoder2<HeaderEncoder<'e>, Encoder2<CompactSizeEncoder, SliceEncoder<'e, Transaction>>>
    where
        Self: 'e;

    fn encoder(&self) -> Self::Encoder<'_> {
        Encoder2::new(
            self.header.encoder(),
            Encoder2::new(
                CompactSizeEncoder::new(self.transactions.len()),
                SliceEncoder::without_length_prefix(&self.transactions),
            ),
        )
    }
}

#[cfg(feature = "alloc")]
type BlockInnerDecoder = Decoder2<HeaderDecoder, VecDecoder<Transaction>>;

/// The decoder for the [`Block`] type.
///
/// This decoder can only produce a `Block<Unchecked>`.
#[cfg(feature = "alloc")]
pub struct BlockDecoder(BlockInnerDecoder);

#[cfg(feature = "alloc")]
impl BlockDecoder {
    /// Constructs a new [`Block`] decoder.
    pub const fn new() -> Self {
        Self(Decoder2::new(HeaderDecoder::new(), VecDecoder::new()))
    }
}

#[cfg(feature = "alloc")]
impl Default for BlockDecoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "alloc")]
impl encoding::Decoder for BlockDecoder {
    type Output = Block;
    type Error = BlockDecoderError;

    #[inline]
    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
        self.0.push_bytes(bytes).map_err(BlockDecoderError)
    }

    #[inline]
    fn end(self) -> Result<Self::Output, Self::Error> {
        let (header, transactions) = self.0.end().map_err(BlockDecoderError)?;
        Ok(Self::Output::new_unchecked(header, transactions))
    }

    #[inline]
    fn read_limit(&self) -> usize {
        self.0.read_limit()
    }
}

#[cfg(feature = "alloc")]
impl encoding::Decodable for Block<Unchecked> {
    type Decoder = BlockDecoder;
    fn decoder() -> Self::Decoder {
        BlockDecoder(Decoder2::new(Header::decoder(), VecDecoder::<Transaction>::new()))
    }
}

/// An error consensus decoding a [`Block`].
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockDecoderError(<BlockInnerDecoder as encoding::Decoder>::Error);

#[cfg(feature = "alloc")]
impl From<Infallible> for BlockDecoderError {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

#[cfg(feature = "alloc")]
impl fmt::Display for BlockDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_err!(f, "block decoder error"; self.0)
    }
}

#[cfg(feature = "alloc")]
#[cfg(feature = "std")]
impl std::error::Error for BlockDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

/// Invalid block error.
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvalidBlockError {
    /// Header Merkle root does not match the calculated Merkle root.
    InvalidMerkleRoot,
    /// The witness commitment in coinbase transaction does not match the calculated `witness_root`.
    InvalidWitnessCommitment,
    /// Block has no transactions (missing coinbase).
    NoTransactions,
    /// The first transaction is not a valid coinbase transaction.
    InvalidCoinbase,
    /// A context-free block sanity rule failed.
    Sanity(BlockSanityError),
}

#[cfg(feature = "alloc")]
impl From<Infallible> for InvalidBlockError {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

#[cfg(feature = "alloc")]
impl From<BlockSanityError> for InvalidBlockError {
    fn from(err: BlockSanityError) -> Self {
        match err {
            BlockSanityError::InvalidMerkleRoot => Self::InvalidMerkleRoot,
            BlockSanityError::InvalidWitnessCommitment => Self::InvalidWitnessCommitment,
            BlockSanityError::NoTransactions => Self::NoTransactions,
            BlockSanityError::MissingCoinbase => Self::InvalidCoinbase,
            other => Self::Sanity(other),
        }
    }
}

#[cfg(feature = "alloc")]
impl fmt::Display for InvalidBlockError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::InvalidMerkleRoot => {
                write!(f, "header Merkle root does not match the calculated Merkle root")
            }
            Self::InvalidWitnessCommitment => write!(
                f,
                "the witness commitment in coinbase transaction does not match the calculated witness_root"
            ),
            Self::NoTransactions => write!(f, "block has no transactions (missing coinbase)"),
            Self::InvalidCoinbase => {
                write!(f, "the first transaction is not a valid coinbase transaction")
            }
            Self::Sanity(err) => write_err!(f, "block sanity error"; err),
        }
    }
}

#[cfg(feature = "alloc")]
#[cfg(feature = "std")]
impl std::error::Error for InvalidBlockError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Sanity(err) => Some(err),
            _ => None,
        }
    }
}

/// Context-free block sanity error.
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BlockSanityError {
    /// Header Merkle root does not match the calculated Merkle root.
    InvalidMerkleRoot,
    /// Transaction merkle tree mutation was detected.
    MutatedMerkleRoot,
    /// The witness commitment in coinbase transaction does not match the calculated `witness_root`.
    InvalidWitnessCommitment,
    /// Block has no transactions.
    NoTransactions,
    /// The first transaction is not a valid coinbase transaction.
    MissingCoinbase,
    /// A non-first transaction is a coinbase transaction.
    MultipleCoinbase {
        /// Invalid transaction index.
        index: usize,
    },
    /// Block failed context-free transaction sanity.
    Transaction {
        /// Invalid transaction index.
        index: usize,
        /// Transaction sanity error.
        source: TransactionSanityError,
    },
    /// Block exceeds context-free serialized-size limits.
    SizeLimits,
    /// Block exceeds the full weight limit.
    WeightLimit,
    /// Block exceeds the legacy sigop cost limit.
    TooManyLegacySigops {
        /// Computed sigop cost.
        cost: usize,
    },
}

#[cfg(feature = "alloc")]
impl fmt::Display for BlockSanityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidMerkleRoot => {
                write!(f, "header Merkle root does not match the calculated Merkle root")
            }
            Self::MutatedMerkleRoot => write!(f, "transaction merkle tree is mutated"),
            Self::InvalidWitnessCommitment => write!(
                f,
                "the witness commitment in coinbase transaction does not match the calculated witness_root"
            ),
            Self::NoTransactions => write!(f, "block has no transactions"),
            Self::MissingCoinbase => {
                write!(f, "the first transaction is not a valid coinbase transaction")
            }
            Self::MultipleCoinbase { index } => {
                write!(f, "non-first transaction {} is coinbase", index)
            }
            Self::Transaction { index, source } => {
                write_err!(f, "transaction sanity failed at index {}", index; source)
            }
            Self::SizeLimits => write!(f, "block context-free size limits failed"),
            Self::WeightLimit => write!(f, "block weight limit failed"),
            Self::TooManyLegacySigops { cost } => {
                write!(f, "block legacy sigop cost {} exceeds {}", cost, MAX_BLOCK_SIGOPS_COST)
            }
        }
    }
}

#[cfg(all(feature = "alloc", feature = "std"))]
impl std::error::Error for BlockSanityError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Transaction { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Computes the Merkle root for a list of transactions.
///
/// Returns `None` if the iterator was empty, or if the transaction list contains
/// consecutive duplicates which would trigger CVE 2012-2459. Blocks with duplicate
/// transactions will always be invalid, so there is no harm in us refusing to
/// compute their merkle roots.
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the `Option` returned by this method!
#[cfg(feature = "alloc")]
pub fn compute_merkle_root(transactions: &[Transaction]) -> Option<TxMerkleNode> {
    let hashes = transactions.iter().map(Transaction::compute_txid);
    TxMerkleNode::calculate_root(hashes)
}

/// Computes the Merkle root of transactions hashed for witness.
///
/// Returns `None` if the iterator was empty, or if the transaction list contains
/// consecutive duplicates which would trigger CVE 2012-2459. Blocks with duplicate
/// transactions will always be invalid, so there is no harm in us refusing to
/// compute their merkle roots.
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the `Option` returned by this method!
#[cfg(feature = "alloc")]
pub fn compute_witness_root(transactions: &[Transaction]) -> Option<WitnessMerkleNode> {
    let hashes = transactions.iter().enumerate().map(|(i, t)| {
        if i == 0 {
            // Replace the first hash with zeroes.
            Wtxid::COINBASE
        } else {
            t.compute_wtxid()
        }
    });
    WitnessMerkleNode::calculate_root(hashes)
}

#[cfg(feature = "alloc")]
fn witness_commitment_from_coinbase(coinbase: &Transaction) -> Option<WitnessCommitment> {
    // Consists of OP_RETURN, OP_PUSHBYTES_36, and four "witness header" bytes.
    const MAGIC: [u8; 6] = [0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed];

    if !coinbase.is_coinbase() {
        return None;
    }

    // Commitment is in the last output that starts with magic bytes.
    if let Some(pos) = coinbase
        .outputs
        .iter()
        .rposition(|o| o.script_pubkey.len() >= 38 && o.script_pubkey.as_bytes()[0..6] == MAGIC)
    {
        let bytes =
            <[u8; 32]>::try_from(&coinbase.outputs[pos].script_pubkey.as_bytes()[6..38]).unwrap();
        Some(WitnessCommitment::from_byte_array(bytes))
    } else {
        None
    }
}

/// Merge-mining auxpow payload appended to a Tidecoin block header when the auxpow version bit is set.
#[cfg(feature = "alloc")]
#[derive(PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
pub struct AuxPow {
    /// The parent block's coinbase transaction.
    pub coinbase_tx: Transaction,
    /// The merkle branch of the coinbase transaction to the parent block merkle root.
    pub merkle_branch: Vec<BlockHash>,
    /// The merkle branch linking the Tidecoin block hash into the coinbase commitment.
    pub chain_merkle_branch: Vec<BlockHash>,
    /// Merkle tree index of the aux block hash in the coinbase.
    pub chain_index: i32,
    /// Parent block header. This is always encoded as a pure 80-byte header.
    pub parent_block: Header,
}

#[cfg(feature = "alloc")]
impl AuxPow {
    fn consensus_len(&self) -> usize {
        let encoder = self.encoder();
        encoding::ExactSizeEncoder::len(&encoder)
    }

    /// Creates the minimal auxpow payload used by the Tidecoin node serialization tests.
    ///
    /// # Panics
    ///
    /// Panics if the fixed merged-mining commitment no longer fits in a single-byte script push.
    pub fn minimal_for_header(header: &Header) -> Self {
        debug_assert!(header.version.is_auxpow());

        let mut input_data = header.block_hash().to_byte_array().to_vec();
        input_data.reverse();
        input_data.push(1);
        input_data.extend_from_slice(&[0; 7]);

        let mut script_sig = Vec::with_capacity(1 + input_data.len());
        script_sig.push(u8::try_from(input_data.len()).expect("merged-mining commitment is small"));
        script_sig.extend_from_slice(&input_data);

        let coinbase_tx = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: Vec::from([TxIn {
                script_sig: ScriptSigBuf::from_bytes(script_sig),
                ..TxIn::EMPTY_COINBASE
            }]),
            outputs: Vec::from([TxOut {
                amount: Amount::ZERO,
                script_pubkey: ScriptPubKeyBuf::new(),
            }]),
        };

        let parent_block = Header {
            version: Version::ONE,
            prev_blockhash: BlockHash::from_byte_array([0; 32]),
            merkle_root: compute_merkle_root(core::slice::from_ref(&coinbase_tx))
                .expect("single coinbase transaction has a merkle root"),
            time: BlockTime::from_u32(0),
            bits: CompactTarget::from_consensus(0),
            nonce: 0,
            auxpow: None,
        };

        Self {
            coinbase_tx,
            merkle_branch: Vec::new(),
            chain_merkle_branch: Vec::new(),
            chain_index: 0,
            parent_block,
        }
    }
}

fn sha256d_hash_encoder(mut encoder: impl encoding::Encoder) -> sha256d::Hash {
    let mut enc = sha256d::Hash::engine();
    loop {
        enc.input(encoder.current_chunk());
        if !encoder.advance() {
            break;
        }
    }

    enc.finalize()
}

/// Tidecoin block header.
///
/// Contains all the block's information except the actual transactions, but
/// including a root of a [Merkle tree] committing to all transactions in the block.
///
/// [Merkle tree]: https://en.wikipedia.org/wiki/Merkle_tree
#[derive(PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
pub struct Header {
    /// Block version, now repurposed for soft fork signalling.
    pub version: Version,
    /// Reference to the previous block in the chain.
    pub prev_blockhash: BlockHash,
    /// The root hash of the Merkle tree of transactions in the block.
    pub merkle_root: TxMerkleNode,
    /// The timestamp of the block, as claimed by the miner.
    pub time: BlockTime,
    /// The target value below which the blockhash must lie.
    pub bits: CompactTarget,
    /// The nonce, selected to obtain a low enough blockhash.
    pub nonce: u32,
    /// Optional auxpow payload appended to the header when the auxpow version bit is set.
    #[cfg(feature = "alloc")]
    pub auxpow: Option<Box<AuxPow>>,
}

impl Header {
    /// The number of bytes that the block header contributes to the size of a block.
    // Serialized length of fields (version, prev_blockhash, merkle_root, time, bits, nonce)
    pub const SIZE: usize = 4 + 32 + 32 + 4 + 4 + 4; // 80

    /// Returns the serialized header length, including auxpow when present.
    #[cfg(feature = "alloc")]
    pub fn serialized_len(&self) -> usize {
        Self::SIZE + self.auxpow.as_ref().map_or(0, |auxpow| auxpow.consensus_len())
    }

    /// Returns the block hash.
    // This hashes only the six standard header fields; auxpow is not committed by the block hash.
    pub fn block_hash(&self) -> BlockHash {
        let bare_hash = sha256d_hash_encoder(self.pure_encoder());
        BlockHash::from_byte_array(bare_hash.to_byte_array())
    }

    /// Returns the pure 80-byte header serialization used by mining hashes.
    ///
    /// `AuxPoW` payload bytes are intentionally excluded. Tidecoin's block hash,
    /// yespower mining hash, scrypt mining hash, and `AuxPoW` parent-header hash
    /// all operate over the pure header fields only.
    pub fn pure_header_bytes(&self) -> [u8; Self::SIZE] {
        let mut out = [0u8; Self::SIZE];
        let mut offset = 0;
        let mut encoder = self.pure_encoder();
        loop {
            let chunk = encoder.current_chunk();
            out[offset..offset + chunk.len()].copy_from_slice(chunk);
            offset += chunk.len();
            if !encoder.advance() {
                break;
            }
        }
        debug_assert_eq!(offset, Self::SIZE);
        out
    }

    fn pure_encoder(&self) -> PureHeaderEncoder<'_> {
        PureHeaderEncoder::new(encoding::Encoder6::new(
            self.version.encoder(),
            self.prev_blockhash.encoder(),
            self.merkle_root.encoder(),
            self.time.encoder(),
            self.bits.encoder(),
            encoding::ArrayEncoder::without_length_prefix(self.nonce.to_le_bytes()),
        ))
    }
}

#[cfg(feature = "hex")]
impl core::str::FromStr for Header {
    type Err = ParseHeaderError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        HexPrimitive::from_str(s).map_err(ParseHeaderError)
    }
}

#[cfg(feature = "hex")]
impl fmt::Display for Header {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&HexPrimitive(self), f)
    }
}

#[cfg(feature = "hex")]
impl fmt::LowerHex for Header {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::LowerHex::fmt(&HexPrimitive(self), f)
    }
}

#[cfg(feature = "hex")]
impl fmt::UpperHex for Header {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::UpperHex::fmt(&HexPrimitive(self), f)
    }
}

impl fmt::Debug for Header {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut dbg = f.debug_struct("Header");
        dbg.field("block_hash", &self.block_hash())
            .field("version", &self.version)
            .field("prev_blockhash", &self.prev_blockhash)
            .field("merkle_root", &self.merkle_root)
            .field("time", &self.time)
            .field("bits", &self.bits)
            .field("nonce", &self.nonce);
        #[cfg(feature = "alloc")]
        dbg.field("auxpow", &self.auxpow);
        dbg.finish()
    }
}

/// An error that occurs during parsing of a [`Header`] from a hex string.
#[cfg(feature = "hex")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseHeaderError(ParsePrimitiveError<Header>);

#[cfg(feature = "hex")]
impl From<Infallible> for ParseHeaderError {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

#[cfg(feature = "hex")]
impl fmt::Display for ParseHeaderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_err!(f, "parse header error"; self.0)
    }
}

#[cfg(all(feature = "hex", feature = "std"))]
impl std::error::Error for ParseHeaderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

encoding::encoder_newtype_exact! {
    /// Encoder for a header without AuxPoW extension bytes.
    pub struct PureHeaderEncoder<'e>(
        encoding::Encoder6<
            VersionEncoder<'e>,
            BlockHashEncoder<'e>,
            crate::merkle_tree::TxMerkleNodeEncoder<'e>,
            crate::time::BlockTimeEncoder<'e>,
            crate::pow::CompactTargetEncoder<'e>,
            encoding::ArrayEncoder<4>,
        >
    );
}

#[cfg(feature = "alloc")]
type MerkleBranchEncoder<'e> = Encoder2<CompactSizeEncoder, SliceEncoder<'e, BlockHash>>;

#[cfg(feature = "alloc")]
type AuxPowEncoderInner<'e> = encoding::Encoder6<
    crate::transaction::TransactionEncoder<'e>,
    encoding::ArrayEncoder<32>,
    MerkleBranchEncoder<'e>,
    encoding::ArrayEncoder<4>,
    MerkleBranchEncoder<'e>,
    Encoder2<encoding::ArrayEncoder<4>, PureHeaderEncoder<'e>>,
>;

#[cfg(feature = "alloc")]
encoding::encoder_newtype_exact! {
    /// The structured encoder for the [`AuxPow`] wire layout.
    struct AuxPowLayoutEncoder<'e>(AuxPowEncoderInner<'e>);
}

#[cfg(feature = "alloc")]
fn auxpow_layout_encoder(auxpow: &AuxPow) -> AuxPowLayoutEncoder<'_> {
    let merkle_branch = Encoder2::new(
        CompactSizeEncoder::new(auxpow.merkle_branch.len()),
        SliceEncoder::without_length_prefix(&auxpow.merkle_branch),
    );
    let chain_merkle_branch = Encoder2::new(
        CompactSizeEncoder::new(auxpow.chain_merkle_branch.len()),
        SliceEncoder::without_length_prefix(&auxpow.chain_merkle_branch),
    );

    AuxPowLayoutEncoder::new(encoding::Encoder6::new(
        auxpow.coinbase_tx.encoder(),
        encoding::ArrayEncoder::without_length_prefix([0; 32]),
        merkle_branch,
        encoding::ArrayEncoder::without_length_prefix(0_i32.to_le_bytes()),
        chain_merkle_branch,
        Encoder2::new(
            encoding::ArrayEncoder::without_length_prefix(auxpow.chain_index.to_le_bytes()),
            auxpow.parent_block.pure_encoder(),
        ),
    ))
}

#[cfg(feature = "alloc")]
encoding::encoder_newtype_exact! {
    /// The encoder for the [`AuxPow`] type.
    pub struct AuxPowEncoder<'e>(AuxPowLayoutEncoder<'e>);
}

#[cfg(feature = "alloc")]
impl encoding::Encodable for AuxPow {
    type Encoder<'e>
        = AuxPowEncoder<'e>
    where
        Self: 'e;

    fn encoder(&self) -> Self::Encoder<'_> {
        AuxPowEncoder::new(auxpow_layout_encoder(self))
    }
}

#[cfg(feature = "alloc")]
/// The encoder for the [`Header`] type.
pub struct HeaderEncoder<'e> {
    pure: PureHeaderEncoder<'e>,
    auxpow: Option<AuxPowEncoder<'e>>,
    pure_done: bool,
}

#[cfg(not(feature = "alloc"))]
pub use PureHeaderEncoder as HeaderEncoder;

#[cfg(feature = "alloc")]
impl<'e> HeaderEncoder<'e> {
    fn new(header: &'e Header) -> Self {
        Self {
            pure: header.pure_encoder(),
            auxpow: header.auxpow.as_deref().map(encoding::Encodable::encoder),
            pure_done: false,
        }
    }
}

#[cfg(feature = "alloc")]
impl encoding::Encoder for HeaderEncoder<'_> {
    fn current_chunk(&self) -> &[u8] {
        if self.pure_done {
            self.auxpow.as_ref().map_or(&[], encoding::Encoder::current_chunk)
        } else {
            self.pure.current_chunk()
        }
    }

    fn advance(&mut self) -> bool {
        if !self.pure_done {
            if self.pure.advance() {
                return true;
            }
            self.pure_done = true;
            return self.auxpow.is_some();
        }

        if let Some(auxpow) = self.auxpow.as_mut() {
            if auxpow.advance() {
                return true;
            }
            self.auxpow = None;
        }

        false
    }
}

#[cfg(feature = "alloc")]
impl encoding::ExactSizeEncoder for HeaderEncoder<'_> {
    fn len(&self) -> usize {
        self.pure.len() + self.auxpow.as_ref().map_or(0, encoding::ExactSizeEncoder::len)
    }
}

#[cfg(feature = "alloc")]
impl encoding::Encodable for Header {
    type Encoder<'e> = HeaderEncoder<'e>;

    fn encoder(&self) -> Self::Encoder<'_> {
        HeaderEncoder::new(self)
    }
}

#[cfg(not(feature = "alloc"))]
impl encoding::Encodable for Header {
    type Encoder<'e> = HeaderEncoder<'e>;

    fn encoder(&self) -> Self::Encoder<'_> {
        self.pure_encoder()
    }
}

type HeaderInnerDecoder = Decoder6<
    VersionDecoder,
    BlockHashDecoder,
    TxMerkleNodeDecoder,
    BlockTimeDecoder,
    CompactTargetDecoder,
    encoding::ArrayDecoder<4>, // Nonce
>;

/// Decoder for a header without `AuxPoW` extension bytes.
pub struct PureHeaderDecoder(HeaderInnerDecoder);

impl PureHeaderDecoder {
    /// Constructs a decoder for a header without `AuxPoW` extension bytes.
    pub const fn new() -> Self {
        Self(Decoder6::new(
            VersionDecoder::new(),
            BlockHashDecoder::new(),
            TxMerkleNodeDecoder::new(),
            BlockTimeDecoder::new(),
            CompactTargetDecoder::new(),
            ArrayDecoder::new(),
        ))
    }

    fn from_inner(e: <HeaderInnerDecoder as encoding::Decoder>::Error) -> HeaderDecoderError {
        match e {
            encoding::Decoder6Error::First(e) => HeaderDecoderError::Version(e),
            encoding::Decoder6Error::Second(e) => HeaderDecoderError::PrevBlockhash(e),
            encoding::Decoder6Error::Third(e) => HeaderDecoderError::MerkleRoot(e),
            encoding::Decoder6Error::Fourth(e) => HeaderDecoderError::Time(e),
            encoding::Decoder6Error::Fifth(e) => HeaderDecoderError::Bits(e),
            encoding::Decoder6Error::Sixth(e) => HeaderDecoderError::Nonce(e),
        }
    }
}

impl Default for PureHeaderDecoder {
    fn default() -> Self {
        Self::new()
    }
}

impl encoding::Decoder for PureHeaderDecoder {
    type Output = Header;
    type Error = HeaderDecoderError;

    #[inline]
    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
        self.0.push_bytes(bytes).map_err(Self::from_inner)
    }

    #[inline]
    fn end(self) -> Result<Self::Output, Self::Error> {
        let (version, prev_blockhash, merkle_root, time, bits, nonce) =
            self.0.end().map_err(Self::from_inner)?;
        let nonce = u32::from_le_bytes(nonce);
        Ok(Header {
            version,
            prev_blockhash,
            merkle_root,
            time,
            bits,
            nonce,
            #[cfg(feature = "alloc")]
            auxpow: None,
        })
    }

    #[inline]
    fn read_limit(&self) -> usize {
        self.0.read_limit()
    }
}

#[cfg(not(feature = "alloc"))]
pub use PureHeaderDecoder as HeaderDecoder;

/// An error consensus decoding a `Header`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeaderDecoderError {
    /// Error while decoding the `version`.
    Version(VersionDecoderError),
    /// Error while decoding the `prev_blockhash`.
    PrevBlockhash(BlockHashDecoderError),
    /// Error while decoding the `merkle_root`.
    MerkleRoot(TxMerkleNodeDecoderError),
    /// Error while decoding the `time`.
    Time(BlockTimeDecoderError),
    /// Error while decoding the `bits`.
    Bits(CompactTargetDecoderError),
    /// Error while decoding the `nonce`.
    Nonce(encoding::UnexpectedEofError),
    /// Error while decoding the auxpow payload.
    #[cfg(feature = "alloc")]
    AuxPow(Box<AuxPowDecoderError>),
}

impl From<Infallible> for HeaderDecoderError {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

impl fmt::Display for HeaderDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Version(ref e) => write_err!(f, "header decoder error"; e),
            Self::PrevBlockhash(ref e) => write_err!(f, "header decoder error"; e),
            Self::MerkleRoot(ref e) => write_err!(f, "header decoder error"; e),
            Self::Time(ref e) => write_err!(f, "header decoder error"; e),
            Self::Bits(ref e) => write_err!(f, "header decoder error"; e),
            Self::Nonce(ref e) => write_err!(f, "header decoder error"; e),
            #[cfg(feature = "alloc")]
            Self::AuxPow(ref e) => write_err!(f, "header decoder error"; e),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for HeaderDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Self::Version(ref e) => Some(e),
            Self::PrevBlockhash(ref e) => Some(e),
            Self::MerkleRoot(ref e) => Some(e),
            Self::Time(ref e) => Some(e),
            Self::Bits(ref e) => Some(e),
            Self::Nonce(ref e) => Some(e),
            #[cfg(feature = "alloc")]
            Self::AuxPow(ref e) => Some(e),
        }
    }
}

#[cfg(feature = "alloc")]
enum AuxPowDecoderState {
    CoinbaseTx(crate::transaction::TransactionDecoder),
    HashBlock(encoding::ArrayDecoder<32>, Transaction),
    MerkleBranch(VecDecoder<BlockHash>, Transaction),
    CoinbaseIndex(encoding::ArrayDecoder<4>, Transaction, Vec<BlockHash>),
    ChainMerkleBranch(VecDecoder<BlockHash>, Transaction, Vec<BlockHash>),
    ChainIndex(encoding::ArrayDecoder<4>, Transaction, Vec<BlockHash>, Vec<BlockHash>),
    ParentBlock(PureHeaderDecoder, Transaction, Vec<BlockHash>, Vec<BlockHash>, i32),
    Done(AuxPow),
    Errored,
}

/// An error consensus decoding an auxpow payload.
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuxPowDecoderError {
    /// Error while decoding the parent coinbase transaction.
    CoinbaseTx(crate::transaction::TransactionDecoderError),
    /// Error while decoding the reserved `AuxPow` `hashBlock` field.
    HashBlock(encoding::UnexpectedEofError),
    /// Error while decoding the parent coinbase merkle branch.
    MerkleBranch(<VecDecoder<BlockHash> as encoding::Decoder>::Error),
    /// Error while decoding the reserved parent coinbase index field.
    CoinbaseIndex(encoding::UnexpectedEofError),
    /// Error while decoding the chain merkle branch.
    ChainMerkleBranch(<VecDecoder<BlockHash> as encoding::Decoder>::Error),
    /// Error while decoding the chain index.
    ChainIndex(encoding::UnexpectedEofError),
    /// Error while decoding the pure parent block header.
    ParentBlock(Box<HeaderDecoderError>),
    /// The reserved parent coinbase index field was non-zero.
    InvalidCoinbaseIndex(i32),
    /// The auxpow payload ended before all required fields were present.
    EarlyEnd(&'static str),
}

#[cfg(feature = "alloc")]
impl fmt::Display for AuxPowDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CoinbaseTx(e) => write_err!(f, "auxpow decoder error"; e),
            Self::HashBlock(e) => write_err!(f, "auxpow decoder error"; e),
            Self::MerkleBranch(e) => write_err!(f, "auxpow decoder error"; e),
            Self::CoinbaseIndex(e) => write_err!(f, "auxpow decoder error"; e),
            Self::ChainMerkleBranch(e) => write_err!(f, "auxpow decoder error"; e),
            Self::ChainIndex(e) => write_err!(f, "auxpow decoder error"; e),
            Self::ParentBlock(e) => write_err!(f, "auxpow decoder error"; e),
            Self::InvalidCoinbaseIndex(index) => {
                write!(f, "auxpow decoder error: coinbase index must be zero, got {}", index)
            }
            Self::EarlyEnd(field) => {
                write!(f, "auxpow decoder error: early end while decoding {}", field)
            }
        }
    }
}

#[cfg(all(feature = "alloc", feature = "std"))]
impl std::error::Error for AuxPowDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CoinbaseTx(e) => Some(e),
            Self::HashBlock(e) => Some(e),
            Self::MerkleBranch(e) => Some(e),
            Self::CoinbaseIndex(e) => Some(e),
            Self::ChainMerkleBranch(e) => Some(e),
            Self::ChainIndex(e) => Some(e),
            Self::ParentBlock(e) => Some(e),
            Self::InvalidCoinbaseIndex(_) | Self::EarlyEnd(_) => None,
        }
    }
}

#[cfg(feature = "alloc")]
struct AuxPowDecoder {
    state: AuxPowDecoderState,
}

#[cfg(feature = "alloc")]
impl AuxPowDecoder {
    pub const fn new() -> Self {
        Self {
            state: AuxPowDecoderState::CoinbaseTx(crate::transaction::TransactionDecoder::new()),
        }
    }
}

#[cfg(feature = "alloc")]
impl Default for AuxPowDecoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "alloc")]
impl encoding::Decoder for AuxPowDecoder {
    type Output = AuxPow;
    type Error = AuxPowDecoderError;

    #[allow(clippy::too_many_lines)]
    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
        use AuxPowDecoderError as E;
        use AuxPowDecoderState as S;

        loop {
            match &mut self.state {
                S::CoinbaseTx(decoder) => {
                    if decoder.push_bytes(bytes).map_err(E::CoinbaseTx)? {
                        return Ok(true);
                    }
                }
                S::HashBlock(decoder, _) => {
                    if decoder.push_bytes(bytes).map_err(E::HashBlock)? {
                        return Ok(true);
                    }
                }
                S::MerkleBranch(decoder, _) => {
                    if decoder.push_bytes(bytes).map_err(E::MerkleBranch)? {
                        return Ok(true);
                    }
                }
                S::CoinbaseIndex(decoder, ..) => {
                    if decoder.push_bytes(bytes).map_err(E::CoinbaseIndex)? {
                        return Ok(true);
                    }
                }
                S::ChainMerkleBranch(decoder, ..) => {
                    if decoder.push_bytes(bytes).map_err(E::ChainMerkleBranch)? {
                        return Ok(true);
                    }
                }
                S::ChainIndex(decoder, ..) => {
                    if decoder.push_bytes(bytes).map_err(E::ChainIndex)? {
                        return Ok(true);
                    }
                }
                S::ParentBlock(decoder, ..) => {
                    if decoder.push_bytes(bytes).map_err(|e| E::ParentBlock(Box::new(e)))? {
                        return Ok(true);
                    }
                }
                S::Done(..) => return Ok(false),
                S::Errored => panic!("call to push_bytes() after auxpow decoder errored"),
            }

            match mem::replace(&mut self.state, S::Errored) {
                S::CoinbaseTx(decoder) => {
                    let coinbase_tx = decoder.end().map_err(E::CoinbaseTx)?;
                    self.state = S::HashBlock(encoding::ArrayDecoder::new(), coinbase_tx);
                }
                S::HashBlock(decoder, coinbase_tx) => {
                    let _ = decoder.end().map_err(E::HashBlock)?;
                    self.state = S::MerkleBranch(VecDecoder::<BlockHash>::new(), coinbase_tx);
                }
                S::MerkleBranch(decoder, coinbase_tx) => {
                    let merkle_branch = decoder.end().map_err(E::MerkleBranch)?;
                    self.state =
                        S::CoinbaseIndex(encoding::ArrayDecoder::new(), coinbase_tx, merkle_branch);
                }
                S::CoinbaseIndex(decoder, coinbase_tx, merkle_branch) => {
                    let index = i32::from_le_bytes(decoder.end().map_err(E::CoinbaseIndex)?);
                    if index != 0 {
                        return Err(E::InvalidCoinbaseIndex(index));
                    }
                    self.state = S::ChainMerkleBranch(
                        VecDecoder::<BlockHash>::new(),
                        coinbase_tx,
                        merkle_branch,
                    );
                }
                S::ChainMerkleBranch(decoder, coinbase_tx, merkle_branch) => {
                    let chain_merkle_branch = decoder.end().map_err(E::ChainMerkleBranch)?;
                    self.state = S::ChainIndex(
                        encoding::ArrayDecoder::new(),
                        coinbase_tx,
                        merkle_branch,
                        chain_merkle_branch,
                    );
                }
                S::ChainIndex(decoder, coinbase_tx, merkle_branch, chain_merkle_branch) => {
                    let chain_index = i32::from_le_bytes(decoder.end().map_err(E::ChainIndex)?);
                    self.state = S::ParentBlock(
                        PureHeaderDecoder::new(),
                        coinbase_tx,
                        merkle_branch,
                        chain_merkle_branch,
                        chain_index,
                    );
                }
                S::ParentBlock(
                    decoder,
                    coinbase_tx,
                    merkle_branch,
                    chain_merkle_branch,
                    chain_index,
                ) => {
                    let parent_block = decoder.end().map_err(|e| E::ParentBlock(Box::new(e)))?;
                    self.state = S::Done(AuxPow {
                        coinbase_tx,
                        merkle_branch,
                        chain_merkle_branch,
                        chain_index,
                        parent_block,
                    });
                    return Ok(false);
                }
                S::Done(auxpow) => {
                    self.state = S::Done(auxpow);
                    return Ok(false);
                }
                S::Errored => unreachable!("checked above"),
            }
        }
    }

    fn end(self) -> Result<Self::Output, Self::Error> {
        use AuxPowDecoderError as E;
        use AuxPowDecoderState as S;

        match self.state {
            S::CoinbaseTx(_) => Err(E::EarlyEnd("coinbase transaction")),
            S::HashBlock(..) => Err(E::EarlyEnd("reserved auxpow hashBlock field")),
            S::MerkleBranch(..) => Err(E::EarlyEnd("coinbase merkle branch")),
            S::CoinbaseIndex(..) => Err(E::EarlyEnd("coinbase merkle index")),
            S::ChainMerkleBranch(..) => Err(E::EarlyEnd("chain merkle branch")),
            S::ChainIndex(..) => Err(E::EarlyEnd("chain index")),
            S::ParentBlock(
                header_decoder,
                coinbase_tx,
                merkle_branch,
                chain_merkle_branch,
                chain_index,
            ) => {
                let parent_block = header_decoder.end().map_err(|e| E::ParentBlock(Box::new(e)))?;
                Ok(AuxPow {
                    coinbase_tx,
                    merkle_branch,
                    chain_merkle_branch,
                    chain_index,
                    parent_block,
                })
            }
            S::Done(auxpow) => Ok(auxpow),
            S::Errored => panic!("call to end() after auxpow decoder errored"),
        }
    }

    fn read_limit(&self) -> usize {
        use AuxPowDecoderState as S;

        match &self.state {
            S::CoinbaseTx(decoder) => decoder.read_limit(),
            S::HashBlock(decoder, _) => decoder.read_limit(),
            S::MerkleBranch(decoder, _) => decoder.read_limit(),
            S::CoinbaseIndex(decoder, ..) => decoder.read_limit(),
            S::ChainMerkleBranch(decoder, ..) => decoder.read_limit(),
            S::ChainIndex(decoder, ..) => decoder.read_limit(),
            S::ParentBlock(decoder, ..) => decoder.read_limit(),
            S::Done(..) => 0,
            S::Errored => 0,
        }
    }
}

#[cfg(feature = "alloc")]
enum HeaderDecoderState {
    Pure(PureHeaderDecoder),
    AuxPow(Box<(Header, AuxPowDecoder)>),
    Done(Header),
    Errored,
}

/// The decoder for the [`Header`] type.
#[cfg(feature = "alloc")]
pub struct HeaderDecoder {
    state: HeaderDecoderState,
}

#[cfg(feature = "alloc")]
impl HeaderDecoder {
    /// Constructs a new [`Header`] decoder.
    pub const fn new() -> Self {
        Self { state: HeaderDecoderState::Pure(PureHeaderDecoder::new()) }
    }
}

#[cfg(feature = "alloc")]
impl Default for HeaderDecoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "alloc")]
impl encoding::Decoder for HeaderDecoder {
    type Output = Header;
    type Error = HeaderDecoderError;

    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
        use HeaderDecoderState as S;

        loop {
            match &mut self.state {
                S::Pure(decoder) => {
                    if decoder.push_bytes(bytes)? {
                        return Ok(true);
                    }
                }
                S::AuxPow(state) => {
                    if state
                        .1
                        .push_bytes(bytes)
                        .map_err(|e| HeaderDecoderError::AuxPow(Box::new(e)))?
                    {
                        return Ok(true);
                    }
                }
                S::Done(..) => return Ok(false),
                S::Errored => panic!("call to push_bytes() after header decoder errored"),
            }

            match mem::replace(&mut self.state, S::Errored) {
                S::Pure(decoder) => {
                    let header = decoder.end()?;
                    if header.version.is_auxpow() {
                        self.state = S::AuxPow(Box::new((header, AuxPowDecoder::new())));
                    } else {
                        self.state = S::Done(header);
                        return Ok(false);
                    }
                }
                S::AuxPow(state) => {
                    let (mut header, decoder) = *state;
                    header.auxpow = Some(Box::new(
                        decoder.end().map_err(|e| HeaderDecoderError::AuxPow(Box::new(e)))?,
                    ));
                    self.state = S::Done(header);
                    return Ok(false);
                }
                S::Done(header) => {
                    self.state = S::Done(header);
                    return Ok(false);
                }
                S::Errored => unreachable!("checked above"),
            }
        }
    }

    fn end(self) -> Result<Self::Output, Self::Error> {
        use HeaderDecoderState as S;

        match self.state {
            S::Pure(decoder) => decoder.end(),
            S::AuxPow(state) => {
                let (mut header, decoder) = *state;
                header.auxpow = Some(Box::new(
                    decoder.end().map_err(|e| HeaderDecoderError::AuxPow(Box::new(e)))?,
                ));
                Ok(header)
            }
            S::Done(header) => Ok(header),
            S::Errored => panic!("call to end() after header decoder errored"),
        }
    }

    fn read_limit(&self) -> usize {
        use HeaderDecoderState as S;

        match &self.state {
            S::Pure(decoder) => decoder.read_limit(),
            S::AuxPow(state) => state.1.read_limit(),
            S::Done(..) => 0,
            S::Errored => 0,
        }
    }
}

#[cfg(feature = "alloc")]
impl encoding::Decodable for Header {
    type Decoder = HeaderDecoder;

    fn decoder() -> Self::Decoder {
        HeaderDecoder::new()
    }
}

#[cfg(not(feature = "alloc"))]
impl encoding::Decodable for Header {
    type Decoder = HeaderDecoder;

    fn decoder() -> Self::Decoder {
        HeaderDecoder::new()
    }
}

impl From<Header> for BlockHash {
    #[inline]
    fn from(header: Header) -> Self {
        header.block_hash()
    }
}

impl From<&Header> for BlockHash {
    #[inline]
    fn from(header: &Header) -> Self {
        header.block_hash()
    }
}

/// Tidecoin block version number.
///
/// Originally used as a protocol version, but repurposed for soft-fork signaling.
///
/// The inner value is a signed integer for wire compatibility. If version bits are being used, the
/// top three bits must be 001, which gives a useful range of [0x20000000...0x3FFFFFFF].
///
/// > When a block nVersion does not have top bits 001, it is treated as if all bits are 0 for the purposes of deployments.
#[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Version(i32);

impl Version {
    /// Tidecoin block version 1.
    pub const ONE: Self = Self(1);

    /// Tidecoin block version 2 with coinbase height encoding.
    pub const TWO: Self = Self(2);

    /// Version-bits compatible version number that does not signal for any softforks.
    pub const NO_SOFT_FORK_SIGNALLING: Self = Self(Self::USE_VERSION_BITS as i32);

    /// Auxpow header flag.
    pub const VERSION_AUXPOW: i32 = 1 << 8;
    /// First bit used by the embedded auxpow chain id.
    pub const VERSION_START_BIT: u8 = 16;
    /// Starting value of the embedded chain id region.
    pub const VERSION_CHAIN_START: i32 = 1 << Self::VERSION_START_BIT;
    /// Mask for version-bits top bits that must be ignored for base-version extraction.
    pub const VERSION_AUXPOW_TOP_MASK: i32 = (1 << 28) | (1 << 29) | (1 << 30);
    /// Mask of the embedded auxpow chain id field already shifted into place.
    pub const MASK_AUXPOW_CHAINID_SHIFTED: i32 = 0x001f << Self::VERSION_START_BIT;

    /// Version-bits soft fork signal bits mask.
    const VERSION_BITS_MASK: u32 = 0x1FFF_FFFF;

    /// 32bit value starting with `001` to use version bits.
    ///
    /// The value has the top three bits `001` which enables the use of version bits to signal for soft forks.
    const USE_VERSION_BITS: u32 = 0x2000_0000;

    /// Constructs a new [`Version`] from a signed 32 bit integer value.
    #[inline]
    pub const fn from_consensus(v: i32) -> Self {
        Self(v)
    }

    /// Returns the inner `i32` value.
    #[inline]
    pub const fn to_consensus(self) -> i32 {
        self.0
    }

    /// Returns whether the auxpow flag is set.
    pub const fn is_auxpow(self) -> bool {
        (self.0 & Self::VERSION_AUXPOW) != 0
    }

    /// Returns this version with the auxpow flag enabled or disabled.
    #[must_use]
    pub const fn with_auxpow(self, enabled: bool) -> Self {
        if enabled {
            Self(self.0 | Self::VERSION_AUXPOW)
        } else {
            Self(self.0 & !Self::VERSION_AUXPOW)
        }
    }

    /// Returns the base version with auxpow and embedded chain-id bits stripped.
    pub const fn base_version(self) -> i32 {
        (self.0 & !Self::VERSION_AUXPOW) & !Self::MASK_AUXPOW_CHAINID_SHIFTED
    }

    /// Returns the auxpow chain id when auxpow is active, or zero otherwise.
    pub const fn chain_id(self) -> i32 {
        if self.is_auxpow() {
            (self.0 & Self::MASK_AUXPOW_CHAINID_SHIFTED) >> Self::VERSION_START_BIT
        } else {
            0
        }
    }

    /// Builds a version from a base version and chain id, leaving the auxpow flag unset.
    pub const fn with_base_version(base_version: i32, chain_id: i32) -> Self {
        Self(base_version | (chain_id << Self::VERSION_START_BIT))
    }

    /// Returns whether the provided base version is valid for embedding a chain id.
    pub const fn is_valid_base_version(base_version: i32) -> bool {
        (base_version & !Self::VERSION_AUXPOW_TOP_MASK) < Self::VERSION_CHAIN_START
    }

    /// Returns whether this is the legacy version-1 header.
    pub const fn is_legacy(self) -> bool {
        self.0 == 1
    }

    /// Checks whether the version number is signalling a soft fork at the given bit.
    ///
    /// A block signals for a version-bits soft fork if the first 3 bits are `001` and
    /// the version bit for the specific soft fork is toggled on.
    pub fn is_signalling_soft_fork(self, bit: u8) -> bool {
        // Only bits [0, 28] inclusive are used for signalling.
        if bit > 28 {
            return false;
        }

        // To signal using version bits, the first three bits must be `001`.
        if (self.0 as u32) & !Self::VERSION_BITS_MASK != Self::USE_VERSION_BITS {
            return false;
        }

        // The bit is set if signalling a soft fork.
        (self.0 as u32 & Self::VERSION_BITS_MASK) & (1 << bit) > 0
    }
}

impl fmt::Display for Version {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl fmt::LowerHex for Version {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::LowerHex::fmt(&self.0, f)
    }
}

impl fmt::UpperHex for Version {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::UpperHex::fmt(&self.0, f)
    }
}

impl fmt::Octal for Version {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Octal::fmt(&self.0, f)
    }
}

impl fmt::Binary for Version {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Binary::fmt(&self.0, f)
    }
}

impl Default for Version {
    #[inline]
    fn default() -> Self {
        Self::NO_SOFT_FORK_SIGNALLING
    }
}

encoding::encoder_newtype_exact! {
    /// The encoder for the [`Version`] type.
    pub struct VersionEncoder<'e>(encoding::ArrayEncoder<4>);
}

impl encoding::Encodable for Version {
    type Encoder<'e> = VersionEncoder<'e>;
    fn encoder(&self) -> Self::Encoder<'_> {
        VersionEncoder::new(encoding::ArrayEncoder::without_length_prefix(
            self.to_consensus().to_le_bytes(),
        ))
    }
}

/// The decoder for the [`Version`] type.
pub struct VersionDecoder(encoding::ArrayDecoder<4>);

impl VersionDecoder {
    /// Constructs a new [`Version`] decoder.
    pub const fn new() -> Self {
        Self(encoding::ArrayDecoder::new())
    }
}

impl Default for VersionDecoder {
    fn default() -> Self {
        Self::new()
    }
}

impl encoding::Decoder for VersionDecoder {
    type Output = Version;
    type Error = VersionDecoderError;

    #[inline]
    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
        self.0.push_bytes(bytes).map_err(VersionDecoderError)
    }

    #[inline]
    fn end(self) -> Result<Self::Output, Self::Error> {
        let n = i32::from_le_bytes(self.0.end().map_err(VersionDecoderError)?);
        Ok(Version::from_consensus(n))
    }

    #[inline]
    fn read_limit(&self) -> usize {
        self.0.read_limit()
    }
}

impl encoding::Decodable for Version {
    type Decoder = VersionDecoder;
    fn decoder() -> Self::Decoder {
        VersionDecoder(encoding::ArrayDecoder::<4>::new())
    }
}

/// An error consensus decoding an `Version`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionDecoderError(encoding::UnexpectedEofError);

impl From<Infallible> for VersionDecoderError {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

impl fmt::Display for VersionDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_err!(f, "version decoder error"; self.0)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for VersionDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

#[cfg(feature = "arbitrary")]
#[cfg(feature = "alloc")]
impl<'a> Arbitrary<'a> for Block {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let header = Header::arbitrary(u)?;
        let transactions = Vec::<Transaction>::arbitrary(u)?;
        Ok(Self::new_unchecked(header, transactions))
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Header {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self {
            version: Version::arbitrary(u)?,
            prev_blockhash: BlockHash::from_byte_array(u.arbitrary()?),
            merkle_root: TxMerkleNode::from_byte_array(u.arbitrary()?),
            time: u.arbitrary()?,
            bits: CompactTarget::from_consensus(u.arbitrary()?),
            nonce: u.arbitrary()?,
            #[cfg(feature = "alloc")]
            auxpow: None,
        })
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Version {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        // Equally weight known versions and arbitrary versions
        let choice = u.int_in_range(0..=3)?;
        match choice {
            0 => Ok(Self::ONE),
            1 => Ok(Self::TWO),
            2 => Ok(Self::NO_SOFT_FORK_SIGNALLING),
            _ => Ok(Self::from_consensus(u.arbitrary()?)),
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "alloc")]
    use alloc::string::ToString;
    #[cfg(feature = "alloc")]
    use alloc::{format, vec};
    #[cfg(all(feature = "alloc", feature = "hex"))]
    use core::str::FromStr as _;

    #[cfg(feature = "alloc")]
    use encoding::Decodable as _;
    use encoding::{Decoder as _, Encodable as _, Encoder as _};
    #[cfg(all(feature = "serde", feature = "hex", feature = "alloc"))]
    use serde::{Deserialize, Serialize};

    use super::*;

    fn dummy_header() -> Header {
        Header {
            version: Version::ONE,
            prev_blockhash: BlockHash::from_byte_array([0x99; 32]),
            merkle_root: TxMerkleNode::from_byte_array([0x77; 32]),
            time: BlockTime::from(2),
            bits: CompactTarget::from_consensus(3),
            nonce: 4,
            #[cfg(feature = "alloc")]
            auxpow: None,
        }
    }

    #[test]
    fn version_is_not_signalling_with_invalid_bit() {
        let arbitrary_version = Version::from_consensus(1_234_567_890);
        // The max bit number to signal is 28.
        assert!(!Version::is_signalling_soft_fork(arbitrary_version, 29));
    }

    #[test]
    fn version_is_not_signalling_when_use_version_bit_not_set() {
        let version = Version::from_consensus(0b0100_0000_0000_0000_0000_0000_0000_0000);
        // Top three bits must be 001 to signal.
        assert!(!Version::is_signalling_soft_fork(version, 1));
    }

    #[test]
    fn version_is_signalling() {
        let version = Version::from_consensus(0b0010_0000_0000_0000_0000_0000_0000_0010);
        assert!(Version::is_signalling_soft_fork(version, 1));
        let version = Version::from_consensus(0b0011_0000_0000_0000_0000_0000_0000_0000);
        assert!(Version::is_signalling_soft_fork(version, 28));
    }

    #[test]
    fn version_is_not_signalling() {
        let version = Version::from_consensus(0b0010_0000_0000_0000_0000_0000_0000_0010);
        assert!(!Version::is_signalling_soft_fork(version, 0));
    }

    #[test]
    fn version_to_consensus() {
        let version = Version::from_consensus(1_234_567_890);
        assert_eq!(version.to_consensus(), 1_234_567_890);
    }

    #[test]
    fn version_default() {
        let version = Version::default();
        assert_eq!(version.to_consensus(), Version::NO_SOFT_FORK_SIGNALLING.to_consensus());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn version_display() {
        let version = Version(75);
        assert_eq!(format!("{}", version), "75");
        assert_eq!(format!("{:x}", version), "4b");
        assert_eq!(format!("{:#x}", version), "0x4b");
        assert_eq!(format!("{:X}", version), "4B");
        assert_eq!(format!("{:#X}", version), "0x4B");
        assert_eq!(format!("{:o}", version), "113");
        assert_eq!(format!("{:#o}", version), "0o113");
        assert_eq!(format!("{:b}", version), "1001011");
        assert_eq!(format!("{:#b}", version), "0b1001011");
    }

    // Check that the size of the header consensus serialization matches the const SIZE value
    #[test]
    fn header_size() {
        let header = dummy_header();

        // Calculate the size of the block header in bytes from the sum of the serialized lengths
        // its fields: version, prev_blockhash, merkle_root, time, bits, nonce.
        let header_size = header.version.to_consensus().to_le_bytes().len()
            + header.prev_blockhash.as_byte_array().len()
            + header.merkle_root.as_byte_array().len()
            + header.time.to_u32().to_le_bytes().len()
            + header.bits.to_consensus().to_le_bytes().len()
            + header.nonce.to_le_bytes().len();

        assert_eq!(header_size, Header::SIZE);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_new_unchecked() {
        let header = dummy_header();
        let transactions = vec![];
        let block = Block::new_unchecked(header.clone(), transactions.clone());
        assert_eq!(block.header, header);
        assert_eq!(block.transactions, transactions);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_assume_checked() {
        let header = dummy_header();
        let transactions = vec![];
        let block = Block::new_unchecked(header.clone(), transactions.clone());
        let witness_root = Some(WitnessMerkleNode::from_byte_array([0x88; 32]));
        let checked_block = block.assume_checked(witness_root);
        assert_eq!(checked_block.header(), &header);
        assert_eq!(checked_block.transactions(), &transactions);
        assert_eq!(checked_block.cached_witness_root(), witness_root);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_into_parts() {
        let header = dummy_header();
        let transactions = vec![];
        let block = Block::new_unchecked(header.clone(), transactions.clone());
        let (block_header, block_transactions) = block.into_parts();
        assert_eq!(block_header, header);
        assert_eq!(block_transactions, transactions);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_cached_witness_root() {
        let header = dummy_header();
        let transactions = vec![];
        let block = Block::new_unchecked(header, transactions);
        let witness_root = Some(WitnessMerkleNode::from_byte_array([0x88; 32]));
        let checked_block = block.assume_checked(witness_root);
        assert_eq!(checked_block.cached_witness_root(), witness_root);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_validation_no_transactions() {
        let header = dummy_header();
        let transactions = Vec::new(); // Empty transactions

        let block = Block::new_unchecked(header, transactions);
        matches!(block.validate(), Err(InvalidBlockError::NoTransactions));
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_validation_invalid_coinbase() {
        let header = dummy_header();

        // Create a non-coinbase transaction (has a real previous output, not all zeros)
        let non_coinbase_tx = Transaction {
            version: crate::transaction::Version::TWO,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![crate::TxIn {
                previous_output: crate::OutPoint {
                    txid: crate::Txid::from_byte_array([1; 32]), // Not all zeros
                    vout: 0,
                },
                script_sig: crate::ScriptSigBuf::new(),
                sequence: units::Sequence::ENABLE_LOCKTIME_AND_RBF,
                witness: crate::Witness::new(),
            }],
            outputs: vec![crate::TxOut {
                amount: units::Amount::ONE_TDC,
                script_pubkey: crate::ScriptPubKeyBuf::new(),
            }],
        };

        let transactions = vec![non_coinbase_tx];
        let block = Block::new_unchecked(header, transactions);

        matches!(block.validate(), Err(InvalidBlockError::InvalidCoinbase));
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_decoder_read_limit() {
        let mut coinbase_in = crate::TxIn::EMPTY_COINBASE;
        coinbase_in.script_sig = crate::ScriptSigBuf::from_bytes(vec![0u8; 2]);

        let block = Block::new_unchecked(
            dummy_header(),
            vec![Transaction {
                version: crate::transaction::Version::ONE,
                lock_time: crate::absolute::LockTime::ZERO,
                inputs: vec![coinbase_in],
                outputs: vec![crate::TxOut {
                    amount: units::Amount::MIN,
                    script_pubkey: crate::ScriptPubKeyBuf::new(),
                }],
            }],
        );

        let bytes = encoding::encode_to_vec(&block);
        let mut view = bytes.as_slice();

        let mut decoder = Block::decoder();
        assert!(decoder.read_limit() > 0);
        let needs_more = decoder.push_bytes(&mut view).unwrap();
        assert!(!needs_more);
        assert_eq!(decoder.read_limit(), 0);
        assert_eq!(decoder.end().unwrap(), block);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn header_decoder_read_limit() {
        let header = dummy_header();
        let bytes = encoding::encode_to_vec(&header);
        let mut view = bytes.as_slice();

        let mut decoder = Header::decoder();
        assert!(decoder.read_limit() > 0);
        let needs_more = decoder.push_bytes(&mut view).unwrap();
        assert!(!needs_more);
        assert_eq!(decoder.read_limit(), 0);
        assert_eq!(decoder.end().unwrap(), header);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_check_witness_commitment_optional() {
        // Valid block with optional witness commitment
        let mut header = dummy_header();
        header.merkle_root = TxMerkleNode::from_byte_array([0u8; 32]);
        let coinbase = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![crate::TxIn::EMPTY_COINBASE],
            outputs: vec![],
        };

        let transactions = vec![coinbase];
        let block = Block::new_unchecked(header, transactions);

        let result = block.check_witness_commitment();
        assert_eq!(result, (true, None));
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_block_hash() {
        let header = dummy_header();
        let transactions = vec![];
        let block = Block::new_unchecked(header.clone(), transactions);
        assert_eq!(block.block_hash(), header.block_hash());
    }

    #[test]
    fn block_hash_from_header() {
        let header = dummy_header();
        let block_hash = header.block_hash();
        assert_eq!(block_hash, BlockHash::from(header));
    }

    #[test]
    fn block_hash_from_header_ref() {
        let header = dummy_header();
        let block_hash: BlockHash = BlockHash::from(&header);
        assert_eq!(block_hash, header.block_hash());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_hash_from_block() {
        let header = dummy_header();
        let transactions = vec![];
        let block = Block::new_unchecked(header.clone(), transactions);
        let block_hash: BlockHash = BlockHash::from(block);
        assert_eq!(block_hash, header.block_hash());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_hash_from_block_ref() {
        let header = dummy_header();
        let transactions = vec![];
        let block = Block::new_unchecked(header.clone(), transactions);
        let block_hash: BlockHash = BlockHash::from(&block);
        assert_eq!(block_hash, header.block_hash());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn header_debug() {
        let header = dummy_header();
        let expected = format!(
            "Header {{ block_hash: {:?}, version: {:?}, prev_blockhash: {:?}, merkle_root: {:?}, time: {:?}, bits: {:?}, nonce: {:?}, auxpow: None }}",
            header.block_hash(),
            header.version,
            header.prev_blockhash,
            header.merkle_root,
            header.time,
            header.bits,
            header.nonce
        );
        assert_eq!(format!("{:?}", header), expected);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn version_auxpow_helpers_roundtrip() {
        let version = Version::with_base_version(1, 8).with_auxpow(true);
        assert!(version.is_auxpow());
        assert_eq!(version.base_version(), 1);
        assert_eq!(version.chain_id(), 8);
        assert!(!version.is_legacy());
        assert!(Version::from_consensus(version.base_version()).is_legacy());
        assert!(Version::is_valid_base_version(1));
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn auxpow_payload_does_not_change_header_hash() {
        let mut header = dummy_header();
        header.version = Version::with_base_version(1, 8).with_auxpow(true);

        let expected = header.block_hash();
        header.auxpow = Some(Box::new(AuxPow::minimal_for_header(&header)));

        assert_eq!(header.block_hash(), expected);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn pure_header_bytes_exclude_auxpow_payload() {
        let mut header = dummy_header();
        header.version = Version::with_base_version(1, 8).with_auxpow(true);

        let expected = header.pure_header_bytes();
        header.auxpow = Some(Box::new(AuxPow::minimal_for_header(&header)));

        assert_eq!(header.pure_header_bytes(), expected);
        assert_eq!(header.pure_header_bytes().len(), Header::SIZE);
    }

    #[test]
    #[cfg(feature = "hex")]
    #[cfg(feature = "alloc")]
    fn header_display() {
        let seconds: u32 = 1_653_195_600; // Arbitrary timestamp: May 22nd, 5am UTC.

        let header = Header {
            version: Version::TWO,
            prev_blockhash: BlockHash::from_byte_array([0xab; 32]),
            merkle_root: TxMerkleNode::from_byte_array([0xcd; 32]),
            time: BlockTime::from(seconds),
            bits: CompactTarget::from_consensus(0xbeef),
            nonce: 0xcafe,
            auxpow: None,
        };

        let want = concat!(
            "02000000",                                                         // version
            "abababababababababababababababababababababababababababababababab", // prev_blockhash
            "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", // merkle_root
            "50c38962",                                                         // time
            "efbe0000",                                                         // bits
            "feca0000",                                                         // nonce
        );
        assert_eq!(want.len(), 160);
        assert_eq!(format!("{}", header), want);

        // Check how formatting options are handled.
        let want = format!("{:.20}", want);
        let got = format!("{:.20}", header);
        assert_eq!(got, want);

        let want = format!("{:.0}", want);
        let got = format!("{:.0}", header);
        assert_eq!(got, want);
    }

    #[test]
    #[cfg(feature = "hex")]
    #[cfg(feature = "alloc")]
    fn header_hex() {
        let header = dummy_header();

        let lower_hex = concat!(
            "01000000",                                                         // version
            "9999999999999999999999999999999999999999999999999999999999999999", // prev_blockhash
            "7777777777777777777777777777777777777777777777777777777777777777", // merkle_root
            "02000000",                                                         // time
            "03000000",                                                         // bits
            "04000000",                                                         // nonce
        );

        // All of these should yield a lowercase hex
        assert_eq!(lower_hex, format!("{:x}", header));
        assert_eq!(lower_hex, format!("{}", header));

        // And these should yield uppercase hex
        let upper_hex = lower_hex.to_ascii_uppercase();
        assert_eq!(upper_hex, format!("{:X}", header));

        // Check padding (right, left, center, custom char)
        assert_eq!(format!("{:>164}", lower_hex), format!("{:>164x}", header));
        assert_eq!(format!("{:<164}", lower_hex), format!("{:<164x}", header));
        assert_eq!(format!("{:^164}", lower_hex), format!("{:^164x}", header));
        assert_eq!(format!("{:_>164}", lower_hex), format!("{:_>164x}", header));

        // Alt forms
        let lower_hex_alt = format!("0x{}", lower_hex);
        assert_eq!(lower_hex_alt, format!("{:#x}", header));
        assert_eq!(format!("0X{}", upper_hex), format!("{:#X}", header));

        // Alternate + padding
        assert_eq!(format!("{:>166}", lower_hex_alt), format!("{:>#166x}", header));
        assert_eq!(format!("{:<166}", lower_hex_alt), format!("{:<#166x}", header));
        assert_eq!(format!("{:^166}", lower_hex_alt), format!("{:^#166x}", header));

        // Alt + truncate
        assert_eq!(format!("{:>.20}", lower_hex_alt), format!("{:>#.20x}", header));
        assert_eq!(format!("{:<.20}", lower_hex_alt), format!("{:<#.20x}", header));
        assert_eq!(format!("{:^.20}", lower_hex_alt), format!("{:^#.20x}", header));
    }

    #[test]
    #[cfg(feature = "hex")]
    #[cfg(feature = "alloc")]
    fn header_from_hex_str_round_trip() {
        // Create a header and convert it to a hex string
        let header = dummy_header();

        let lower_hex_header = format!("{:x}", header);
        let upper_hex_header = format!("{:X}", header);

        // Parse the hex strings back into headers
        let parsed_lower = Header::from_str(&lower_hex_header).unwrap();
        let parsed_upper = Header::from_str(&upper_hex_header).unwrap();

        // The parsed header should match the originals
        assert_eq!(header, parsed_lower);
        assert_eq!(header, parsed_upper);
    }

    #[cfg(feature = "alloc")]
    fn dummy_block() -> Block {
        let header = Header {
            version: Version::ONE,
            #[rustfmt::skip]
            prev_blockhash: BlockHash::from_byte_array([
                0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA,
                0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA,
                0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA,
                0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA,
            ]),
            #[rustfmt::skip]
            merkle_root: TxMerkleNode::from_byte_array([
                0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD,
                0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD,
                0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD,
                0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD,
            ]),
            time: BlockTime::from(1_742_979_600), // 26 Mar 2025 9:00 UTC
            bits: CompactTarget::from_consensus(12_345_678),
            nonce: 1024,
            auxpow: None,
        };

        let block: u32 = 741_521;
        let transactions = vec![Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: units::absolute::LockTime::from_height(block).unwrap(),
            inputs: vec![crate::transaction::TxIn {
                previous_output: crate::transaction::OutPoint::COINBASE_PREVOUT,
                // Coinbase scriptSig must be 2-100 bytes
                script_sig: crate::script::ScriptSigBuf::from_bytes(vec![0x51, 0x51]),
                sequence: crate::sequence::Sequence::MAX,
                witness: crate::witness::Witness::new(),
            }],
            outputs: vec![crate::transaction::TxOut {
                amount: units::Amount::ONE_SAT,
                script_pubkey: crate::script::ScriptPubKeyBuf::new(),
            }],
        }];
        Block::new_unchecked(header, transactions)
    }

    #[test]
    #[cfg(feature = "hex")]
    #[cfg(feature = "alloc")]
    fn block_hex() {
        let header = dummy_header();
        let transactions = vec![Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::locktime::absolute::LockTime::ZERO,
            inputs: vec![],
            outputs: vec![],
        }];
        let block = Block::new_unchecked(header, transactions);

        // Transaction with no inputs uses segwit serialization:
        // version (4) + marker (1) + flag (1) + input_count (1) + output_count (1) + lock_time (4)
        let want = "010000009999999999999999999999999999999999999999999999999999999999999999777777777777777777777777777777777777777777777777777777777777777702000000030000000400000001010000000001000000000000";

        assert_eq!(format!("{}", block), want);
        assert_eq!(format!("{:x}", block), want);

        // Note this is pointless because the hex does not have letters in it, only numbers.
        let want =
            want.chars().map(|chr| chr.to_ascii_uppercase()).collect::<alloc::string::String>();
        assert_eq!(want, format!("{:X}", block));
    }

    #[test]
    #[cfg(feature = "hex")]
    #[cfg(feature = "alloc")]
    fn block_from_hex_str_round_trip() {
        let block = dummy_block();

        let lower_hex_block = format!("{:x}", block);
        let upper_hex_block = format!("{:X}", block);

        let parsed_lower = Block::from_str(&lower_hex_block).unwrap();
        let parsed_upper = Block::from_str(&upper_hex_block).unwrap();

        assert_eq!(parsed_lower, block);
        assert_eq!(parsed_upper, block);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_decode() {
        let original = dummy_block();

        let encoded = encoding::encode_to_vec(&original);
        let decoded: Block = encoding::decode_from_slice(encoded.as_slice()).unwrap();

        assert_eq!(decoded, original);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn merkle_tree_hash_collision() {
        fn coinbase_tx() -> Transaction {
            let mut coinbase_in = crate::TxIn::EMPTY_COINBASE;
            coinbase_in.script_sig = crate::ScriptSigBuf::from_bytes(vec![0x51, 0x51]);
            Transaction {
                version: crate::transaction::Version::ONE,
                lock_time: crate::absolute::LockTime::ZERO,
                inputs: vec![coinbase_in],
                outputs: vec![crate::TxOut {
                    amount: units::Amount::ONE_SAT,
                    script_pubkey: crate::ScriptPubKeyBuf::from_bytes(vec![0x51]),
                }],
            }
        }

        fn spend_tx(tag: u8) -> Transaction {
            Transaction {
                version: crate::transaction::Version::TWO,
                lock_time: crate::absolute::LockTime::ZERO,
                inputs: vec![crate::TxIn {
                    previous_output: crate::OutPoint {
                        txid: crate::Txid::from_byte_array([tag; 32]),
                        vout: tag.into(),
                    },
                    script_sig: crate::ScriptSigBuf::from_bytes(vec![tag]),
                    sequence: crate::sequence::Sequence::MAX,
                    witness: crate::Witness::new(),
                }],
                outputs: vec![crate::TxOut {
                    amount: units::Amount::ONE_SAT,
                    script_pubkey: crate::ScriptPubKeyBuf::from_bytes(vec![tag.wrapping_add(1)]),
                }],
            }
        }

        let transactions = vec![coinbase_tx(), spend_tx(0x11), spend_tx(0x12)];
        let mut header = dummy_header();
        header.merkle_root = compute_merkle_root(&transactions).unwrap();
        let valid_block = Block::new_unchecked(header.clone(), transactions.clone());

        let mut forged_transactions = transactions;
        forged_transactions.push(forged_transactions[2].clone());
        let forged_block = Block::new_unchecked(header, forged_transactions);

        assert!(valid_block.validate().is_ok());
        assert!(forged_block.validate().is_err());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn witness_commitment_from_coinbase_simple() {
        // Add witness commitment to the coinbase
        let magic = [0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed];
        let mut pubkey_bytes = [0; 38];
        pubkey_bytes[0..6].copy_from_slice(&magic);
        let witness_commitment =
            WitnessCommitment::from_byte_array(pubkey_bytes[6..38].try_into().unwrap());
        let commitment_script = crate::script::ScriptBuf::from_bytes(pubkey_bytes.to_vec());

        // Create a coinbase transaction with witness commitment
        let tx = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![crate::TxIn::EMPTY_COINBASE],
            outputs: vec![crate::TxOut {
                amount: units::Amount::MIN,
                script_pubkey: commitment_script,
            }],
        };

        // Test if the witness commitment is extracted properly
        let extracted = witness_commitment_from_coinbase(&tx);
        assert_eq!(extracted, Some(witness_commitment));
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn witness_commitment_from_non_coinbase_returns_none() {
        let tx = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![crate::TxIn {
                previous_output: crate::OutPoint {
                    txid: crate::Txid::from_byte_array([1; 32]),
                    vout: 0,
                },
                script_sig: crate::ScriptSigBuf::new(),
                sequence: units::Sequence::ENABLE_LOCKTIME_AND_RBF,
                witness: crate::Witness::new(),
            }],
            outputs: vec![crate::TxOut {
                amount: units::Amount::MIN,
                script_pubkey: crate::ScriptPubKeyBuf::new(),
            }],
        };

        assert!(witness_commitment_from_coinbase(&tx).is_none());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_check_witness_commitment_empty_script_pubkey() {
        let mut txin = crate::TxIn::EMPTY_COINBASE;
        let push = [11_u8];
        txin.witness.push(push);

        let tx = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![txin],
            outputs: vec![crate::TxOut {
                amount: units::Amount::MIN,
                // Empty scriptbuf means there is no witness commitment due to no magic bytes.
                script_pubkey: crate::script::ScriptBuf::new(),
            }],
        };

        let block = Block::new_unchecked(dummy_header(), vec![tx]);
        let result = block.check_witness_commitment();
        assert_eq!(result, (false, None)); // (false, None) since there's no valid witness commitment
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_check_witness_commitment_no_transactions() {
        // Test case of block with no transactions
        let empty_block = Block::new_unchecked(dummy_header(), vec![]);
        let result = empty_block.check_witness_commitment();
        assert_eq!(result, (false, None));
    }

    #[test]
    #[cfg(all(feature = "alloc", feature = "hex"))]
    fn block_check_witness_commitment_with_witness() {
        let mut txin = crate::TxIn::EMPTY_COINBASE;
        // Single witness item of 32 bytes.
        let witness_bytes: [u8; 32] = [11u8; 32];
        txin.witness.push(witness_bytes);

        // pubkey bytes must match the magic bytes followed by the hash of the witness bytes.
        let script_pubkey_bytes = hex::decode_to_array::<38>(
            "6a24aa21a9ed3cde9e0b9f4ad8f9d0fd66d6b9326cd68597c04fa22ab64b8e455f08d2e31ceb",
        )
        .unwrap();
        let tx1 = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![txin],
            outputs: vec![crate::TxOut {
                amount: units::Amount::MIN,
                script_pubkey: crate::script::ScriptBuf::from_bytes(script_pubkey_bytes.to_vec()),
            }],
        };

        let tx2 = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![crate::TxIn::EMPTY_COINBASE],
            outputs: vec![crate::TxOut {
                amount: units::Amount::MIN,
                script_pubkey: crate::script::ScriptBuf::new(),
            }],
        };

        let block = Block::new_unchecked(dummy_header(), vec![tx1, tx2]);
        let result = block.check_witness_commitment();

        let exp_bytes = hex::decode_to_array::<32>(
            "fb848679079938b249a12f14b72d56aeb116df79254e17cdf72b46523bcb49db",
        )
        .unwrap();
        let expected = WitnessMerkleNode::from_byte_array(exp_bytes);
        assert_eq!(result, (true, Some(expected)));
    }

    #[test]
    #[cfg(all(feature = "alloc", feature = "hex"))]
    fn block_check_witness_commitment_invalid_witness() {
        let mut txin = crate::TxIn::EMPTY_COINBASE;
        txin.script_sig = crate::ScriptSigBuf::from_bytes(vec![0u8; 2]);
        let witness_bytes: [u8; 32] = [11u8; 32];
        // First witness item is 32 bytes, but there are two witness elements.
        txin.witness.push(witness_bytes);
        txin.witness.push([12u8]);

        let script_pubkey_bytes = hex::decode_to_array::<38>(
            "6a24aa21a9ed3cde9e0b9f4ad8f9d0fd66d6b9326cd68597c04fa22ab64b8e455f08d2e31ceb",
        )
        .unwrap();
        let tx1 = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![txin],
            outputs: vec![crate::TxOut {
                amount: units::Amount::MIN,
                script_pubkey: crate::script::ScriptBuf::from_bytes(script_pubkey_bytes.to_vec()),
            }],
        };

        let tx2 = Transaction {
            version: crate::transaction::Version::ONE,
            lock_time: crate::absolute::LockTime::ZERO,
            inputs: vec![crate::TxIn {
                previous_output: crate::OutPoint {
                    txid: crate::Txid::from_byte_array([1; 32]),
                    vout: 0,
                },
                script_sig: crate::ScriptSigBuf::new(),
                sequence: crate::Sequence::MAX,
                witness: crate::Witness::default(),
            }],
            outputs: vec![crate::TxOut {
                amount: units::Amount::MIN,
                script_pubkey: crate::script::ScriptBuf::new(),
            }],
        };

        let mut header = dummy_header();
        let transactions = vec![tx1, tx2];
        header.merkle_root = compute_merkle_root(&transactions).unwrap();

        let block = Block::new_unchecked(header, transactions);
        assert_eq!(block.check_witness_commitment(), (false, None));
        assert!(matches!(block.validate(), Err(InvalidBlockError::InvalidWitnessCommitment)));
    }

    #[test]
    fn version_encoder_emits_consensus_bytes() {
        let version = Version::from_consensus(123_456_789);
        let mut encoder = version.encoder();

        assert_eq!(encoder.current_chunk(), &version.to_consensus().to_le_bytes());
        assert!(!encoder.advance());
    }

    #[test]
    fn version_decoder_end_and_read_limit() {
        let mut decoder = VersionDecoder::new();
        let bytes_arr = Version::TWO.to_consensus().to_le_bytes();
        let mut bytes = bytes_arr.as_slice();

        assert!(decoder.read_limit() > 0);

        let needs_more = decoder.push_bytes(&mut bytes).unwrap();
        assert!(!needs_more);
        assert!(bytes.is_empty());

        assert_eq!(decoder.read_limit(), 0);
        let decoded = decoder.end().unwrap();
        assert_eq!(decoded, Version::TWO);
    }

    #[test]
    fn version_decoder_default_roundtrip() {
        let version = Version::from_consensus(123_456_789);
        let mut decoder = VersionDecoder::default();
        let consensus = version.to_consensus().to_le_bytes();
        let mut bytes = consensus.as_slice();
        decoder.push_bytes(&mut bytes).unwrap();

        assert_eq!(decoder.end().unwrap(), version);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn block_decoder_error() {
        let err_first = Block::decoder().end().unwrap_err();
        assert!(matches!(err_first.0, encoding::Decoder2Error::First(_)));
        assert!(!err_first.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(std::error::Error::source(&err_first).is_some());

        // Provide a complete header and a vec length prefix (1 tx) but omit any tx bytes.
        // This forces the inner VecDecoder to error when finalizing.
        let mut bytes = encoding::encode_to_vec(&dummy_header());
        bytes.push(1u8);
        let mut view = bytes.as_slice();

        let mut decoder = Block::decoder();
        assert!(decoder.push_bytes(&mut view).unwrap());
        assert!(view.is_empty());

        let err_second = decoder.end().unwrap_err();
        assert!(matches!(err_second.0, encoding::Decoder2Error::Second(_)));
        assert!(!err_second.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(std::error::Error::source(&err_second).is_some());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn header_decoder_error() {
        let header_bytes = encoding::encode_to_vec(&dummy_header());
        // Number of bytes in the encoding up to the start of each field.
        let lengths = [0usize, 4, 36, 68, 72, 76];

        for &len in &lengths {
            let mut decoder = Header::decoder();
            let mut slice = header_bytes[..len].as_ref();
            decoder.push_bytes(&mut slice).unwrap();
            let err = decoder.end().unwrap_err();
            match len {
                0 => assert!(matches!(err, HeaderDecoderError::Version(_))),
                4 => assert!(matches!(err, HeaderDecoderError::PrevBlockhash(_))),
                36 => assert!(matches!(err, HeaderDecoderError::MerkleRoot(_))),
                68 => assert!(matches!(err, HeaderDecoderError::Time(_))),
                72 => assert!(matches!(err, HeaderDecoderError::Bits(_))),
                76 => assert!(matches!(err, HeaderDecoderError::Nonce(_))),
                _ => unreachable!(),
            }
            assert!(!err.to_string().is_empty());
            #[cfg(feature = "std")]
            assert!(std::error::Error::source(&err).is_some());
        }
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn invalid_block_error() {
        #[cfg(feature = "std")]
        use std::error::Error as _;

        let variants = [
            InvalidBlockError::InvalidMerkleRoot,
            InvalidBlockError::InvalidWitnessCommitment,
            InvalidBlockError::NoTransactions,
            InvalidBlockError::InvalidCoinbase,
        ];

        for variant in variants {
            assert!(!variant.to_string().is_empty());
            #[cfg(feature = "std")]
            assert!(variant.source().is_none());
        }
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn version_decoder_error() {
        let err = encoding::decode_from_slice::<Version>(&[0x01]).unwrap_err();
        assert!(!err.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(std::error::Error::source(&err).is_some());
    }

    /// A type that has a `Block` field and a `Header` field.
    #[cfg(all(feature = "serde", feature = "hex", feature = "alloc"))]
    #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
    struct Adt {
        #[serde(with = "crate::serde_as_consensus")]
        header: Header,
        #[serde(with = "crate::serde_as_consensus")]
        block: Block,
    }

    #[test]
    #[cfg(all(feature = "serde", feature = "hex", feature = "alloc"))]
    fn can_serde_as_consensus_json() {
        let orig = Adt { header: dummy_header(), block: dummy_block() };

        let json = serde_json::to_string(&orig).expect("failed to serialize");

        let want = "{\"header\":\"0100000099999999999999999999999999999999999999999999999999999999999999997777777777777777777777777777777777777777777777777777777777777777020000000300000004000000\",\"block\":\"01000000dcbadcbadcbadcbadcbadcbadcbadcbadcbadcbadcbadcbadcbadcbadcbadcbaabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd10c2e3674e61bc00000400000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025151ffffffff0101000000000000000091500b00\"}";
        assert_eq!(json, want);

        let roundtrip: Adt = serde_json::from_str(&json).expect("failed to deserialize");
        assert_eq!(roundtrip, orig);
    }

    #[test]
    #[cfg(all(feature = "serde", feature = "hex", feature = "alloc"))]
    fn can_serde_as_consensus_bincode() {
        let orig = Adt { header: dummy_header(), block: dummy_block() };

        // Bincode is non-human-readable, so it should use bytes
        let bytes = bincode::serialize(&orig).expect("failed to serialize");

        let roundtrip: Adt = bincode::deserialize(&bytes).expect("failed to deserialize");
        assert_eq!(roundtrip, orig);
    }
}