filecoin-proofs 19.1.0

The Filecoin specific aspects of storage-proofs, including a C based FFI, to generate and verify proofs.
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
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
use std::collections::BTreeMap;
use std::fs::{metadata, read_dir, remove_file, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use anyhow::{ensure, Context, Error, Result};
use bellperson::groth16;
use bincode::serialize;
use blstrs::{Bls12, Scalar as Fr};
use ff::Field;
use filecoin_hashers::Hasher;
use filecoin_proofs::{
    add_piece, aggregate_empty_sector_update_proofs, aggregate_seal_commit_proofs, clear_cache,
    clear_synthetic_proofs, compute_comm_d, decode_from, decode_from_range, encode_into,
    fauxrep_aux, generate_empty_sector_update_proof,
    generate_empty_sector_update_proof_with_vanilla, generate_fallback_sector_challenges,
    generate_partition_proofs, generate_piece_commitment, generate_single_partition_proof,
    generate_single_vanilla_proof, generate_single_window_post_with_vanilla, generate_synth_proofs,
    generate_tree_c, generate_tree_r_last, generate_window_post, generate_window_post_with_vanilla,
    generate_winning_post, generate_winning_post_sector_challenge,
    generate_winning_post_with_vanilla, get_num_partition_for_fallback_post, get_seal_inputs,
    get_sector_update_h_select_from_porep_config, get_sector_update_inputs,
    merge_window_post_partition_proofs, remove_encoded_data, seal_commit_phase1,
    seal_commit_phase2, seal_commit_phase2_circuit_proofs, seal_pre_commit_phase1,
    seal_pre_commit_phase2, unseal_range, validate_cache_for_commit,
    validate_cache_for_precommit_phase2, verify_aggregate_seal_commit_proofs,
    verify_aggregate_sector_update_proofs, verify_empty_sector_update_proof,
    verify_partition_proofs, verify_seal, verify_single_partition_proof, verify_window_post,
    verify_winning_post, Commitment, DefaultTreeDomain, EmptySectorUpdateProof, MerkleTreeTrait,
    PaddedBytesAmount, PieceInfo, PoRepConfig, PoStConfig, PoStType, PrivateReplicaInfo, ProverId,
    PublicReplicaInfo, SealCommitOutput, SealPreCommitOutput, SealPreCommitPhase1Output,
    SectorShape16KiB, SectorShape2KiB, SectorShape32GiB, SectorShape32KiB, SectorShape4KiB,
    SectorUpdateConfig, SectorUpdateProofInputs, UnpaddedByteIndex, UnpaddedBytesAmount,
    SECTOR_SIZE_16_KIB, SECTOR_SIZE_2_KIB, SECTOR_SIZE_32_GIB, SECTOR_SIZE_32_KIB,
    SECTOR_SIZE_4_KIB, WINDOW_POST_CHALLENGE_COUNT, WINDOW_POST_SECTOR_COUNT,
    WINNING_POST_CHALLENGE_COUNT, WINNING_POST_SECTOR_COUNT,
};
use fr32::bytes_into_fr;
use log::{info, trace};
use memmap2::MmapOptions;
use merkletree::store::StoreConfig;
use rand::{random, Rng, SeedableRng};
use rand_xorshift::XorShiftRng;
use sha2::{Digest, Sha256};
use storage_proofs_core::{
    api_version::{ApiFeature, ApiVersion},
    cache_key::CacheKey,
    is_legacy_porep_id,
    merkle::get_base_tree_count,
    sector::SectorId,
    util::NODE_SIZE,
};
use storage_proofs_update::constants::TreeRHasher;
use tempfile::{tempdir, NamedTempFile, TempDir};

use filecoin_proofs::constants::{
    FIP92_MAX_NI_POREP_AGGREGATION_PROOFS, FIP92_MIN_NI_POREP_AGGREGATION_PROOFS,
    MAX_LEGACY_REGISTERED_SEAL_PROOF_ID,
};

#[cfg(feature = "big-tests")]
use filecoin_proofs::{
    SectorShape512MiB, SectorShape64GiB, SectorShape8MiB, SECTOR_SIZE_512_MIB, SECTOR_SIZE_64_GIB,
    SECTOR_SIZE_8_MIB,
};

#[cfg(feature = "persist-regression-proofs")]
mod regression;
#[cfg(feature = "persist-regression-proofs")]
use regression::persist_generated_proof_for_regression_testing;

// Use a fixed PoRep ID, so that the parents cache can be re-used between some tests.
// Note however, that parents caches cannot be shared when testing the differences
// between API v1 and v2 behaviour (since the parent caches will be different for the
// same porep_ids).
const ARBITRARY_POREP_ID_V1_0_0: [u8; 32] = [127; 32];
const ARBITRARY_POREP_ID_V1_1_0: [u8; 32] = [128; 32];
const ARBITRARY_POREP_ID_V1_2_0: [u8; 32] = [129; 32];

const TEST_SEED: [u8; 16] = [
    0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5,
];

fn to_porep_id_verified(registered_seal_proof: u64, api_version: ApiVersion) -> [u8; 32] {
    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&registered_seal_proof.to_le_bytes());

    assert!(match api_version {
        ApiVersion::V1_0_0 => is_legacy_porep_id(porep_id),
        ApiVersion::V1_1_0 | ApiVersion::V1_2_0 => !is_legacy_porep_id(porep_id),
    });

    porep_id
}

#[test]
fn test_get_sector_update_inputs() -> Result<()> {
    fil_logger::maybe_init();

    let porep_id_v1_1_2k: u64 = 5; // This is a RegisteredSealProof value
    let porep_id_v1_1_32g: u64 = 8; // This is a RegisteredSealProof value

    let mut porep_id_2k = [0u8; 32];
    porep_id_2k[..8].copy_from_slice(&porep_id_v1_1_2k.to_le_bytes());
    assert!(!is_legacy_porep_id(porep_id_2k));

    let mut porep_id_32g = [0u8; 32];
    porep_id_32g[..8].copy_from_slice(&porep_id_v1_1_32g.to_le_bytes());
    assert!(!is_legacy_porep_id(porep_id_32g));

    let porep_config_2k =
        PoRepConfig::new_groth16(SECTOR_SIZE_2_KIB, porep_id_2k, ApiVersion::V1_2_0);
    let sector_config_2k = SectorUpdateConfig::from_porep_config(&porep_config_2k);

    let porep_config_32g =
        PoRepConfig::new_groth16(SECTOR_SIZE_32_GIB, porep_id_32g, ApiVersion::V1_2_0);
    let sector_config_32g = SectorUpdateConfig::from_porep_config(&porep_config_32g);

    let comm_r_old = [5u8; 32];
    let comm_r_new = [6u8; 32];
    let comm_d_new = [7u8; 32];

    let inputs_2k = get_sector_update_inputs::<SectorShape2KiB>(
        &porep_config_2k,
        comm_r_old,
        comm_r_new,
        comm_d_new,
    )?;

    // Ensure the num inputs is equal to the number of partitions
    info!("2k sector inputs count is {}", inputs_2k.len());
    ensure!(
        inputs_2k.len() == usize::from(sector_config_2k.update_partitions),
        "2k sector_update_inputs length mismatch"
    );

    let inputs_32g = get_sector_update_inputs::<SectorShape32GiB>(
        &porep_config_32g,
        comm_r_old,
        comm_r_new,
        comm_d_new,
    )?;

    // Ensure the num inputs is equal to the number of partitions
    info!("32g sector inputs count is {}", inputs_32g.len());
    ensure!(
        inputs_32g.len() == usize::from(sector_config_32g.update_partitions),
        "32g sector_update_inputs length mismatch"
    );

    Ok(())
}

#[test]
#[ignore]
fn test_seal_lifecycle_2kib_base_8() -> Result<()> {
    // The first value is RegisteredSealProof value
    // The second value is the ApiVersion to use
    // The third value is enabled Api features
    let test_inputs = vec![
        (0u64, ApiVersion::V1_0_0, Vec::new()),
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_1_0,
            Vec::new(),
        ),
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            Vec::new(),
        ),
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id_num, api_version, features) in test_inputs {
        let porep_id = to_porep_id_verified(porep_id_num, api_version);
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_2_KIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle::<SectorShape2KiB>(&porep_config)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_lifecycle_upgrade_2kib_base_8() -> Result<()> {
    // The first value is RegisteredSealProof value
    // The second value is the ApiVersion to use
    // The third value is enabled Api features
    let test_inputs = vec![
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_1_0,
            Vec::new(),
        ),
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            Vec::new(),
        ),
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id_num, api_version, features) in test_inputs {
        let porep_id = to_porep_id_verified(porep_id_num, api_version);
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_2_KIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle_upgrade::<SectorShape2KiB>(&porep_config)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_lifecycle_4kib_base_8() -> Result<()> {
    let test_inputs = vec![
        (ARBITRARY_POREP_ID_V1_0_0, ApiVersion::V1_0_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_1_0, ApiVersion::V1_1_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_2_0, ApiVersion::V1_2_0, Vec::new()),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id, api_version, features) in test_inputs {
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_4_KIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle::<SectorShape4KiB>(&porep_config)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_lifecycle_upgrade_4kib_base_8() -> Result<()> {
    let test_inputs = vec![
        (ARBITRARY_POREP_ID_V1_0_0, ApiVersion::V1_0_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_1_0, ApiVersion::V1_1_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_2_0, ApiVersion::V1_2_0, Vec::new()),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id, api_version, features) in test_inputs {
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_4_KIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle_upgrade::<SectorShape4KiB>(&porep_config)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_lifecycle_16kib_base_8() -> Result<()> {
    let test_inputs = vec![
        (ARBITRARY_POREP_ID_V1_0_0, ApiVersion::V1_0_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_1_0, ApiVersion::V1_1_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_2_0, ApiVersion::V1_2_0, Vec::new()),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id, api_version, features) in test_inputs {
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_16_KIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle::<SectorShape16KiB>(&porep_config)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_lifecycle_upgrade_16kib_base_8() -> Result<()> {
    let test_inputs = vec![
        (ARBITRARY_POREP_ID_V1_0_0, ApiVersion::V1_0_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_1_0, ApiVersion::V1_1_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_2_0, ApiVersion::V1_2_0, Vec::new()),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id, api_version, features) in test_inputs {
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_16_KIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle_upgrade::<SectorShape16KiB>(&porep_config)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_lifecycle_32kib_base_8() -> Result<()> {
    let test_inputs = vec![
        (ARBITRARY_POREP_ID_V1_0_0, ApiVersion::V1_0_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_1_0, ApiVersion::V1_1_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_2_0, ApiVersion::V1_2_0, Vec::new()),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id, api_version, features) in test_inputs {
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_32_KIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle::<SectorShape32KiB>(&porep_config)?;
    }

    Ok(())
}

// These tests are good to run, but take a long time.

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_8mib_base_8() -> Result<()> {
    let test_inputs = vec![
        (ARBITRARY_POREP_ID_V1_0_0, ApiVersion::V1_0_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_1_0, ApiVersion::V1_1_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_2_0, ApiVersion::V1_2_0, Vec::new()),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id, api_version, features) in test_inputs {
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_8_MIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle::<SectorShape8MiB>(&porep_config)?;
    }

    Ok(())
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_512mib_base_8() -> Result<()> {
    let test_inputs = vec![
        (ARBITRARY_POREP_ID_V1_0_0, ApiVersion::V1_0_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_1_0, ApiVersion::V1_1_0, Vec::new()),
        (ARBITRARY_POREP_ID_V1_2_0, ApiVersion::V1_2_0, Vec::new()),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            ARBITRARY_POREP_ID_V1_2_0,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (porep_id, api_version, features) in test_inputs {
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_512_MIB,
            porep_id,
            api_version,
            features,
        )?;

        seal_lifecycle::<SectorShape512MiB>(&porep_config)?;
    }

    Ok(())
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_upgrade_512mib_top_8_0_0_v1_1() -> Result<()> {
    let porep_config = PoRepConfig::new_groth16(
        SECTOR_SIZE_512_MIB,
        ARBITRARY_POREP_ID_V1_2_0,
        ApiVersion::V1_2_0,
    );
    seal_lifecycle_upgrade::<SectorShape512MiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_32gib_porep_id_v1_top_8_8_0_api_v1() -> Result<()> {
    let porep_id_v1: u64 = 3; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1.to_le_bytes());
    assert!(is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16(SECTOR_SIZE_32_GIB, porep_id, ApiVersion::V1_0_0);
    seal_lifecycle::<SectorShape32GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_32gib_porep_id_v1_1_top_8_8_0_api_v1_1() -> Result<()> {
    let porep_id_v1_1: u64 = 8; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1_1.to_le_bytes());
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16(SECTOR_SIZE_32_GIB, porep_id, ApiVersion::V1_1_0);
    seal_lifecycle::<SectorShape32GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_32gib_porep_id_v1_2_top_8_8_0_api_v1_2() -> Result<()> {
    let porep_id_v1_2: u64 = 8; // This is a RegisteredSealProof value

    let porep_id = to_porep_id_verified(porep_id_v1_2, ApiVersion::V1_2_0);
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16_with_features(
        SECTOR_SIZE_32_GIB,
        porep_id,
        ApiVersion::V1_2_0,
        vec![ApiFeature::SyntheticPoRep],
    )?;

    seal_lifecycle::<SectorShape32GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_32gib_porep_id_v1_2_ni_top_8_8_0_api_v1_2() -> Result<()> {
    let porep_id_v1_2: u64 = 8; // This is a RegisteredSealProof value

    let porep_id = to_porep_id_verified(porep_id_v1_2, ApiVersion::V1_2_0);
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16_with_features(
        SECTOR_SIZE_32_GIB,
        porep_id,
        ApiVersion::V1_2_0,
        vec![ApiFeature::NonInteractivePoRep],
    )?;

    seal_lifecycle::<SectorShape32GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_max_ni_seal_proof_aggregation_32gib() -> Result<()> {
    let porep_id_v1_2: u64 = 8; // This is a RegisteredSealProof value

    let porep_id = to_porep_id_verified(porep_id_v1_2, ApiVersion::V1_2_0);
    let porep_config = PoRepConfig::new_groth16_with_features(
        SECTOR_SIZE_32_GIB,
        porep_id,
        ApiVersion::V1_2_0,
        vec![ApiFeature::NonInteractivePoRep],
    )?;

    aggregate_seal_proofs::<SectorShape32GiB>(&porep_config, FIP92_MAX_NI_POREP_AGGREGATION_PROOFS)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_max_ni_seal_proof_aggregation_64gib() -> Result<()> {
    let porep_id_v1_2: u64 = 9; // This is a RegisteredSealProof value

    let porep_id = to_porep_id_verified(porep_id_v1_2, ApiVersion::V1_2_0);
    let porep_config = PoRepConfig::new_groth16_with_features(
        SECTOR_SIZE_64_GIB,
        porep_id,
        ApiVersion::V1_2_0,
        vec![ApiFeature::NonInteractivePoRep],
    )?;

    aggregate_seal_proofs::<SectorShape64GiB>(&porep_config, FIP92_MAX_NI_POREP_AGGREGATION_PROOFS)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_upgrade_32gib_top_8_8_0_v1_2() -> Result<()> {
    let porep_config = PoRepConfig::new_groth16(
        SECTOR_SIZE_32_GIB,
        ARBITRARY_POREP_ID_V1_2_0,
        ApiVersion::V1_2_0,
    );
    seal_lifecycle_upgrade::<SectorShape32GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_64gib_porep_id_v1_top_8_8_2_api_v1() -> Result<()> {
    let porep_id_v1: u64 = 4; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1.to_le_bytes());
    assert!(is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16(SECTOR_SIZE_64_GIB, porep_id, ApiVersion::V1_0_0);
    seal_lifecycle::<SectorShape64GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_64gib_porep_id_v1_1_top_8_8_2_api_v1_1() -> Result<()> {
    let porep_id_v1_1: u64 = 9; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1_1.to_le_bytes());
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16(SECTOR_SIZE_64_GIB, porep_id, ApiVersion::V1_1_0);
    seal_lifecycle::<SectorShape64GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_64gib_porep_id_v1_2_top_8_8_2_api_v1_2() -> Result<()> {
    let porep_id_v1_2: u64 = 9; // This is a RegisteredSealProof value

    let porep_id = to_porep_id_verified(porep_id_v1_2, ApiVersion::V1_2_0);
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16_with_features(
        SECTOR_SIZE_64_GIB,
        porep_id,
        ApiVersion::V1_2_0,
        vec![ApiFeature::SyntheticPoRep],
    )?;

    seal_lifecycle::<SectorShape64GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_64gib_porep_id_v1_2_ni_top_8_8_2_api_v1_2() -> Result<()> {
    let porep_id_v1_2: u64 = 9; // This is a RegisteredSealProof value

    let porep_id = to_porep_id_verified(porep_id_v1_2, ApiVersion::V1_2_0);
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = PoRepConfig::new_groth16_with_features(
        SECTOR_SIZE_64_GIB,
        porep_id,
        ApiVersion::V1_2_0,
        vec![ApiFeature::NonInteractivePoRep],
    )?;

    seal_lifecycle::<SectorShape64GiB>(&porep_config)
}

#[cfg(feature = "big-tests")]
#[test]
fn test_seal_lifecycle_upgrade_64gib_top_8_8_2_v1_2() -> Result<()> {
    let porep_config = PoRepConfig::new_groth16(
        SECTOR_SIZE_64_GIB,
        ARBITRARY_POREP_ID_V1_2_0,
        ApiVersion::V1_2_0,
    );
    seal_lifecycle_upgrade::<SectorShape64GiB>(&porep_config)
}

fn seal_lifecycle<Tree: 'static + MerkleTreeTrait>(porep_config: &PoRepConfig) -> Result<()> {
    let mut rng = XorShiftRng::from_seed(TEST_SEED);
    let prover_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    info!(
        "Creating seal proof with ApiVersion {} and PoRep ID {:?}",
        porep_config.api_version, porep_config.porep_id
    );
    let (_, replica, _, _) = create_seal::<_, Tree>(porep_config, &mut rng, prover_id, false)?;
    replica.close()?;

    Ok(())
}

fn seal_lifecycle_upgrade<Tree: 'static + MerkleTreeTrait<Hasher = TreeRHasher>>(
    porep_config: &PoRepConfig,
) -> Result<()> {
    let mut rng = &mut XorShiftRng::from_seed(TEST_SEED);
    let prover_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    info!(
        "Creating seal proof for upgrade with ApiVersion {}",
        porep_config.api_version
    );
    let (_, replica, _, _) = create_seal_for_upgrade::<_, Tree>(porep_config, &mut rng, prover_id)?;
    replica.close()?;

    Ok(())
}

#[test]
#[ignore]
fn test_seal_proof_aggregation_2kib() -> Result<()> {
    let test_inputs = vec![
        (
            1,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_1_0,
            vec![],
        ),
        (
            5,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            FIP92_MAX_NI_POREP_AGGREGATION_PROOFS,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (proofs_to_aggregate, porep_id_num, api_version, api_features) in test_inputs {
        let porep_id = to_porep_id_verified(porep_id_num, api_version);
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_2_KIB,
            porep_id,
            api_version,
            api_features,
        )?;

        aggregate_seal_proofs::<SectorShape2KiB>(&porep_config, proofs_to_aggregate)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_proof_aggregation_2kib_failures() -> Result<()> {
    let test_inputs = vec![
        (
            FIP92_MIN_NI_POREP_AGGREGATION_PROOFS - 1,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
        (
            FIP92_MAX_NI_POREP_AGGREGATION_PROOFS + 1,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (proofs_to_aggregate, porep_id_num, api_version, api_features) in test_inputs {
        let porep_id = to_porep_id_verified(porep_id_num, api_version);
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_2_KIB,
            porep_id,
            api_version,
            api_features,
        )?;

        ensure!(
            aggregate_seal_proofs::<SectorShape2KiB>(&porep_config, proofs_to_aggregate).is_err(),
            "test case failure passed unexpectedly"
        );
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_proof_aggregation_4kib() -> Result<()> {
    let test_inputs = vec![
        (
            7,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_1_0,
            vec![],
        ),
        (
            24,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            17,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (proofs_to_aggregate, porep_id_num, api_version, api_features) in test_inputs {
        let porep_id = to_porep_id_verified(porep_id_num, api_version);
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_4_KIB,
            porep_id,
            api_version,
            api_features,
        )?;

        aggregate_seal_proofs::<SectorShape4KiB>(&porep_config, proofs_to_aggregate)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_seal_proof_aggregation_32kib() -> Result<()> {
    let test_inputs = vec![
        (
            220,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_1_0,
            vec![],
        ),
        (
            500,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::SyntheticPoRep],
        ),
        (
            5,
            MAX_LEGACY_REGISTERED_SEAL_PROOF_ID + 1,
            ApiVersion::V1_2_0,
            vec![ApiFeature::NonInteractivePoRep],
        ),
    ];

    for (proofs_to_aggregate, porep_id_num, api_version, api_features) in test_inputs {
        let porep_id = to_porep_id_verified(porep_id_num, api_version);
        let porep_config = PoRepConfig::new_groth16_with_features(
            SECTOR_SIZE_32_KIB,
            porep_id,
            api_version,
            api_features,
        )?;

        aggregate_seal_proofs::<SectorShape32KiB>(&porep_config, proofs_to_aggregate)?;
    }

    Ok(())
}

//#[test]
//#[ignore]
//fn test_seal_proof_aggregation_818_32gib_porep_id_v1_1_base_8() -> Result<()> {
//    let proofs_to_aggregate = 818; // Requires auto-padding
//
//    let porep_id = ARBITRARY_POREP_ID_V1_1_0;
//    assert!(!is_legacy_porep_id(porep_id));
//    let verified = aggregate_seal_proofs::<SectorShape32GiB>(
//        SECTOR_SIZE_32_GIB,
//        &porep_id,
//        ApiVersion::V1_1_0,
//        proofs_to_aggregate,
//    )?;
//    assert!(verified);
//
//    Ok(())
//}

//#[test]
//#[ignore]
//fn test_seal_proof_aggregation_818_64gib_porep_id_v1_1_base_8() -> Result<()> {
//    let proofs_to_aggregate = 818; // Requires auto-padding
//
//    let porep_id = ARBITRARY_POREP_ID_V1_1_0;
//    assert!(!is_legacy_porep_id(porep_id));
//    let verified = aggregate_seal_proofs::<SectorShape64GiB>(
//        SECTOR_SIZE_64_GIB,
//        &porep_id,
//        ApiVersion::V1_1_0,
//        proofs_to_aggregate,
//    )?;
//    assert!(verified);
//
//    Ok(())
//}

#[test]
#[ignore]
fn test_sector_update_proof_aggregation_1011_2kib() -> Result<()> {
    let proofs_to_aggregate = 1011; // Requires auto-padding

    let api_version = ApiVersion::V1_2_0;
    let porep_id = ARBITRARY_POREP_ID_V1_2_0;
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = porep_config(SECTOR_SIZE_2_KIB, porep_id, api_version);
    aggregate_sector_update_proofs::<SectorShape2KiB>(&porep_config, proofs_to_aggregate)
}

#[test]
#[ignore]
fn test_sector_update_proof_aggregation_33_4kib() -> Result<()> {
    let proofs_to_aggregate = 33; // Requires auto-padding

    let api_version = ApiVersion::V1_2_0;
    let porep_id = ARBITRARY_POREP_ID_V1_2_0;
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = porep_config(SECTOR_SIZE_4_KIB, porep_id, api_version);
    aggregate_sector_update_proofs::<SectorShape4KiB>(&porep_config, proofs_to_aggregate)
}

#[test]
#[ignore]
fn test_sector_update_proof_aggregation_508_16kib() -> Result<()> {
    let proofs_to_aggregate = 508; // Requires auto-padding

    let api_version = ApiVersion::V1_2_0;
    let porep_id = ARBITRARY_POREP_ID_V1_2_0;
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = porep_config(SECTOR_SIZE_16_KIB, porep_id, api_version);
    aggregate_sector_update_proofs::<SectorShape16KiB>(&porep_config, proofs_to_aggregate)
}

#[test]
#[ignore]
fn test_sector_update_proof_aggregation_818_32kib() -> Result<()> {
    let proofs_to_aggregate = 818; // Requires auto-padding

    let api_version = ApiVersion::V1_2_0;
    let porep_id = ARBITRARY_POREP_ID_V1_2_0;
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = porep_config(SECTOR_SIZE_32_KIB, porep_id, api_version);
    aggregate_sector_update_proofs::<SectorShape32KiB>(&porep_config, proofs_to_aggregate)
}

#[test]
#[cfg(feature = "big-tests")]
fn test_sector_update_proof_aggregation_11_512mib() -> Result<()> {
    let proofs_to_aggregate = 11; // Requires auto-padding

    let api_version = ApiVersion::V1_2_0;
    let porep_id = ARBITRARY_POREP_ID_V1_2_0;
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = porep_config(SECTOR_SIZE_512_MIB, porep_id, api_version);
    aggregate_sector_update_proofs::<SectorShape512MiB>(&porep_config, proofs_to_aggregate)
}

#[test]
#[cfg(feature = "big-tests")]
fn test_sector_update_proof_aggregation_455_32gib() -> Result<()> {
    let proofs_to_aggregate = 455; // Requires auto-padding

    let api_version = ApiVersion::V1_2_0;
    let porep_id = ARBITRARY_POREP_ID_V1_2_0;
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = porep_config(SECTOR_SIZE_32_GIB, porep_id, api_version);
    aggregate_sector_update_proofs::<SectorShape32GiB>(&porep_config, proofs_to_aggregate)
}

#[test]
#[cfg(feature = "big-tests")]
fn test_sector_update_proof_aggregation_3_64gib() -> Result<()> {
    let proofs_to_aggregate = 3; // Requires auto-padding

    let api_version = ApiVersion::V1_2_0;
    let porep_id = ARBITRARY_POREP_ID_V1_2_0;
    assert!(!is_legacy_porep_id(porep_id));

    let porep_config = porep_config(SECTOR_SIZE_64_GIB, porep_id, api_version);
    aggregate_sector_update_proofs::<SectorShape64GiB>(&porep_config, proofs_to_aggregate)
}

fn aggregate_seal_proofs<Tree: 'static + MerkleTreeTrait>(
    porep_config: &PoRepConfig,
    num_proofs_to_aggregate: usize,
) -> Result<()> {
    fil_logger::maybe_init();

    let mut rng = XorShiftRng::from_seed(TEST_SEED);
    let prover_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    // Note that ApiVersion 1.2.0 only supports SnarkPack v2, so only
    // allow that testing here.
    let aggregate_versions = match porep_config.api_version {
        ApiVersion::V1_2_0 => vec![groth16::aggregate::AggregateVersion::V2],
        ApiVersion::V1_1_0 => vec![
            groth16::aggregate::AggregateVersion::V1,
            groth16::aggregate::AggregateVersion::V2,
        ],
        ApiVersion::V1_0_0 => vec![groth16::aggregate::AggregateVersion::V1],
    };
    info!(
        "Aggregating {} seal proof with ApiVersion {}, Features {:?}, and PoRep ID {:?}",
        num_proofs_to_aggregate,
        porep_config.api_version,
        porep_config.api_features,
        porep_config.porep_id
    );

    for aggregate_version in aggregate_versions {
        info!(
            "Aggregating {} seal proofs with ApiVersion {}, Snarkpack{}, Features {:?}, and PoRep ID {:?}",
            num_proofs_to_aggregate,
            porep_config.api_version,
            aggregate_version,
            porep_config.api_features,
            porep_config.porep_id
        );

        let mut commit_outputs = Vec::with_capacity(num_proofs_to_aggregate);
        let mut commit_inputs = Vec::with_capacity(num_proofs_to_aggregate);
        let mut seeds = Vec::with_capacity(num_proofs_to_aggregate);
        let mut comm_rs = Vec::with_capacity(num_proofs_to_aggregate);

        let (commit_output, commit_input, seed, comm_r) =
            create_seal_for_aggregation::<_, Tree>(&mut rng, porep_config, prover_id)?;

        for _ in 0..num_proofs_to_aggregate {
            commit_outputs.push(commit_output.clone());
            commit_inputs.extend(commit_input.clone());
            seeds.push(seed);
            comm_rs.push(comm_r);
        }

        let aggregate_proof = aggregate_seal_commit_proofs::<Tree>(
            porep_config,
            &comm_rs,
            &seeds,
            commit_outputs.as_slice(),
            aggregate_version,
        )?;
        info!("Aggregate proof size is {} bytes", aggregate_proof.len());
        assert!(verify_aggregate_seal_commit_proofs::<Tree>(
            porep_config,
            aggregate_proof.clone(),
            &comm_rs,
            &seeds,
            commit_inputs.clone(),
            aggregate_version,
        )?);

        // This ensures that once we generate an snarkpack proof
        // with one version, it cannot verify with another.
        let conflicting_aggregate_version = match aggregate_version {
            groth16::aggregate::AggregateVersion::V1 => groth16::aggregate::AggregateVersion::V2,
            groth16::aggregate::AggregateVersion::V2 => groth16::aggregate::AggregateVersion::V1,
        };
        assert!(!verify_aggregate_seal_commit_proofs::<Tree>(
            porep_config,
            aggregate_proof,
            &comm_rs,
            &seeds,
            commit_inputs,
            conflicting_aggregate_version,
        )?);
    }

    Ok(())
}

fn aggregate_sector_update_proofs<Tree: 'static + MerkleTreeTrait<Hasher = TreeRHasher>>(
    porep_config: &PoRepConfig,
    num_proofs_to_aggregate: usize,
) -> Result<()> {
    fil_logger::maybe_init();

    let mut rng = &mut XorShiftRng::from_seed(TEST_SEED);
    let prover_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    // Note: Sector Update aggregation only supports SnarkPackV2
    let aggregate_versions = vec![groth16::aggregate::AggregateVersion::V2];

    let (proof, proof_inputs) =
        create_seal_for_upgrade_aggregation::<_, Tree>(porep_config, &mut rng, prover_id)?;

    for aggregate_version in aggregate_versions {
        info!(
            "***** Aggregating {} sector update proofs *****",
            num_proofs_to_aggregate
        );
        let mut sector_update_proofs = Vec::with_capacity(num_proofs_to_aggregate);
        let mut sector_update_inputs = Vec::with_capacity(num_proofs_to_aggregate);
        for _ in 0..num_proofs_to_aggregate {
            sector_update_proofs.push(proof.clone());
            sector_update_inputs.push(proof_inputs.clone());
        }
        ensure!(sector_update_proofs.len() == num_proofs_to_aggregate);
        ensure!(sector_update_inputs.len() == num_proofs_to_aggregate);

        let agg_update_proof = aggregate_empty_sector_update_proofs::<Tree>(
            porep_config,
            &sector_update_proofs,
            &sector_update_inputs,
            aggregate_version,
        )?;

        let combined_sector_update_inputs: Vec<Vec<Fr>> = sector_update_inputs
            .iter()
            .flat_map(|input| {
                get_sector_update_inputs::<Tree>(
                    porep_config,
                    input.comm_r_old,
                    input.comm_r_new,
                    input.comm_d_new,
                )
                .expect("failed to get sector update inputs")
            })
            .collect();

        trace!(
            "combined sector update inputs len {}, sector_update_inputs len {}",
            combined_sector_update_inputs.len(),
            sector_update_inputs.len()
        );

        let valid = verify_aggregate_sector_update_proofs::<Tree>(
            porep_config,
            agg_update_proof,
            &sector_update_inputs,
            combined_sector_update_inputs,
            aggregate_version,
        )?;
        ensure!(
            valid,
            "aggregate empty sector update proof failed to verify"
        );
    }

    Ok(())
}

fn get_layer_file_paths(cache_dir: &tempfile::TempDir) -> Vec<PathBuf> {
    let mut list: Vec<_> = read_dir(cache_dir)
        .unwrap_or_else(|_| panic!("failed to read directory {:?}", cache_dir))
        .filter_map(|entry| {
            let cur = entry.expect("reading directory failed");
            let entry_path = cur.path();
            let entry_str = entry_path.to_str().expect("failed to get string from path");
            if entry_str.contains("data-layer") {
                Some(entry_path.clone())
            } else {
                None
            }
        })
        .collect();
    list.sort();
    list
}

fn clear_cache_dir_keep_data_layer(cache_dir: &TempDir) {
    for entry in read_dir(cache_dir).expect("failed to read directory") {
        let entry_path = entry.expect("failed get directory entry").path();
        if entry_path.is_file() {
            // delete everything except the data-layers
            if !entry_path
                .to_str()
                .expect("failed to get string from path")
                .contains("data-layer")
            {
                remove_file(entry_path).expect("failed to remove file")
            }
        }
    }
}

#[test]
fn test_resumable_seal_skip_proofs_v1() {
    let porep_id_v1: u64 = 0; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1.to_le_bytes());
    assert!(is_legacy_porep_id(porep_id));
    run_resumable_seal::<SectorShape2KiB>(true, 0, &porep_id, ApiVersion::V1_0_0);
    run_resumable_seal::<SectorShape2KiB>(true, 1, &porep_id, ApiVersion::V1_0_0);
}

#[test]
fn test_resumable_seal_skip_proofs_v1_1() {
    let porep_id_v1_1: u64 = 5; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1_1.to_le_bytes());
    assert!(!is_legacy_porep_id(porep_id));
    run_resumable_seal::<SectorShape2KiB>(true, 0, &porep_id, ApiVersion::V1_1_0);
    run_resumable_seal::<SectorShape2KiB>(true, 1, &porep_id, ApiVersion::V1_1_0);
}

#[test]
#[ignore]
fn test_resumable_seal_v1() {
    let porep_id_v1: u64 = 0; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1.to_le_bytes());
    assert!(is_legacy_porep_id(porep_id));
    run_resumable_seal::<SectorShape2KiB>(false, 0, &porep_id, ApiVersion::V1_0_0);
    run_resumable_seal::<SectorShape2KiB>(false, 1, &porep_id, ApiVersion::V1_0_0);
}

#[test]
#[ignore]
fn test_resumable_seal_v1_1() {
    let porep_id_v1_1: u64 = 5; // This is a RegisteredSealProof value

    let mut porep_id = [0u8; 32];
    porep_id[..8].copy_from_slice(&porep_id_v1_1.to_le_bytes());
    assert!(!is_legacy_porep_id(porep_id));
    run_resumable_seal::<SectorShape2KiB>(false, 0, &porep_id, ApiVersion::V1_1_0);
    run_resumable_seal::<SectorShape2KiB>(false, 1, &porep_id, ApiVersion::V1_1_0);
}

/// Create a seal, delete a layer and resume
///
/// The current code works on two layers only. The `layer_to_delete` specifies (zero-based) which
/// layer should be deleted.
fn run_resumable_seal<Tree: 'static + MerkleTreeTrait>(
    skip_proofs: bool,
    layer_to_delete: usize,
    porep_id: &[u8; 32],
    api_version: ApiVersion,
) {
    fil_logger::maybe_init();

    let sector_size = SECTOR_SIZE_2_KIB;
    let mut rng = XorShiftRng::from_seed(TEST_SEED);
    let prover_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    let (mut piece_file, piece_bytes) =
        generate_piece_file(sector_size).expect("failed to generate piece file");
    let sealed_sector_file = NamedTempFile::new().expect("failed to created sealed sector file");
    let cache_dir = tempdir().expect("failed to create temp dir");

    let config = porep_config(sector_size, *porep_id, api_version);
    let ticket = rng.gen();
    let sector_id = rng.gen::<u64>().into();

    // First create seals as expected
    run_seal_pre_commit_phase1::<Tree>(
        &config,
        prover_id,
        sector_id,
        ticket,
        &cache_dir,
        &mut piece_file,
        &sealed_sector_file,
    )
    .expect("failed to run seal pre commit phase1");
    let layers = get_layer_file_paths(&cache_dir);
    assert_eq!(layers.len(), 2, "not all expected layers were created");

    // Delete one layer, keep the other
    clear_cache_dir_keep_data_layer(&cache_dir);
    remove_file(&layers[layer_to_delete]).expect("failed to remove layer");
    let layers_remaining = get_layer_file_paths(&cache_dir);
    assert_eq!(layers_remaining.len(), 1, "expected one layer only");
    if layer_to_delete == 0 {
        assert_eq!(layers_remaining[0], layers[1], "wrong layer was removed");
    } else {
        assert_eq!(layers_remaining[0], layers[0], "wrong layer was removed");
    }

    // Resume the seal
    piece_file
        .rewind()
        .expect("failed to seek piece file to start");
    let (piece_infos, phase1_output) = run_seal_pre_commit_phase1::<Tree>(
        &config,
        prover_id,
        sector_id,
        ticket,
        &cache_dir,
        &mut piece_file,
        &sealed_sector_file,
    )
    .expect("failed to run seal pre commit phase1");

    // Running proofs clears the cache, hence we can only check for existence of files if we don't
    // run them
    if skip_proofs {
        let layers_recreated = get_layer_file_paths(&cache_dir);
        assert_eq!(
            layers_recreated.len(),
            2,
            "not all expected layers were recreated"
        );
        assert_eq!(
            layers_recreated, layers,
            "recreated layers don't match original ones"
        );
    } else {
        let pre_commit_output = seal_pre_commit_phase2(
            &config,
            phase1_output,
            cache_dir.path(),
            sealed_sector_file.path(),
        )
        .expect("failed to run seal pre commit phase2");

        validate_cache_for_commit::<_, _, Tree>(cache_dir.path(), sealed_sector_file.path())
            .expect("failed to validate cache for commit");

        let seed = rng.gen();
        proof_and_unseal::<Tree>(
            &config,
            cache_dir.path(),
            &sealed_sector_file,
            prover_id,
            sector_id,
            ticket,
            seed,
            pre_commit_output,
            &piece_infos,
            &piece_bytes,
        )
        .expect("failed to proof");
    }
}

#[test]
#[ignore]
fn test_winning_post_2kib_base_8() -> Result<()> {
    winning_post::<SectorShape2KiB>(SECTOR_SIZE_2_KIB, false, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape2KiB>(SECTOR_SIZE_2_KIB, true, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape2KiB>(SECTOR_SIZE_2_KIB, false, ApiVersion::V1_1_0)?;
    winning_post::<SectorShape2KiB>(SECTOR_SIZE_2_KIB, true, ApiVersion::V1_1_0)
}

#[test]
#[ignore]
fn test_winning_post_4kib_sub_8_2() -> Result<()> {
    winning_post::<SectorShape4KiB>(SECTOR_SIZE_4_KIB, false, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape4KiB>(SECTOR_SIZE_4_KIB, true, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape4KiB>(SECTOR_SIZE_4_KIB, false, ApiVersion::V1_1_0)?;
    winning_post::<SectorShape4KiB>(SECTOR_SIZE_4_KIB, true, ApiVersion::V1_1_0)
}

#[test]
#[ignore]
fn test_winning_post_16kib_sub_8_8() -> Result<()> {
    winning_post::<SectorShape16KiB>(SECTOR_SIZE_16_KIB, false, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape16KiB>(SECTOR_SIZE_16_KIB, true, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape16KiB>(SECTOR_SIZE_16_KIB, false, ApiVersion::V1_1_0)?;
    winning_post::<SectorShape16KiB>(SECTOR_SIZE_16_KIB, true, ApiVersion::V1_1_0)
}

#[test]
#[ignore]
fn test_winning_post_32kib_top_8_8_2() -> Result<()> {
    winning_post::<SectorShape32KiB>(SECTOR_SIZE_32_KIB, false, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape32KiB>(SECTOR_SIZE_32_KIB, true, ApiVersion::V1_0_0)?;
    winning_post::<SectorShape32KiB>(SECTOR_SIZE_32_KIB, false, ApiVersion::V1_1_0)?;
    winning_post::<SectorShape32KiB>(SECTOR_SIZE_32_KIB, true, ApiVersion::V1_1_0)
}

#[test]
fn test_winning_post_empty_sector_challenge() -> Result<()> {
    let mut rng = XorShiftRng::from_seed(TEST_SEED);

    let prover_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    let sector_count = 0;
    let sector_size = SECTOR_SIZE_2_KIB;
    let porep_id = ARBITRARY_POREP_ID_V1_1_0;
    let api_version = ApiVersion::V1_1_0;

    let porep_config = PoRepConfig::new_groth16(sector_size, porep_id, api_version);
    let (_, replica, _, _) =
        create_seal::<_, SectorShape2KiB>(&porep_config, &mut rng, prover_id, true)?;

    let random_fr: DefaultTreeDomain = Fr::random(rng).into();
    let mut randomness = [0u8; 32];
    randomness.copy_from_slice(AsRef::<[u8]>::as_ref(&random_fr));

    let config = PoStConfig {
        sector_size: sector_size.into(),
        sector_count,
        challenge_count: WINNING_POST_CHALLENGE_COUNT,
        typ: PoStType::Winning,
        priority: false,
        api_version,
    };

    assert!(generate_winning_post_sector_challenge::<SectorShape2KiB>(
        &config,
        &randomness,
        sector_count as u64,
        prover_id
    )
    .is_err());

    replica.close()?;

    Ok(())
}

fn winning_post<Tree: 'static + MerkleTreeTrait>(
    sector_size: u64,
    fake: bool,
    api_version: ApiVersion,
) -> Result<()> {
    let mut rng = XorShiftRng::from_seed(TEST_SEED);

    let prover_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    let porep_id = match api_version {
        ApiVersion::V1_0_0 => ARBITRARY_POREP_ID_V1_0_0,
        ApiVersion::V1_1_0 => ARBITRARY_POREP_ID_V1_1_0,
        ApiVersion::V1_2_0 => ARBITRARY_POREP_ID_V1_2_0,
    };

    let porep_config = PoRepConfig::new_groth16(sector_size, porep_id, api_version);
    let (sector_id, replica, comm_r, cache_dir) = if fake {
        create_fake_seal::<_, Tree>(&mut rng, sector_size, &porep_id, api_version)?
    } else {
        create_seal::<_, Tree>(&porep_config, &mut rng, prover_id, true)?
    };
    let sector_count = WINNING_POST_SECTOR_COUNT;

    let random_fr: DefaultTreeDomain = Fr::random(&mut rng).into();
    let mut randomness = [0u8; 32];
    randomness.copy_from_slice(AsRef::<[u8]>::as_ref(&random_fr));

    let config = PoStConfig {
        sector_size: sector_size.into(),
        sector_count,
        challenge_count: WINNING_POST_CHALLENGE_COUNT,
        typ: PoStType::Winning,
        priority: false,
        api_version,
    };

    let challenged_sectors = generate_winning_post_sector_challenge::<Tree>(
        &config,
        &randomness,
        sector_count as u64,
        prover_id,
    )?;
    assert_eq!(challenged_sectors.len(), sector_count);
    assert_eq!(challenged_sectors[0], 0); // with a sector_count of 1, the only valid index is 0

    let pub_replicas = [(sector_id, PublicReplicaInfo::new(comm_r)?)];
    let private_replica_info =
        PrivateReplicaInfo::new(replica.path().into(), comm_r, cache_dir.path().into())?;

    /////////////////////////////////////////////
    // The following methods of proof generation are functionally equivalent:
    // 1)
    //
    let priv_replicas = [(sector_id, private_replica_info.clone())];
    let proof = generate_winning_post::<Tree>(&config, &randomness, &priv_replicas[..], prover_id)?;

    let valid =
        verify_winning_post::<Tree>(&config, &randomness, &pub_replicas[..], prover_id, &proof)?;
    assert!(valid, "proof did not verify");

    //
    // 2)
    let mut vanilla_proofs = Vec::with_capacity(sector_count);
    let challenges =
        generate_fallback_sector_challenges::<Tree>(&config, &randomness, &[sector_id], prover_id)?;

    // Make sure that files can be read-only for a window post.
    set_readonly_flag(replica.path(), true);
    set_readonly_flag(cache_dir.path(), true);

    let single_proof = generate_single_vanilla_proof::<Tree>(
        &config,
        sector_id,
        &private_replica_info,
        &challenges[&sector_id],
    )?;

    vanilla_proofs.push(single_proof);

    let proof = generate_winning_post_with_vanilla::<Tree>(
        &config,
        &randomness,
        prover_id,
        vanilla_proofs,
    )?;
    /////////////////////////////////////////////

    let valid =
        verify_winning_post::<Tree>(&config, &randomness, &pub_replicas[..], prover_id, &proof)?;
    assert!(valid, "proof did not verify");

    // Make files writeable again, so that the temporary directory can be removed.
    set_readonly_flag(replica.path(), false);
    set_readonly_flag(cache_dir.path(), false);

    replica.close()?;

    Ok(())
}

#[test]
#[ignore]
fn test_window_post_single_partition_smaller_2kib_base_8() -> Result<()> {
    let sector_size = SECTOR_SIZE_2_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        window_post::<SectorShape2KiB>(
            sector_size,
            sector_count / 2,
            sector_count,
            false,
            version,
        )?;
        window_post::<SectorShape2KiB>(sector_size, sector_count / 2, sector_count, true, version)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_window_post_two_partitions_matching_2kib_base_8() -> Result<()> {
    let sector_size = SECTOR_SIZE_2_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        window_post::<SectorShape2KiB>(
            sector_size,
            2 * sector_count,
            sector_count,
            false,
            version,
        )?;
        window_post::<SectorShape2KiB>(sector_size, 2 * sector_count, sector_count, true, version)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_window_post_two_partitions_matching_4kib_sub_8_2() -> Result<()> {
    let sector_size = SECTOR_SIZE_4_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        window_post::<SectorShape4KiB>(
            sector_size,
            2 * sector_count,
            sector_count,
            false,
            version,
        )?;
        window_post::<SectorShape4KiB>(sector_size, 2 * sector_count, sector_count, true, version)?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_window_post_two_partitions_matching_16kib_sub_8_8() -> Result<()> {
    let sector_size = SECTOR_SIZE_16_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        window_post::<SectorShape16KiB>(
            sector_size,
            2 * sector_count,
            sector_count,
            false,
            version,
        )?;
        window_post::<SectorShape16KiB>(
            sector_size,
            2 * sector_count,
            sector_count,
            true,
            version,
        )?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_window_post_two_partitions_matching_32kib_top_8_8_2() -> Result<()> {
    let sector_size = SECTOR_SIZE_32_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        window_post::<SectorShape32KiB>(
            sector_size,
            2 * sector_count,
            sector_count,
            false,
            version,
        )?;
        window_post::<SectorShape32KiB>(
            sector_size,
            2 * sector_count,
            sector_count,
            true,
            version,
        )?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_window_post_two_partitions_smaller_2kib_base_8() -> Result<()> {
    let sector_size = SECTOR_SIZE_2_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        window_post::<SectorShape2KiB>(
            sector_size,
            2 * sector_count - 1,
            sector_count,
            false,
            version,
        )?;
        window_post::<SectorShape2KiB>(
            sector_size,
            2 * sector_count - 1,
            sector_count,
            true,
            version,
        )?;
    }

    Ok(())
}

#[test]
#[ignore]
fn test_window_post_single_partition_matching_2kib_base_8() -> Result<()> {
    let sector_size = SECTOR_SIZE_2_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        window_post::<SectorShape2KiB>(sector_size, sector_count, sector_count, false, version)?;
        window_post::<SectorShape2KiB>(sector_size, sector_count, sector_count, true, version)?;
    }

    Ok(())
}

#[test]
fn test_window_post_partition_matching_2kib_base_8() -> Result<()> {
    let sector_size = SECTOR_SIZE_2_KIB;
    let sector_count = *WINDOW_POST_SECTOR_COUNT
        .read()
        .expect("WINDOW_POST_SECTOR_COUNT poisoned")
        .get(&sector_size)
        .expect("unknown sector size");

    let versions = vec![ApiVersion::V1_0_0, ApiVersion::V1_1_0, ApiVersion::V1_2_0];
    for version in versions {
        partition_window_post::<SectorShape2KiB>(
            sector_size,
            3, // Validate the scenarios of two partition
            sector_count,
            false,
            version,
        )?;
        partition_window_post::<SectorShape2KiB>(sector_size, 3, sector_count, true, version)?;
    }

    Ok(())
}

#[allow(clippy::iter_kv_map)]
fn partition_window_post<Tree: 'static + MerkleTreeTrait>(
    sector_size: u64,
    total_sector_count: usize,
    sector_count: usize,
    fake: bool,
    api_version: ApiVersion,
) -> Result<()> {
    use anyhow::anyhow;

    let mut rng = XorShiftRng::from_seed(TEST_SEED);

    let mut sectors = Vec::with_capacity(total_sector_count);
    let mut pub_replicas = BTreeMap::new();
    let mut priv_replicas = BTreeMap::new();

    let prover_fr: <Tree::Hasher as Hasher>::Domain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    let porep_id = match api_version {
        ApiVersion::V1_0_0 => ARBITRARY_POREP_ID_V1_0_0,
        ApiVersion::V1_1_0 => ARBITRARY_POREP_ID_V1_1_0,
        ApiVersion::V1_2_0 => ARBITRARY_POREP_ID_V1_2_0,
    };

    let porep_config = PoRepConfig::new_groth16(sector_size, porep_id, api_version);
    for _ in 0..total_sector_count {
        let (sector_id, replica, comm_r, cache_dir) = if fake {
            create_fake_seal::<_, Tree>(&mut rng, sector_size, &porep_id, api_version)?
        } else {
            create_seal::<_, Tree>(&porep_config, &mut rng, prover_id, true)?
        };
        priv_replicas.insert(
            sector_id,
            PrivateReplicaInfo::new(replica.path().into(), comm_r, cache_dir.path().into())?,
        );
        pub_replicas.insert(sector_id, PublicReplicaInfo::new(comm_r)?);
        sectors.push((sector_id, replica, comm_r, cache_dir, prover_id));
    }
    assert_eq!(priv_replicas.len(), total_sector_count);
    assert_eq!(pub_replicas.len(), total_sector_count);
    assert_eq!(sectors.len(), total_sector_count);

    let random_fr: <Tree::Hasher as Hasher>::Domain = Fr::random(&mut rng).into();
    let mut randomness = [0u8; 32];
    randomness.copy_from_slice(AsRef::<[u8]>::as_ref(&random_fr));

    let config = PoStConfig {
        sector_size: sector_size.into(),
        sector_count,
        challenge_count: WINDOW_POST_CHALLENGE_COUNT,
        typ: PoStType::Window,
        priority: false,
        api_version,
    };

    let replica_sectors = priv_replicas
        .iter()
        .map(|(sector, _replica)| *sector)
        .collect::<Vec<SectorId>>();

    let challenges = generate_fallback_sector_challenges::<Tree>(
        &config,
        &randomness,
        &replica_sectors,
        prover_id,
    )?;

    let num_sectors_per_chunk = config.sector_count;
    let mut proofs = Vec::new();

    let partitions = get_num_partition_for_fallback_post(&config, replica_sectors.len());
    for partition_index in 0..partitions {
        let sector_ids = replica_sectors
            .chunks(num_sectors_per_chunk)
            .nth(partition_index)
            .ok_or_else(|| anyhow!("invalid number of sectors/partition index"))?;

        let mut partition_priv_replicas = BTreeMap::new();
        for id in sector_ids {
            let p_sector = match priv_replicas.get(id) {
                Some(v) => v,
                _ => {
                    continue;
                }
            };

            partition_priv_replicas.insert(*id, p_sector);
        }

        let mut vanilla_proofs = Vec::new();
        for (sector_id, sector) in partition_priv_replicas.iter() {
            let sector_challenges = &challenges[sector_id];
            let single_proof = generate_single_vanilla_proof::<Tree>(
                &config,
                *sector_id,
                sector,
                sector_challenges,
            )?;

            vanilla_proofs.push(single_proof);
        }

        let proof = generate_single_window_post_with_vanilla(
            &config,
            &randomness,
            prover_id,
            vanilla_proofs,
            partition_index,
        )?;

        proofs.push(proof);
    }

    let final_proof = merge_window_post_partition_proofs(proofs)?;
    let valid =
        verify_window_post::<Tree>(&config, &randomness, &pub_replicas, prover_id, &final_proof)?;
    assert!(valid, "proofs did not verify");

    Ok(())
}

/// Make all files recursively read-only/writeable, starting at the given directory/file.
fn set_readonly_flag(path: &Path, readonly: bool) {
    for entry in walkdir::WalkDir::new(path) {
        let entry = entry.expect("couldn't get file");
        let metadata = entry.metadata().expect("couldn't get metadata");
        let mut permissions = metadata.permissions();
        permissions.set_readonly(readonly);
        std::fs::set_permissions(entry.path(), permissions)
            .expect("couldn't apply read-only permissions");
    }
}

#[allow(clippy::iter_kv_map)]
fn window_post<Tree: 'static + MerkleTreeTrait>(
    sector_size: u64,
    total_sector_count: usize,
    sector_count: usize,
    fake: bool,
    api_version: ApiVersion,
) -> Result<()> {
    let mut rng = XorShiftRng::from_seed(TEST_SEED);

    let mut sectors = Vec::with_capacity(total_sector_count);
    let mut pub_replicas = BTreeMap::new();
    let mut priv_replicas = BTreeMap::new();
    let mut priv_faulty_replicas = BTreeMap::new();

    let prover_fr: <Tree::Hasher as Hasher>::Domain = Fr::random(&mut rng).into();
    let mut prover_id = [0u8; 32];
    prover_id.copy_from_slice(AsRef::<[u8]>::as_ref(&prover_fr));

    let porep_id = match api_version {
        ApiVersion::V1_0_0 => ARBITRARY_POREP_ID_V1_0_0,
        ApiVersion::V1_1_0 => ARBITRARY_POREP_ID_V1_1_0,
        ApiVersion::V1_2_0 => ARBITRARY_POREP_ID_V1_2_0,
    };

    let porep_config = PoRepConfig::new_groth16(sector_size, porep_id, api_version);
    for _ in 0..total_sector_count {
        let (sector_id, replica, comm_r, cache_dir) = if fake {
            create_fake_seal::<_, Tree>(&mut rng, sector_size, &porep_id, api_version)?
        } else {
            create_seal::<_, Tree>(&porep_config, &mut rng, prover_id, true)?
        };
        priv_replicas.insert(
            sector_id,
            PrivateReplicaInfo::new(replica.path().into(), comm_r, cache_dir.path().into())?,
        );

        // Create a bad replica (total failure) and add to
        // priv_faulty_replicas for checking later.
        //
        // Note: the file length makes it impossible to have any valid
        // proofs generated.  If we did something like
        // .set_len(metadata(replica.path())?.len() - 1)?
        // we could see a partial result (depending on sector shape).
        let bad_replica = NamedTempFile::new()?;
        bad_replica.as_file().set_len(1)?;
        priv_faulty_replicas.insert(
            sector_id,
            PrivateReplicaInfo::<Tree>::new(
                bad_replica.path().into(),
                comm_r,
                cache_dir.path().into(),
            )?,
        );
        bad_replica.keep()?;

        pub_replicas.insert(sector_id, PublicReplicaInfo::new(comm_r)?);
        sectors.push((sector_id, replica, comm_r, cache_dir, prover_id));
    }
    assert_eq!(priv_replicas.len(), total_sector_count);
    assert_eq!(pub_replicas.len(), total_sector_count);
    assert_eq!(sectors.len(), total_sector_count);

    let random_fr: <Tree::Hasher as Hasher>::Domain = Fr::random(&mut rng).into();
    let mut randomness = [0u8; 32];
    randomness.copy_from_slice(AsRef::<[u8]>::as_ref(&random_fr));

    let config = PoStConfig {
        sector_size: sector_size.into(),
        sector_count,
        challenge_count: WINDOW_POST_CHALLENGE_COUNT,
        typ: PoStType::Window,
        priority: false,
        api_version,
    };

    /////////////////////////////////////////////
    // The following methods of proof generation are functionally equivalent:
    // 1)
    let proof = generate_window_post::<Tree>(&config, &randomness, &priv_replicas, prover_id)?;

    let valid = verify_window_post::<Tree>(&config, &randomness, &pub_replicas, prover_id, &proof)?;
    assert!(valid, "proof did not verify");

    // 2)
    let replica_sectors = priv_replicas
        .iter()
        .map(|(sector, _replica)| *sector)
        .collect::<Vec<SectorId>>();

    let challenges = generate_fallback_sector_challenges::<Tree>(
        &config,
        &randomness,
        &replica_sectors,
        prover_id,
    )?;

    let mut vanilla_proofs = Vec::with_capacity(replica_sectors.len());

    // Make sure that files can be read-only for a window post.
    for (_, replica, _, cache_dir, _) in &sectors {
        set_readonly_flag(replica.path(), true);
        set_readonly_flag(cache_dir.path(), true);
    }

    for (sector_id, replica) in priv_replicas.iter() {
        let sector_challenges = &challenges[sector_id];
        let single_proof =
            generate_single_vanilla_proof::<Tree>(&config, *sector_id, replica, sector_challenges)?;

        vanilla_proofs.push(single_proof);
    }

    let proof =
        generate_window_post_with_vanilla::<Tree>(&config, &randomness, prover_id, vanilla_proofs)?;

    let valid = verify_window_post::<Tree>(&config, &randomness, &pub_replicas, prover_id, &proof)?;
    assert!(valid, "proof did not verify");
    /////////////////////////////////////////////

    // Lastly, let's ensure we're getting the faulty sectors.
    {
        let mut faulty_sectors = Vec::new();
        let proof =
            generate_window_post::<Tree>(&config, &randomness, &priv_faulty_replicas, prover_id);

        use storage_proofs_core::error::Error as FaultySectorError;
        match proof {
            Ok(proof) => {
                let valid = verify_window_post::<Tree>(
                    &config,
                    &randomness,
                    &pub_replicas,
                    prover_id,
                    &proof,
                )?;
                assert!(!valid, "proof made with faulty sectors verified");
            }
            Err(e) => match e.downcast::<FaultySectorError>() {
                Err(_) => panic!("failed to downcast to Error"),
                Ok(FaultySectorError::FaultySectors(sector_ids)) => {
                    info!("faulty_sectors detected properly: {:?}", sector_ids);
                    faulty_sectors.extend(sector_ids);
                }
                Ok(_) => panic!("PoSt failed to return FaultySectors error."),
            },
        };

        // This assertion is for the case of a total failure, not a
        // partial failure.
        assert_eq!(
            faulty_sectors.len(),
            priv_faulty_replicas.len(),
            "faulty sector detection failure"
        );

        priv_faulty_replicas
            .iter()
            .for_each(|(sector_id, faulty_replica)| {
                // Ensure we have a record of the faulty sector
                assert!(
                    faulty_sectors.contains(sector_id),
                    "faulty sector not reported"
                );
                // Delete temporary faulty_replica files.
                remove_file(faulty_replica.replica_path()).expect("failed to remove faulty_replica")
            });
    }

    // Make files writeable again, so that the temporary directory can be removed.
    for (_, replica, _, cache_dir, _) in &sectors {
        set_readonly_flag(replica.path(), false);
        set_readonly_flag(cache_dir.path(), false);
    }

    Ok(())
}

fn generate_piece_file(sector_size: u64) -> Result<(NamedTempFile, Vec<u8>)> {
    let number_of_bytes_in_piece = UnpaddedBytesAmount::from(PaddedBytesAmount(sector_size));

    let piece_bytes: Vec<u8> = (0..number_of_bytes_in_piece.0)
        .map(|_| random::<u8>())
        .collect();

    let mut piece_file = NamedTempFile::new()?;
    piece_file.write_all(&piece_bytes)?;
    piece_file.as_file_mut().sync_all()?;
    piece_file.as_file_mut().rewind()?;

    Ok((piece_file, piece_bytes))
}

fn porep_config(sector_size: u64, porep_id: [u8; 32], api_version: ApiVersion) -> PoRepConfig {
    PoRepConfig::new_groth16(sector_size, porep_id, api_version)
}

fn run_seal_pre_commit_phase1<Tree: 'static + MerkleTreeTrait>(
    config: &PoRepConfig,
    prover_id: ProverId,
    sector_id: SectorId,
    ticket: [u8; 32],
    cache_dir: &TempDir,
    mut piece_file: &mut NamedTempFile,
    sealed_sector_file: &NamedTempFile,
) -> Result<(Vec<PieceInfo>, SealPreCommitPhase1Output<Tree>)> {
    let number_of_bytes_in_piece = config.unpadded_bytes_amount();

    let piece_info = generate_piece_commitment(piece_file.as_file_mut(), number_of_bytes_in_piece)?;
    piece_file.as_file_mut().rewind()?;

    let mut staged_sector_file = NamedTempFile::new()?;
    add_piece(
        &mut piece_file,
        &mut staged_sector_file,
        number_of_bytes_in_piece,
        &[],
    )?;

    let piece_infos = vec![piece_info];

    let phase1_output = seal_pre_commit_phase1::<_, _, _, Tree>(
        config,
        cache_dir.path(),
        staged_sector_file.path(),
        sealed_sector_file.path(),
        prover_id,
        sector_id,
        ticket,
        &piece_infos,
    )?;

    validate_cache_for_precommit_phase2(
        cache_dir.path(),
        staged_sector_file.path(),
        &phase1_output,
    )?;

    Ok((piece_infos, phase1_output))
}

#[allow(clippy::too_many_arguments)]
fn generate_proof<Tree: 'static + MerkleTreeTrait>(
    config: &PoRepConfig,
    cache_dir_path: &Path,
    sealed_sector_file: &NamedTempFile,
    prover_id: ProverId,
    sector_id: SectorId,
    ticket: [u8; 32],
    seed: [u8; 32],
    pre_commit_output: &SealPreCommitOutput,
    piece_infos: &[PieceInfo],
    aggregation_enabled: bool,
) -> Result<(SealCommitOutput, Vec<Vec<Fr>>, [u8; 32], [u8; 32])> {
    info!("Generating Proof with features {:?}", config.api_features);
    if config.feature_enabled(ApiFeature::SyntheticPoRep) {
        info!("SyntheticPoRep is enabled");
        generate_synth_proofs::<_, Tree>(
            config,
            cache_dir_path,
            sealed_sector_file.path(),
            prover_id,
            sector_id,
            ticket,
            pre_commit_output.clone(),
            piece_infos,
        )?;
        clear_cache(cache_dir_path)?;
    } else {
        info!("SyntheticPoRep is NOT enabled");
        validate_cache_for_commit::<_, _, Tree>(cache_dir_path, sealed_sector_file.path())?;
    }

    let phase1_output = seal_commit_phase1::<_, Tree>(
        config,
        cache_dir_path,
        sealed_sector_file.path(),
        prover_id,
        sector_id,
        ticket,
        seed,
        pre_commit_output.clone(),
        piece_infos,
    )?;

    if config.feature_enabled(ApiFeature::SyntheticPoRep) {
        clear_synthetic_proofs(cache_dir_path)?;
    } else {
        clear_cache(cache_dir_path)?;
    }

    ensure!(
        seed == phase1_output.seed,
        "seed and phase1 output seed do not match"
    );
    ensure!(
        ticket == phase1_output.ticket,
        "seed and phase1 output ticket do not match"
    );

    let comm_r = phase1_output.comm_r;
    let inputs = get_seal_inputs::<Tree>(
        config,
        phase1_output.comm_r,
        phase1_output.comm_d,
        prover_id,
        sector_id,
        phase1_output.ticket,
        phase1_output.seed,
    )?;

    // This part of the test is demonstrating that if you want to use
    // NI-PoRep AND aggregate the NI-PoRep proofs, you MUST generate
    // the circuit proofs for each NI-PoRep proof, rather than the
    // full seal commit proof.  If you are NOT aggregating multiple
    // NI-PoRep proofs, you use the existing API as normal.
    //
    // The way the API is contructed, the generation is the ONLY
    // difference in this case, as the aggregation and verification
    // APIs remain the same.

    let result = if config.feature_enabled(ApiFeature::NonInteractivePoRep) && aggregation_enabled {
        info!("NonInteractivePoRep is enabled for aggregation");
        seal_commit_phase2_circuit_proofs(config, phase1_output, sector_id)?
    } else {
        // We don't need to do anything special for aggregating
        // InteractivePoRep seal proofs
        seal_commit_phase2(config, phase1_output, prover_id, sector_id)?
    };

    Ok((result, inputs, seed, comm_r))
}

#[allow(clippy::too_many_arguments)]
fn unseal<Tree: 'static + MerkleTreeTrait>(
    config: &PoRepConfig,
    cache_dir_path: &Path,
    sealed_sector_file: &NamedTempFile,
    prover_id: ProverId,
    sector_id: SectorId,
    ticket: [u8; 32],
    seed: [u8; 32],
    pre_commit_output: &SealPreCommitOutput,
    piece_infos: &[PieceInfo],
    piece_bytes: &[u8],
    commit_output: &SealCommitOutput,
) -> Result<()> {
    let comm_d = pre_commit_output.comm_d;
    let comm_r = pre_commit_output.comm_r;

    let mut unseal_file = NamedTempFile::new()?;
    let _ = unseal_range::<_, _, _, Tree>(
        config,
        cache_dir_path,
        sealed_sector_file,
        &unseal_file,
        prover_id,
        sector_id,
        comm_d,
        ticket,
        UnpaddedByteIndex(508),
        UnpaddedBytesAmount(508),
    )?;

    unseal_file.rewind()?;

    let mut contents = vec![];
    assert!(
        unseal_file.read_to_end(&mut contents).is_ok(),
        "failed to populate buffer with unsealed bytes"
    );
    assert_eq!(contents.len(), 508);
    assert_eq!(&piece_bytes[508..508 + 508], &contents[..]);

    let computed_comm_d = compute_comm_d(config.sector_size, piece_infos)?;

    assert_eq!(
        comm_d, computed_comm_d,
        "Computed and expected comm_d don't match."
    );

    let verified = verify_seal::<Tree>(
        config,
        comm_r,
        comm_d,
        prover_id,
        sector_id,
        ticket,
        seed,
        &commit_output.proof,
    )?;
    assert!(verified, "failed to verify valid seal");
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn proof_and_unseal<Tree: 'static + MerkleTreeTrait>(
    config: &PoRepConfig,
    cache_dir_path: &Path,
    sealed_sector_file: &NamedTempFile,
    prover_id: ProverId,
    sector_id: SectorId,
    ticket: [u8; 32],
    seed: [u8; 32],
    pre_commit_output: SealPreCommitOutput,
    piece_infos: &[PieceInfo],
    piece_bytes: &[u8],
) -> Result<()> {
    let aggregation_enabled = false;
    let (commit_output, _commit_inputs, _seed, _comm_r) = generate_proof::<Tree>(
        config,
        cache_dir_path,
        sealed_sector_file,
        prover_id,
        sector_id,
        ticket,
        seed,
        &pre_commit_output,
        piece_infos,
        aggregation_enabled,
    )?;

    // For regression suite only -- persist seal proof and everything required for the verify here
    #[cfg(feature = "persist-regression-proofs")]
    persist_generated_proof_for_regression_testing::<Tree>(
        config,
        prover_id,
        sector_id,
        ticket,
        seed,
        &pre_commit_output,
        &commit_output,
    )?;

    unseal::<Tree>(
        config,
        cache_dir_path,
        sealed_sector_file,
        prover_id,
        sector_id,
        ticket,
        seed,
        &pre_commit_output,
        piece_infos,
        piece_bytes,
        &commit_output,
    )
}

fn create_seal<R: Rng, Tree: 'static + MerkleTreeTrait>(
    porep_config: &PoRepConfig,
    rng: &mut R,
    prover_id: ProverId,
    skip_proof: bool,
) -> Result<(SectorId, NamedTempFile, Commitment, TempDir)> {
    fil_logger::maybe_init();

    let (mut piece_file, piece_bytes) = generate_piece_file(porep_config.sector_size.into())?;
    let sealed_sector_file = NamedTempFile::new()?;
    let cache_dir = tempdir().expect("failed to create temp dir");

    let ticket = rng.gen();
    let seed = rng.gen();
    let sector_id = rng.gen::<u64>().into();

    let (piece_infos, phase1_output) = run_seal_pre_commit_phase1::<Tree>(
        porep_config,
        prover_id,
        sector_id,
        ticket,
        &cache_dir,
        &mut piece_file,
        &sealed_sector_file,
    )?;

    let num_layers = phase1_output.labels.len();
    let pre_commit_output = seal_pre_commit_phase2(
        porep_config,
        phase1_output,
        cache_dir.path(),
        sealed_sector_file.path(),
    )?;

    // Check if creating only the tree_r_last generates the same output as the full pre commit
    // phase 2 process.
    let tree_r_last_dir = tempdir().expect("failed to create temp dir");
    generate_tree_r_last::<_, _, Tree>(
        porep_config.sector_size.into(),
        &sealed_sector_file,
        &tree_r_last_dir,
    )?;
    compare_trees::<Tree>(&tree_r_last_dir, &cache_dir, CacheKey::CommRLastTree)?;

    // Check if creating only the tree_c generates the same output as the full pre commit phase 2
    // process.
    let tree_c_dir = tempdir().expect("failed to create temp dir");
    generate_tree_c::<_, _, Tree>(
        porep_config.sector_size.into(),
        &cache_dir,
        &tree_c_dir,
        num_layers,
    )?;
    compare_trees::<Tree>(&tree_c_dir, &cache_dir, CacheKey::CommCTree)?;

    let comm_r = pre_commit_output.comm_r;

    if skip_proof {
        if porep_config.feature_enabled(ApiFeature::SyntheticPoRep) {
            clear_synthetic_proofs(cache_dir.path())?;
        }
        clear_cache(cache_dir.path())?;
    } else {
        proof_and_unseal::<Tree>(
            porep_config,
            cache_dir.path(),
            &sealed_sector_file,
            prover_id,
            sector_id,
            ticket,
            seed,
            pre_commit_output,
            &piece_infos,
            &piece_bytes,
        )
        .expect("failed to proof_and_unseal");
    }

    Ok((sector_id, sealed_sector_file, comm_r, cache_dir))
}

fn create_seal_for_aggregation<R: Rng, Tree: 'static + MerkleTreeTrait>(
    rng: &mut R,
    porep_config: &PoRepConfig,
    prover_id: ProverId,
) -> Result<(SealCommitOutput, Vec<Vec<Fr>>, [u8; 32], [u8; 32])> {
    fil_logger::maybe_init();

    let sector_size = porep_config.sector_size.into();
    let (mut piece_file, _piece_bytes) = generate_piece_file(sector_size)?;
    let sealed_sector_file = NamedTempFile::new()?;
    let cache_dir = tempfile::tempdir().expect("failed to create temp dir");

    let ticket = rng.gen();
    let seed = rng.gen();
    let sector_id = rng.gen::<u64>().into();

    let (piece_infos, phase1_output) = run_seal_pre_commit_phase1::<Tree>(
        porep_config,
        prover_id,
        sector_id,
        ticket,
        &cache_dir,
        &mut piece_file,
        &sealed_sector_file,
    )?;

    let pre_commit_output = seal_pre_commit_phase2(
        porep_config,
        phase1_output,
        cache_dir.path(),
        sealed_sector_file.path(),
    )?;

    validate_cache_for_commit::<_, _, Tree>(cache_dir.path(), sealed_sector_file.path())?;

    let aggregation_enabled = true;
    generate_proof::<Tree>(
        porep_config,
        cache_dir.path(),
        &sealed_sector_file,
        prover_id,
        sector_id,
        ticket,
        seed,
        &pre_commit_output,
        &piece_infos,
        aggregation_enabled,
    )
}

fn compare_elements(path1: &Path, path2: &Path) -> Result<(), Error> {
    info!("Comparing elements between {:?} and {:?}", path1, path2);
    let f_data1 = OpenOptions::new()
        .read(true)
        .open(path1)
        .with_context(|| format!("could not open path={:?}", path1))?;
    let data1 = unsafe {
        MmapOptions::new()
            .map(&f_data1)
            .with_context(|| format!("could not mmap path={:?}", path1))
    }?;
    let f_data2 = OpenOptions::new()
        .read(true)
        .open(path2)
        .with_context(|| format!("could not open path={:?}", path2))?;
    let data2 = unsafe {
        MmapOptions::new()
            .map(&f_data2)
            .with_context(|| format!("could not mmap path={:?}", path2))
    }?;
    let fr_size = std::mem::size_of::<Fr>();
    let end = metadata(path1)?.len();
    ensure!(metadata(path2)?.len() == end, "File sizes must match");

    for i in (0..end).step_by(fr_size) {
        let index = i as usize;
        let fr1 = bytes_into_fr(&data1[index..index + fr_size])?;
        let fr2 = bytes_into_fr(&data2[index..index + fr_size])?;
        ensure!(fr1 == fr2, "Data mismatch when comparing elements");
    }
    info!("Match found for {:?} and {:?}", path1, path2);

    Ok(())
}

/// Return the hash of a given file specified by cache key within a certain directory.
fn hash_file(dir: &TempDir, cache_key: &str) -> Result<Vec<u8>> {
    let path = StoreConfig::data_path(dir.path(), cache_key);
    let mut hasher = Sha256::new();
    let mut file = File::open(path)?;
    io::copy(&mut file, &mut hasher)?;
    Ok(hasher.finalize().to_vec())
}

/// Compare whether two trees are identical.
///
/// The tree may be split across several files.
fn compare_trees<Tree: 'static + MerkleTreeTrait>(
    dir_a: &TempDir,
    dir_b: &TempDir,
    cache_key: CacheKey,
) -> Result<()> {
    let base_tree_count = get_base_tree_count::<Tree>();
    let cache_key_names = if base_tree_count == 1 {
        vec![cache_key.to_string()]
    } else {
        (0..base_tree_count)
            .map(|count| format!("{}-{}", cache_key, count))
            .collect()
    };
    for cache_key_name in cache_key_names {
        let hash_a = hash_file(dir_a, &cache_key_name)?;
        let hash_b = hash_file(dir_b, &cache_key_name)?;
        assert_eq!(hash_a, hash_b, "files are identical");
    }
    Ok(())
}

/// Returns the decoded data.
///
/// The decoding is done in several arbitrarily sized parts.
fn decode_from_range_in_parts<R: Rng>(
    rng: &mut R,
    nodes_count: usize,
    comm_d: Commitment,
    comm_r: Commitment,
    mut input_file: &NamedTempFile,
    mut sector_key_file: &NamedTempFile,
    output_file: &mut NamedTempFile,
) -> Result<()> {
    const MAX_NUM_NODES: usize = 10;

    let mut offset = 0;
    while offset < nodes_count {
        // Select a number of nodes that is between 1 and 10.
        let num_nodes = if offset + MAX_NUM_NODES < nodes_count {
            rng.gen_range(1..=MAX_NUM_NODES)
        } else {
            nodes_count - offset
        };
        input_file
            .seek(SeekFrom::Start((offset * NODE_SIZE) as u64))
            .expect("failed to seek input");
        sector_key_file
            .seek(SeekFrom::Start((offset * NODE_SIZE) as u64))
            .expect("failed to seek sector key");
        decode_from_range(
            nodes_count,
            comm_d,
            comm_r,
            input_file,
            sector_key_file,
            output_file,
            offset,
            num_nodes,
        )?;
        offset += num_nodes
    }
    Ok(())
}

fn create_seal_for_upgrade<R: Rng, Tree: 'static + MerkleTreeTrait<Hasher = TreeRHasher>>(
    porep_config: &PoRepConfig,
    rng: &mut R,
    prover_id: ProverId,
) -> Result<(SectorId, NamedTempFile, Commitment, TempDir)> {
    fil_logger::maybe_init();

    let sector_size = porep_config.sector_size.into();
    let (mut piece_file, _piece_bytes) = generate_piece_file(sector_size)?;
    let sealed_sector_file = NamedTempFile::new()?;
    let cache_dir = tempdir().expect("failed to create temp dir");

    let config = SectorUpdateConfig::from_porep_config(porep_config);
    let ticket = rng.gen();
    let sector_id = rng.gen::<u64>().into();

    let (piece_infos, phase1_output) = run_seal_pre_commit_phase1::<Tree>(
        porep_config,
        prover_id,
        sector_id,
        ticket,
        &cache_dir,
        &mut piece_file,
        &sealed_sector_file,
    )?;

    let pre_commit_output = seal_pre_commit_phase2(
        porep_config,
        phase1_output,
        cache_dir.path(),
        sealed_sector_file.path(),
    )?;
    let comm_r = pre_commit_output.comm_r;

    if porep_config.feature_enabled(ApiFeature::SyntheticPoRep) {
        info!("SyntheticPoRep is enabled");
        generate_synth_proofs::<_, Tree>(
            porep_config,
            cache_dir.path(),
            sealed_sector_file.path(),
            prover_id,
            sector_id,
            ticket,
            pre_commit_output,
            &piece_infos,
        )?;
        clear_cache(cache_dir.path())?;
    } else {
        info!("SyntheticPoRep is NOT enabled");
        validate_cache_for_commit::<_, _, Tree>(cache_dir.path(), sealed_sector_file.path())?;
    }

    // Upgrade the cc sector here.
    let new_sealed_sector_file = NamedTempFile::new()?;
    let new_cache_dir = tempdir().expect("failed to create temp dir");

    // create and generate some random data in staged_data_file.
    let (mut new_piece_file, _new_piece_bytes) = generate_piece_file(sector_size)?;
    let number_of_bytes_in_piece = porep_config.unpadded_bytes_amount();

    let new_piece_info =
        generate_piece_commitment(new_piece_file.as_file_mut(), number_of_bytes_in_piece)?;
    new_piece_file.as_file_mut().rewind()?;

    let mut new_staged_sector_file = NamedTempFile::new()?;
    add_piece(
        &mut new_piece_file,
        &mut new_staged_sector_file,
        number_of_bytes_in_piece,
        &[],
    )?;

    let new_piece_infos = vec![new_piece_info];

    // New replica (new_sealed_sector_file) is currently 0 bytes --
    // set a length here to ensure proper mmap later.  Lotus will
    // already be passing in a destination path of the proper size in
    // the future, so this is a test specific work-around.
    let new_replica_target_len = metadata(&sealed_sector_file)?.len();
    let f_sealed_sector = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(new_sealed_sector_file.path())
        .with_context(|| format!("could not open path={:?}", new_sealed_sector_file.path()))?;
    f_sealed_sector.set_len(new_replica_target_len)?;

    let encoded = encode_into::<Tree>(
        &config,
        new_sealed_sector_file.path(),
        new_cache_dir.path(),
        sealed_sector_file.path(),
        cache_dir.path(),
        new_staged_sector_file.path(),
        &new_piece_infos,
    )?;

    // Generate a single partition proof
    let partition_proof = generate_single_partition_proof::<Tree>(
        config,
        0, // first partition
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
        sealed_sector_file.path(), /* sector key file */
        cache_dir.path(),          /* sector key path needed for p_aux and t_aux */
        new_sealed_sector_file.path(),
        new_cache_dir.path(),
    )?;

    // Verify the single partition proof
    let proof_is_valid = verify_single_partition_proof::<Tree>(
        config,
        0, // first partition
        partition_proof,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
    )?;
    ensure!(proof_is_valid, "Partition proof (single) failed to verify");

    // Generate all partition proofs
    let partition_proofs = generate_partition_proofs::<Tree>(
        config,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
        sealed_sector_file.path(), /* sector key file */
        cache_dir.path(),          /* sector key path needed for p_aux and t_aux */
        new_sealed_sector_file.path(),
        new_cache_dir.path(),
    )?;

    // Verify all partition proofs
    let proofs_are_valid = verify_partition_proofs::<Tree>(
        config,
        &partition_proofs,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
    )?;
    ensure!(proofs_are_valid, "Partition proofs failed to verify");

    let proof = generate_empty_sector_update_proof_with_vanilla::<Tree>(
        porep_config,
        partition_proofs,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
    )?;
    let valid = verify_empty_sector_update_proof::<Tree>(
        porep_config,
        &proof.0,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
    )?;
    ensure!(valid, "Compound proof failed to verify");

    let proof = generate_empty_sector_update_proof::<Tree>(
        porep_config,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
        sealed_sector_file.path(), /* sector key file */
        cache_dir.path(),          /* sector key path needed for p_aux and t_aux */
        new_sealed_sector_file.path(),
        new_cache_dir.path(),
    )?;
    let valid = verify_empty_sector_update_proof::<Tree>(
        porep_config,
        &proof.0,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
    )?;
    ensure!(valid, "Compound proof failed to verify");

    let decoded_sector_file = NamedTempFile::new()?;
    // New replica (new_sealed_sector_file) is currently 0 bytes --
    // set a length here to ensure proper mmap later.  Lotus will
    // already be passing in a destination path of the proper size in
    // the future, so this is a test specific work-around.
    let decoded_sector_target_len = metadata(&sealed_sector_file)?.len();
    let f_decoded_sector = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(decoded_sector_file.path())
        .with_context(|| format!("could not open path={:?}", decoded_sector_file.path()))?;
    f_decoded_sector.set_len(decoded_sector_target_len)?;

    decode_from::<Tree>(
        config,
        decoded_sector_file.path(),
        new_sealed_sector_file.path(),
        sealed_sector_file.path(),
        cache_dir.path(), /* sector key path needed for p_aux (for comm_c/comm_r_last) */
        encoded.comm_d_new,
    )?;
    // When the data is decoded, it MUST match the original new staged data.
    compare_elements(decoded_sector_file.path(), new_staged_sector_file.path())?;

    // Decode again, this time not the whole sector is a whole, but with random ranges.
    let mut decoded_sector_in_parts_file = NamedTempFile::new()?;
    decode_from_range_in_parts(
        rng,
        sector_size as usize / NODE_SIZE,
        encoded.comm_d_new,
        comm_r,
        &new_sealed_sector_file,
        &sealed_sector_file,
        &mut decoded_sector_in_parts_file,
    )?;
    compare_elements(
        decoded_sector_in_parts_file.path(),
        decoded_sector_file.path(),
    )?;

    decoded_sector_file.close()?;
    decoded_sector_in_parts_file.close()?;

    // Remove Data here
    let remove_encoded_file = NamedTempFile::new()?;
    let remove_encoded_cache_dir = tempdir().expect("failed to create temp dir");
    // New replica (new_sealed_sector_file) is currently 0 bytes --
    // set a length here to ensure proper mmap later.  Lotus will
    // already be passing in a destination path of the proper size in
    // the future, so this is a test specific work-around.
    let remove_encoded_target_len = metadata(&sealed_sector_file)?.len();
    let f_remove_encoded = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(remove_encoded_file.path())
        .with_context(|| format!("could not open path={:?}", remove_encoded_file.path()))?;
    f_remove_encoded.set_len(remove_encoded_target_len)?;

    // Note: we pass cache_dir to the remove, which is the original
    // dir where the data was sealed (for p_aux/t_aux).
    remove_encoded_data::<Tree>(
        config,
        remove_encoded_file.path(),
        remove_encoded_cache_dir.path(),
        new_sealed_sector_file.path(),
        cache_dir.path(),
        new_staged_sector_file.path(),
        encoded.comm_d_new,
    )?;
    // When the data is removed, it MUST match the original sealed data.
    compare_elements(remove_encoded_file.path(), sealed_sector_file.path())?;

    remove_encoded_file.close()?;

    if porep_config.feature_enabled(ApiFeature::SyntheticPoRep) {
        clear_synthetic_proofs(cache_dir.path())?;
    }
    clear_cache(cache_dir.path())?;
    clear_cache(new_cache_dir.path())?;

    Ok((sector_id, sealed_sector_file, comm_r, cache_dir))
}

fn create_seal_for_upgrade_aggregation<
    R: Rng,
    Tree: 'static + MerkleTreeTrait<Hasher = TreeRHasher>,
>(
    porep_config: &PoRepConfig,
    rng: &mut R,
    prover_id: ProverId,
) -> Result<(EmptySectorUpdateProof, SectorUpdateProofInputs)> {
    fil_logger::maybe_init();

    let sector_size = porep_config.sector_size.into();
    let (mut piece_file, _piece_bytes) = generate_piece_file(sector_size)?;
    let sealed_sector_file = NamedTempFile::new()?;
    let cache_dir = tempdir().expect("failed to create temp dir");

    let config = SectorUpdateConfig::from_porep_config(porep_config);
    let ticket = rng.gen();
    let sector_id = rng.gen::<u64>().into();

    let (piece_infos, phase1_output) = run_seal_pre_commit_phase1::<Tree>(
        porep_config,
        prover_id,
        sector_id,
        ticket,
        &cache_dir,
        &mut piece_file,
        &sealed_sector_file,
    )?;

    let pre_commit_output = seal_pre_commit_phase2(
        porep_config,
        phase1_output,
        cache_dir.path(),
        sealed_sector_file.path(),
    )?;
    let comm_r = pre_commit_output.comm_r;

    if porep_config.feature_enabled(ApiFeature::SyntheticPoRep) {
        info!("SyntheticPoRep is enabled");
        generate_synth_proofs::<_, Tree>(
            porep_config,
            cache_dir.path(),
            sealed_sector_file.path(),
            prover_id,
            sector_id,
            ticket,
            pre_commit_output,
            &piece_infos,
        )?;
        clear_cache(cache_dir.path())?;
    } else {
        info!("SyntheticPoRep is NOT enabled");
        validate_cache_for_commit::<_, _, Tree>(cache_dir.path(), sealed_sector_file.path())?;
    }

    // Upgrade the cc sector here.
    let new_sealed_sector_file = NamedTempFile::new()?;
    let new_cache_dir = tempdir().expect("failed to create temp dir");

    // create and generate some random data in staged_data_file.
    let (mut new_piece_file, _new_piece_bytes) = generate_piece_file(sector_size)?;
    let number_of_bytes_in_piece = porep_config.unpadded_bytes_amount();

    let new_piece_info =
        generate_piece_commitment(new_piece_file.as_file_mut(), number_of_bytes_in_piece)?;
    new_piece_file.as_file_mut().rewind()?;

    let mut new_staged_sector_file = NamedTempFile::new()?;
    add_piece(
        &mut new_piece_file,
        &mut new_staged_sector_file,
        number_of_bytes_in_piece,
        &[],
    )?;

    let new_piece_infos = vec![new_piece_info];

    // New replica (new_sealed_sector_file) is currently 0 bytes --
    // set a length here to ensure proper mmap later.  Lotus will
    // already be passing in a destination path of the proper size in
    // the future, so this is a test specific work-around.
    let new_replica_target_len = metadata(&sealed_sector_file)?.len();
    let f_sealed_sector = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(new_sealed_sector_file.path())
        .with_context(|| format!("could not open path={:?}", new_sealed_sector_file.path()))?;
    f_sealed_sector.set_len(new_replica_target_len)?;

    let encoded = encode_into::<Tree>(
        &config,
        new_sealed_sector_file.path(),
        new_cache_dir.path(),
        sealed_sector_file.path(),
        cache_dir.path(),
        new_staged_sector_file.path(),
        &new_piece_infos,
    )?;

    let proof = generate_empty_sector_update_proof::<Tree>(
        porep_config,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
        sealed_sector_file.path(), /* sector key file */
        cache_dir.path(),          /* sector key path needed for p_aux and t_aux */
        new_sealed_sector_file.path(),
        new_cache_dir.path(),
    )?;
    let valid = verify_empty_sector_update_proof::<Tree>(
        porep_config,
        &proof.0,
        comm_r,
        encoded.comm_r_new,
        encoded.comm_d_new,
    )?;
    ensure!(valid, "Empty Sector Update proof failed to verify");

    let proof_inputs = SectorUpdateProofInputs {
        h: get_sector_update_h_select_from_porep_config(porep_config),
        comm_r_old: comm_r,
        comm_r_new: encoded.comm_r_new,
        comm_d_new: encoded.comm_d_new,
    };

    Ok((proof, proof_inputs))
}

fn create_fake_seal<R: rand::Rng, Tree: 'static + MerkleTreeTrait>(
    mut rng: &mut R,
    sector_size: u64,
    porep_id: &[u8; 32],
    api_version: ApiVersion,
) -> Result<(SectorId, NamedTempFile, Commitment, TempDir)> {
    fil_logger::maybe_init();

    let sealed_sector_file = NamedTempFile::new()?;

    let config = porep_config(sector_size, *porep_id, api_version);

    let cache_dir = tempdir().unwrap();

    let sector_id = rng.gen::<u64>().into();

    let comm_r = fauxrep_aux::<_, _, _, Tree>(
        &mut rng,
        &config,
        cache_dir.path(),
        sealed_sector_file.path(),
    )?;

    Ok((sector_id, sealed_sector_file, comm_r, cache_dir))
}

#[test]
fn test_aggregate_proof_encode_decode() -> Result<()> {
    // This byte vector is a natively serialized aggregate proof generated from the
    // 'test_seal_proof_aggregation_257_2kib_porep_id_v1_1_base_8' test.
    let aggregate_proof_bytes = std::include_bytes!("./aggregate_proof_bytes");
    let expected_aggregate_proof_len = 29_044;

    // Re-construct the aggregate proof from the bytes, using the native deserialization method.
    let aggregate_proof: groth16::aggregate::AggregateProof<Bls12> =
        groth16::aggregate::AggregateProof::read(std::io::Cursor::new(&aggregate_proof_bytes))?;
    let aggregate_proof_count = aggregate_proof.tmipp.gipa.nproofs as usize;
    let expected_aggregate_proof_count = 512;

    assert_eq!(aggregate_proof_count, expected_aggregate_proof_count);

    // Re-serialize the proof to ensure a round-trip match.
    let mut aggregate_proof_bytes2 = Vec::new();
    aggregate_proof.write(&mut aggregate_proof_bytes2)?;

    assert_eq!(aggregate_proof_bytes.len(), expected_aggregate_proof_len);
    assert_eq!(aggregate_proof_bytes.len(), aggregate_proof_bytes2.len());
    assert_eq!(aggregate_proof_bytes, aggregate_proof_bytes2.as_slice());

    // Note: the native serialization format is more compact than bincode serialization, so assert that here.
    let bincode_serialized_proof = serialize(&aggregate_proof)?;
    let expected_bincode_serialized_proof_len = 56_436;

    assert!(aggregate_proof_bytes2.len() < bincode_serialized_proof.len());
    assert_eq!(
        bincode_serialized_proof.len(),
        expected_bincode_serialized_proof_len
    );

    Ok(())
}