subspace_farmer/
single_disk_farm.rs

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
//! Primary [`Farm`] implementation that deals with hardware directly
//!
//! Single disk farm is an abstraction that contains an identity, associated plot with metadata and
//! a small piece cache. It fully manages farming and plotting process, including listening to node
//! notifications, producing solutions and singing rewards.

pub mod direct_io_file;
pub mod farming;
pub mod identity;
mod metrics;
pub mod piece_cache;
pub mod piece_reader;
pub mod plot_cache;
mod plotted_sectors;
mod plotting;
mod reward_signing;

use crate::disk_piece_cache::{DiskPieceCache, DiskPieceCacheError};
use crate::farm::{
    Farm, FarmId, FarmingError, FarmingNotification, HandlerFn, PieceCacheId, PieceReader,
    PlottedSectors, SectorUpdate,
};
use crate::node_client::NodeClient;
use crate::plotter::Plotter;
use crate::single_disk_farm::direct_io_file::{DirectIoFile, DISK_SECTOR_SIZE};
use crate::single_disk_farm::farming::rayon_files::RayonFiles;
use crate::single_disk_farm::farming::{
    farming, slot_notification_forwarder, FarmingOptions, PlotAudit,
};
use crate::single_disk_farm::identity::{Identity, IdentityError};
use crate::single_disk_farm::metrics::SingleDiskFarmMetrics;
use crate::single_disk_farm::piece_cache::SingleDiskPieceCache;
use crate::single_disk_farm::piece_reader::DiskPieceReader;
use crate::single_disk_farm::plot_cache::DiskPlotCache;
use crate::single_disk_farm::plotted_sectors::SingleDiskPlottedSectors;
pub use crate::single_disk_farm::plotting::PlottingError;
use crate::single_disk_farm::plotting::{
    plotting, plotting_scheduler, PlottingOptions, PlottingSchedulerOptions, SectorPlottingOptions,
};
use crate::single_disk_farm::reward_signing::reward_signing;
use crate::utils::{tokio_rayon_spawn_handler, AsyncJoinOnDrop};
use crate::{farm, KNOWN_PEERS_CACHE_SIZE};
use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock};
use async_trait::async_trait;
use event_listener_primitives::{Bag, HandlerId};
use futures::channel::{mpsc, oneshot};
use futures::stream::FuturesUnordered;
use futures::{select, FutureExt, StreamExt};
use parity_scale_codec::{Decode, Encode};
use parking_lot::Mutex;
use prometheus_client::registry::Registry;
use rand::prelude::*;
use rayon::prelude::*;
use rayon::{ThreadPoolBuildError, ThreadPoolBuilder};
use serde::{Deserialize, Serialize};
use static_assertions::const_assert;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::future::Future;
use std::io::Write;
use std::num::{NonZeroU32, NonZeroUsize};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::{fmt, fs, io, mem};
use subspace_core_primitives::hashes::{blake3_hash, Blake3Hash};
use subspace_core_primitives::pieces::Record;
use subspace_core_primitives::sectors::SectorIndex;
use subspace_core_primitives::segments::{HistorySize, SegmentIndex};
use subspace_core_primitives::{PublicKey, ScalarBytes};
use subspace_erasure_coding::ErasureCoding;
use subspace_farmer_components::file_ext::FileExt;
use subspace_farmer_components::reading::ReadSectorRecordChunksMode;
use subspace_farmer_components::sector::{sector_size, SectorMetadata, SectorMetadataChecksummed};
use subspace_farmer_components::{FarmerProtocolInfo, ReadAtSync};
use subspace_kzg::Kzg;
use subspace_networking::KnownPeersManager;
use subspace_proof_of_space::Table;
use subspace_rpc_primitives::{FarmerAppInfo, SolutionResponse};
use thiserror::Error;
use tokio::runtime::Handle;
use tokio::sync::{broadcast, Barrier, Semaphore};
use tokio::task;
use tracing::{debug, error, info, trace, warn, Instrument, Span};

// Refuse to compile on non-64-bit platforms, offsets may fail on those when converting from u64 to
// usize depending on chain parameters
const_assert!(mem::size_of::<usize>() >= mem::size_of::<u64>());

/// Reserve 1M of space for plot metadata (for potential future expansion)
const RESERVED_PLOT_METADATA: u64 = 1024 * 1024;
/// Reserve 1M of space for farm info (for potential future expansion)
const RESERVED_FARM_INFO: u64 = 1024 * 1024;
const NEW_SEGMENT_PROCESSING_DELAY: Duration = Duration::from_secs(30);
/// Limit for reads in internal benchmark.
///
/// 4 seconds is proving time, hence 3 seconds for reads.
const INTERNAL_BENCHMARK_READ_TIMEOUT: Duration = Duration::from_millis(3500);

/// Exclusive lock for single disk farm info file, ensuring no concurrent edits by cooperating processes is done
#[derive(Debug)]
#[must_use = "Lock file must be kept around or as long as farm is used"]
pub struct SingleDiskFarmInfoLock {
    _file: File,
}

/// Important information about the contents of the `SingleDiskFarm`
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SingleDiskFarmInfo {
    /// V0 of the info
    #[serde(rename_all = "camelCase")]
    V0 {
        /// ID of the farm
        id: FarmId,
        /// Genesis hash of the chain used for farm creation
        #[serde(with = "hex")]
        genesis_hash: [u8; 32],
        /// Public key of identity used for farm creation
        public_key: PublicKey,
        /// How many pieces does one sector contain.
        pieces_in_sector: u16,
        /// How much space in bytes is allocated for this farm
        allocated_space: u64,
    },
}

impl SingleDiskFarmInfo {
    const FILE_NAME: &'static str = "single_disk_farm.json";

    /// Create new instance
    pub fn new(
        id: FarmId,
        genesis_hash: [u8; 32],
        public_key: PublicKey,
        pieces_in_sector: u16,
        allocated_space: u64,
    ) -> Self {
        Self::V0 {
            id,
            genesis_hash,
            public_key,
            pieces_in_sector,
            allocated_space,
        }
    }

    /// Load `SingleDiskFarm` from path is supposed to be stored, `None` means no info file was
    /// found, happens during first start.
    pub fn load_from(directory: &Path) -> io::Result<Option<Self>> {
        let bytes = match fs::read(directory.join(Self::FILE_NAME)) {
            Ok(bytes) => bytes,
            Err(error) => {
                return if error.kind() == io::ErrorKind::NotFound {
                    Ok(None)
                } else {
                    Err(error)
                };
            }
        };

        serde_json::from_slice(&bytes)
            .map(Some)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
    }

    /// Store `SingleDiskFarm` info to path, so it can be loaded again upon restart.
    ///
    /// Can optionally return a lock.
    pub fn store_to(
        &self,
        directory: &Path,
        lock: bool,
    ) -> io::Result<Option<SingleDiskFarmInfoLock>> {
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .open(directory.join(Self::FILE_NAME))?;
        if lock {
            fs4::fs_std::FileExt::try_lock_exclusive(&file)?;
        }
        file.set_len(0)?;
        file.write_all(&serde_json::to_vec(self).expect("Info serialization never fails; qed"))?;

        Ok(lock.then_some(SingleDiskFarmInfoLock { _file: file }))
    }

    /// Try to acquire exclusive lock on the single disk farm info file, ensuring no concurrent edits by cooperating
    /// processes is done
    pub fn try_lock(directory: &Path) -> io::Result<SingleDiskFarmInfoLock> {
        let file = File::open(directory.join(Self::FILE_NAME))?;
        fs4::fs_std::FileExt::try_lock_exclusive(&file)?;

        Ok(SingleDiskFarmInfoLock { _file: file })
    }

    /// ID of the farm
    pub fn id(&self) -> &FarmId {
        let Self::V0 { id, .. } = self;
        id
    }

    /// Genesis hash of the chain used for farm creation
    pub fn genesis_hash(&self) -> &[u8; 32] {
        let Self::V0 { genesis_hash, .. } = self;
        genesis_hash
    }

    /// Public key of identity used for farm creation
    pub fn public_key(&self) -> &PublicKey {
        let Self::V0 { public_key, .. } = self;
        public_key
    }

    /// How many pieces does one sector contain.
    pub fn pieces_in_sector(&self) -> u16 {
        match self {
            SingleDiskFarmInfo::V0 {
                pieces_in_sector, ..
            } => *pieces_in_sector,
        }
    }

    /// How much space in bytes is allocated for this farm
    pub fn allocated_space(&self) -> u64 {
        match self {
            SingleDiskFarmInfo::V0 {
                allocated_space, ..
            } => *allocated_space,
        }
    }
}

/// Summary of single disk farm for presentational purposes
#[derive(Debug)]
pub enum SingleDiskFarmSummary {
    /// Farm was found and read successfully
    Found {
        /// Farm info
        info: SingleDiskFarmInfo,
        /// Path to directory where farm is stored.
        directory: PathBuf,
    },
    /// Farm was not found
    NotFound {
        /// Path to directory where farm is stored.
        directory: PathBuf,
    },
    /// Failed to open farm
    Error {
        /// Path to directory where farm is stored.
        directory: PathBuf,
        /// Error itself
        error: io::Error,
    },
}

#[derive(Debug, Encode, Decode)]
struct PlotMetadataHeader {
    version: u8,
    plotted_sector_count: SectorIndex,
}

impl PlotMetadataHeader {
    #[inline]
    fn encoded_size() -> usize {
        let default = PlotMetadataHeader {
            version: 0,
            plotted_sector_count: 0,
        };

        default.encoded_size()
    }
}

/// Options used to open single disk farm
#[derive(Debug)]
pub struct SingleDiskFarmOptions<'a, NC>
where
    NC: Clone,
{
    /// Path to directory where farm is stored.
    pub directory: PathBuf,
    /// Information necessary for farmer application
    pub farmer_app_info: FarmerAppInfo,
    /// How much space in bytes was allocated
    pub allocated_space: u64,
    /// How many pieces one sector is supposed to contain (max)
    pub max_pieces_in_sector: u16,
    /// RPC client connected to Subspace node
    pub node_client: NC,
    /// Address where farming rewards should go
    pub reward_address: PublicKey,
    /// Plotter
    pub plotter: Arc<dyn Plotter + Send + Sync>,
    /// Kzg instance to use.
    pub kzg: Kzg,
    /// Erasure coding instance to use.
    pub erasure_coding: ErasureCoding,
    /// Percentage of allocated space dedicated for caching purposes
    pub cache_percentage: u8,
    /// Thread pool size used for farming (mostly for blocking I/O, but also for some
    /// compute-intensive operations during proving)
    pub farming_thread_pool_size: usize,
    /// Notification for plotter to start, can be used to delay plotting until some initialization
    /// has happened externally
    pub plotting_delay: Option<oneshot::Receiver<()>>,
    /// Global mutex that can restrict concurrency of resource-intensive operations and make sure
    /// that those operations that are very sensitive (like proving) have all the resources
    /// available to them for the highest probability of success
    pub global_mutex: Arc<AsyncMutex<()>>,
    /// How many sectors a will be plotted concurrently per farm
    pub max_plotting_sectors_per_farm: NonZeroUsize,
    /// Disable farm locking, for example if file system doesn't support it
    pub disable_farm_locking: bool,
    /// Explicit mode to use for reading of sector record chunks instead of doing internal
    /// benchmarking
    pub read_sector_record_chunks_mode: Option<ReadSectorRecordChunksMode>,
    /// Barrier before internal benchmarking between different farms
    pub faster_read_sector_record_chunks_mode_barrier: Arc<Barrier>,
    /// Limit concurrency of internal benchmarking between different farms
    pub faster_read_sector_record_chunks_mode_concurrency: Arc<Semaphore>,
    /// Prometheus registry
    pub registry: Option<&'a Mutex<&'a mut Registry>>,
    /// Whether to create a farm if it doesn't yet exist
    pub create: bool,
}

/// Errors happening when trying to create/open single disk farm
#[derive(Debug, Error)]
pub enum SingleDiskFarmError {
    /// Failed to open or create identity
    #[error("Failed to open or create identity: {0}")]
    FailedToOpenIdentity(#[from] IdentityError),
    /// Farm is likely already in use, make sure no other farmer is using it
    #[error("Farm is likely already in use, make sure no other farmer is using it: {0}")]
    LikelyAlreadyInUse(io::Error),
    /// I/O error occurred
    #[error("Single disk farm I/O error: {0}")]
    Io(#[from] io::Error),
    /// Failed to spawn task for blocking thread
    #[error("Failed to spawn task for blocking thread: {0}")]
    TokioJoinError(#[from] task::JoinError),
    /// Piece cache error
    #[error("Piece cache error: {0}")]
    PieceCacheError(#[from] DiskPieceCacheError),
    /// Can't preallocate metadata file, probably not enough space on disk
    #[error("Can't preallocate metadata file, probably not enough space on disk: {0}")]
    CantPreallocateMetadataFile(io::Error),
    /// Can't preallocate plot file, probably not enough space on disk
    #[error("Can't preallocate plot file, probably not enough space on disk: {0}")]
    CantPreallocatePlotFile(io::Error),
    /// Wrong chain (genesis hash)
    #[error(
        "Genesis hash of farm {id} {wrong_chain} is different from {correct_chain} when farm was \
        created, it is not possible to use farm on a different chain"
    )]
    WrongChain {
        /// Farm ID
        id: FarmId,
        /// Hex-encoded genesis hash during farm creation
        // TODO: Wrapper type with `Display` impl for genesis hash
        correct_chain: String,
        /// Hex-encoded current genesis hash
        wrong_chain: String,
    },
    /// Public key in identity doesn't match metadata
    #[error(
        "Public key of farm {id} {wrong_public_key} is different from {correct_public_key} when \
        farm was created, something went wrong, likely due to manual edits"
    )]
    IdentityMismatch {
        /// Farm ID
        id: FarmId,
        /// Public key used during farm creation
        correct_public_key: PublicKey,
        /// Current public key
        wrong_public_key: PublicKey,
    },
    /// Invalid number pieces in sector
    #[error(
        "Invalid number pieces in sector: max supported {max_supported}, farm initialized with \
        {initialized_with}"
    )]
    InvalidPiecesInSector {
        /// Farm ID
        id: FarmId,
        /// Max supported pieces in sector
        max_supported: u16,
        /// Number of pieces in sector farm is initialized with
        initialized_with: u16,
    },
    /// Failed to decode metadata header
    #[error("Failed to decode metadata header: {0}")]
    FailedToDecodeMetadataHeader(parity_scale_codec::Error),
    /// Unexpected metadata version
    #[error("Unexpected metadata version {0}")]
    UnexpectedMetadataVersion(u8),
    /// Allocated space is not enough for one sector
    #[error(
        "Allocated space is not enough for one sector. \
        The lowest acceptable value for allocated space is {min_space} bytes, \
        provided {allocated_space} bytes."
    )]
    InsufficientAllocatedSpace {
        /// Minimal allocated space
        min_space: u64,
        /// Current allocated space
        allocated_space: u64,
    },
    /// Farm is too large
    #[error(
        "Farm is too large: allocated {allocated_sectors} sectors ({allocated_space} bytes), max \
        supported is {max_sectors} ({max_space} bytes). Consider creating multiple smaller farms \
        instead."
    )]
    FarmTooLarge {
        /// Allocated space
        allocated_space: u64,
        /// Allocated space in sectors
        allocated_sectors: u64,
        /// Max supported allocated space
        max_space: u64,
        /// Max supported allocated space in sectors
        max_sectors: u16,
    },
    /// Failed to create thread pool
    #[error("Failed to create thread pool: {0}")]
    FailedToCreateThreadPool(ThreadPoolBuildError),
}

/// Errors happening during scrubbing
#[derive(Debug, Error)]
pub enum SingleDiskFarmScrubError {
    /// Farm is likely already in use, make sure no other farmer is using it
    #[error("Farm is likely already in use, make sure no other farmer is using it: {0}")]
    LikelyAlreadyInUse(io::Error),
    /// Failed to determine file size
    #[error("Failed to file size of {file}: {error}")]
    FailedToDetermineFileSize {
        /// Affected file
        file: PathBuf,
        /// Low-level error
        error: io::Error,
    },
    /// Failed to read bytes from file
    #[error("Failed to read {size} bytes from {file} at offset {offset}: {error}")]
    FailedToReadBytes {
        /// Affected file
        file: PathBuf,
        /// Number of bytes to read
        size: u64,
        /// Offset in the file
        offset: u64,
        /// Low-level error
        error: io::Error,
    },
    /// Failed to write bytes from file
    #[error("Failed to write {size} bytes from {file} at offset {offset}: {error}")]
    FailedToWriteBytes {
        /// Affected file
        file: PathBuf,
        /// Number of bytes to read
        size: u64,
        /// Offset in the file
        offset: u64,
        /// Low-level error
        error: io::Error,
    },
    /// Farm info file does not exist
    #[error("Farm info file does not exist at {file}")]
    FarmInfoFileDoesNotExist {
        /// Info file
        file: PathBuf,
    },
    /// Farm info can't be opened
    #[error("Farm info at {file} can't be opened: {error}")]
    FarmInfoCantBeOpened {
        /// Info file
        file: PathBuf,
        /// Low-level error
        error: io::Error,
    },
    /// Identity file does not exist
    #[error("Identity file does not exist at {file}")]
    IdentityFileDoesNotExist {
        /// Identity file
        file: PathBuf,
    },
    /// Identity can't be opened
    #[error("Identity at {file} can't be opened: {error}")]
    IdentityCantBeOpened {
        /// Identity file
        file: PathBuf,
        /// Low-level error
        error: IdentityError,
    },
    /// Identity public key doesn't match public key in the disk farm info
    #[error(
        "Identity public key {identity} doesn't match public key in the disk farm info {info}"
    )]
    PublicKeyMismatch {
        /// Identity public key
        identity: PublicKey,
        /// Disk farm info public key
        info: PublicKey,
    },
    /// Metadata file does not exist
    #[error("Metadata file does not exist at {file}")]
    MetadataFileDoesNotExist {
        /// Metadata file
        file: PathBuf,
    },
    /// Metadata can't be opened
    #[error("Metadata at {file} can't be opened: {error}")]
    MetadataCantBeOpened {
        /// Metadata file
        file: PathBuf,
        /// Low-level error
        error: io::Error,
    },
    /// Metadata file too small
    #[error(
        "Metadata file at {file} is too small: reserved size is {reserved_size} bytes, file size \
        is {size}"
    )]
    MetadataFileTooSmall {
        /// Metadata file
        file: PathBuf,
        /// Reserved size
        reserved_size: u64,
        /// File size
        size: u64,
    },
    /// Failed to decode metadata header
    #[error("Failed to decode metadata header: {0}")]
    FailedToDecodeMetadataHeader(parity_scale_codec::Error),
    /// Unexpected metadata version
    #[error("Unexpected metadata version {0}")]
    UnexpectedMetadataVersion(u8),
    /// Cache can't be opened
    #[error("Cache at {file} can't be opened: {error}")]
    CacheCantBeOpened {
        /// Cache file
        file: PathBuf,
        /// Low-level error
        error: io::Error,
    },
}

/// Errors that happen in background tasks
#[derive(Debug, Error)]
pub enum BackgroundTaskError {
    /// Plotting error
    #[error(transparent)]
    Plotting(#[from] PlottingError),
    /// Farming error
    #[error(transparent)]
    Farming(#[from] FarmingError),
    /// Reward signing
    #[error(transparent)]
    RewardSigning(#[from] anyhow::Error),
    /// Background task panicked
    #[error("Background task {task} panicked")]
    BackgroundTaskPanicked {
        /// Name of the task
        task: String,
    },
}

type BackgroundTask = Pin<Box<dyn Future<Output = Result<(), BackgroundTaskError>> + Send>>;

/// Scrub target
#[derive(Debug, Copy, Clone)]
pub enum ScrubTarget {
    /// Scrub everything
    All,
    /// Scrub just metadata
    Metadata,
    /// Scrub metadata and corresponding plot
    Plot,
    /// Only scrub cache
    Cache,
}

impl fmt::Display for ScrubTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::All => f.write_str("all"),
            Self::Metadata => f.write_str("metadata"),
            Self::Plot => f.write_str("plot"),
            Self::Cache => f.write_str("cache"),
        }
    }
}

impl FromStr for ScrubTarget {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "all" => Ok(Self::All),
            "metadata" => Ok(Self::Metadata),
            "plot" => Ok(Self::Plot),
            "cache" => Ok(Self::Cache),
            s => Err(format!("Can't parse {s} as `ScrubTarget`")),
        }
    }
}

impl ScrubTarget {
    fn metadata(&self) -> bool {
        match self {
            Self::All | Self::Metadata | Self::Plot => true,
            Self::Cache => false,
        }
    }

    fn plot(&self) -> bool {
        match self {
            Self::All | Self::Plot => true,
            Self::Metadata | Self::Cache => false,
        }
    }

    fn cache(&self) -> bool {
        match self {
            Self::All | Self::Cache => true,
            Self::Metadata | Self::Plot => false,
        }
    }
}

struct AllocatedSpaceDistribution {
    piece_cache_file_size: u64,
    piece_cache_capacity: u32,
    plot_file_size: u64,
    target_sector_count: u16,
    metadata_file_size: u64,
}

impl AllocatedSpaceDistribution {
    fn new(
        allocated_space: u64,
        sector_size: u64,
        cache_percentage: u8,
        sector_metadata_size: u64,
    ) -> Result<Self, SingleDiskFarmError> {
        let single_sector_overhead = sector_size + sector_metadata_size;
        // Fixed space usage regardless of plot size
        let fixed_space_usage = RESERVED_PLOT_METADATA
            + RESERVED_FARM_INFO
            + Identity::file_size() as u64
            + KnownPeersManager::file_size(KNOWN_PEERS_CACHE_SIZE) as u64;
        // Calculate how many sectors can fit
        let target_sector_count = {
            let potentially_plottable_space = allocated_space.saturating_sub(fixed_space_usage)
                / 100
                * (100 - u64::from(cache_percentage));
            // Do the rounding to make sure we have exactly as much space as fits whole number of
            // sectors, account for disk sector size just in case
            (potentially_plottable_space - DISK_SECTOR_SIZE as u64) / single_sector_overhead
        };

        if target_sector_count == 0 {
            let mut single_plot_with_cache_space =
                single_sector_overhead.div_ceil(100 - u64::from(cache_percentage)) * 100;
            // Cache must not be empty, ensure it contains at least one element even if
            // percentage-wise it will use more space
            if single_plot_with_cache_space - single_sector_overhead
                < DiskPieceCache::element_size() as u64
            {
                single_plot_with_cache_space =
                    single_sector_overhead + DiskPieceCache::element_size() as u64;
            }

            return Err(SingleDiskFarmError::InsufficientAllocatedSpace {
                min_space: fixed_space_usage + single_plot_with_cache_space,
                allocated_space,
            });
        }
        let plot_file_size = target_sector_count * sector_size;
        // Align plot file size for disk sector size
        let plot_file_size =
            plot_file_size.div_ceil(DISK_SECTOR_SIZE as u64) * DISK_SECTOR_SIZE as u64;

        // Remaining space will be used for caching purposes
        let piece_cache_capacity = if cache_percentage > 0 {
            let cache_space = allocated_space
                - fixed_space_usage
                - plot_file_size
                - (sector_metadata_size * target_sector_count);
            (cache_space / u64::from(DiskPieceCache::element_size())) as u32
        } else {
            0
        };
        let target_sector_count = match SectorIndex::try_from(target_sector_count) {
            Ok(target_sector_count) if target_sector_count < SectorIndex::MAX => {
                target_sector_count
            }
            _ => {
                // We use this for both count and index, hence index must not reach actual `MAX`
                // (consensus doesn't care about this, just farmer implementation detail)
                let max_sectors = SectorIndex::MAX - 1;
                return Err(SingleDiskFarmError::FarmTooLarge {
                    allocated_space: target_sector_count * sector_size,
                    allocated_sectors: target_sector_count,
                    max_space: max_sectors as u64 * sector_size,
                    max_sectors,
                });
            }
        };

        Ok(Self {
            piece_cache_file_size: u64::from(piece_cache_capacity)
                * u64::from(DiskPieceCache::element_size()),
            piece_cache_capacity,
            plot_file_size,
            target_sector_count,
            metadata_file_size: RESERVED_PLOT_METADATA
                + sector_metadata_size * u64::from(target_sector_count),
        })
    }
}

type Handler<A> = Bag<HandlerFn<A>, A>;

#[derive(Default, Debug)]
struct Handlers {
    sector_update: Handler<(SectorIndex, SectorUpdate)>,
    farming_notification: Handler<FarmingNotification>,
    solution: Handler<SolutionResponse>,
}

struct SingleDiskFarmInit {
    identity: Identity,
    single_disk_farm_info: SingleDiskFarmInfo,
    single_disk_farm_info_lock: Option<SingleDiskFarmInfoLock>,
    plot_file: Arc<DirectIoFile>,
    metadata_file: DirectIoFile,
    metadata_header: PlotMetadataHeader,
    target_sector_count: u16,
    sectors_metadata: Arc<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
    piece_cache_capacity: u32,
    plot_cache: DiskPlotCache,
}

/// Single disk farm abstraction is a container for everything necessary to plot/farm with a single
/// disk.
///
/// Farm starts operating during creation and doesn't stop until dropped (or error happens).
#[derive(Debug)]
#[must_use = "Plot does not function properly unless run() method is called"]
pub struct SingleDiskFarm {
    farmer_protocol_info: FarmerProtocolInfo,
    single_disk_farm_info: SingleDiskFarmInfo,
    /// Metadata of all sectors plotted so far
    sectors_metadata: Arc<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
    pieces_in_sector: u16,
    total_sectors_count: SectorIndex,
    span: Span,
    tasks: FuturesUnordered<BackgroundTask>,
    handlers: Arc<Handlers>,
    piece_cache: SingleDiskPieceCache,
    plot_cache: DiskPlotCache,
    piece_reader: DiskPieceReader,
    /// Sender that will be used to signal to background threads that they should start
    start_sender: Option<broadcast::Sender<()>>,
    /// Sender that will be used to signal to background threads that they must stop
    stop_sender: Option<broadcast::Sender<()>>,
    _single_disk_farm_info_lock: Option<SingleDiskFarmInfoLock>,
}

impl Drop for SingleDiskFarm {
    #[inline]
    fn drop(&mut self) {
        self.piece_reader.close_all_readers();
        // Make background threads that are waiting to do something exit immediately
        self.start_sender.take();
        // Notify background tasks that they must stop
        self.stop_sender.take();
    }
}

#[async_trait(?Send)]
impl Farm for SingleDiskFarm {
    fn id(&self) -> &FarmId {
        self.id()
    }

    fn total_sectors_count(&self) -> SectorIndex {
        self.total_sectors_count
    }

    fn plotted_sectors(&self) -> Arc<dyn PlottedSectors + 'static> {
        Arc::new(self.plotted_sectors())
    }

    fn piece_reader(&self) -> Arc<dyn PieceReader + 'static> {
        Arc::new(self.piece_reader())
    }

    fn on_sector_update(
        &self,
        callback: HandlerFn<(SectorIndex, SectorUpdate)>,
    ) -> Box<dyn farm::HandlerId> {
        Box::new(self.on_sector_update(callback))
    }

    fn on_farming_notification(
        &self,
        callback: HandlerFn<FarmingNotification>,
    ) -> Box<dyn farm::HandlerId> {
        Box::new(self.on_farming_notification(callback))
    }

    fn on_solution(&self, callback: HandlerFn<SolutionResponse>) -> Box<dyn farm::HandlerId> {
        Box::new(self.on_solution(callback))
    }

    fn run(self: Box<Self>) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {
        Box::pin((*self).run())
    }
}

impl SingleDiskFarm {
    /// Name of the plot file
    pub const PLOT_FILE: &'static str = "plot.bin";
    /// Name of the metadata file
    pub const METADATA_FILE: &'static str = "metadata.bin";
    const SUPPORTED_PLOT_VERSION: u8 = 0;

    /// Create new single disk farm instance
    pub async fn new<NC, PosTable>(
        options: SingleDiskFarmOptions<'_, NC>,
        farm_index: usize,
    ) -> Result<Self, SingleDiskFarmError>
    where
        NC: NodeClient + Clone,
        PosTable: Table,
    {
        let span = Span::current();

        let SingleDiskFarmOptions {
            directory,
            farmer_app_info,
            allocated_space,
            max_pieces_in_sector,
            node_client,
            reward_address,
            plotter,
            kzg,
            erasure_coding,
            cache_percentage,
            farming_thread_pool_size,
            plotting_delay,
            global_mutex,
            max_plotting_sectors_per_farm,
            disable_farm_locking,
            read_sector_record_chunks_mode,
            faster_read_sector_record_chunks_mode_barrier,
            faster_read_sector_record_chunks_mode_concurrency,
            registry,
            create,
        } = options;

        let single_disk_farm_init_fut = task::spawn_blocking({
            let directory = directory.clone();
            let farmer_app_info = farmer_app_info.clone();
            let span = span.clone();

            move || {
                let _span_guard = span.enter();
                Self::init(
                    &directory,
                    &farmer_app_info,
                    allocated_space,
                    max_pieces_in_sector,
                    cache_percentage,
                    disable_farm_locking,
                    create,
                )
            }
        });

        let single_disk_farm_init =
            AsyncJoinOnDrop::new(single_disk_farm_init_fut, false).await??;

        let SingleDiskFarmInit {
            identity,
            single_disk_farm_info,
            single_disk_farm_info_lock,
            plot_file,
            metadata_file,
            metadata_header,
            target_sector_count,
            sectors_metadata,
            piece_cache_capacity,
            plot_cache,
        } = single_disk_farm_init;

        let piece_cache = {
            // Convert farm ID into cache ID for single disk farm
            let FarmId::Ulid(id) = *single_disk_farm_info.id();
            let id = PieceCacheId::Ulid(id);

            SingleDiskPieceCache::new(
                id,
                if let Some(piece_cache_capacity) = NonZeroU32::new(piece_cache_capacity) {
                    Some(task::block_in_place(|| {
                        if let Some(registry) = registry {
                            DiskPieceCache::open(
                                &directory,
                                piece_cache_capacity,
                                Some(id),
                                Some(*registry.lock()),
                            )
                        } else {
                            DiskPieceCache::open(&directory, piece_cache_capacity, Some(id), None)
                        }
                    })?)
                } else {
                    None
                },
            )
        };

        let public_key = *single_disk_farm_info.public_key();
        let pieces_in_sector = single_disk_farm_info.pieces_in_sector();
        let sector_size = sector_size(pieces_in_sector);

        let metrics = registry.map(|registry| {
            Arc::new(SingleDiskFarmMetrics::new(
                *registry.lock(),
                single_disk_farm_info.id(),
                target_sector_count,
                sectors_metadata.read_blocking().len() as SectorIndex,
            ))
        });

        let (error_sender, error_receiver) = oneshot::channel();
        let error_sender = Arc::new(Mutex::new(Some(error_sender)));

        let tasks = FuturesUnordered::<BackgroundTask>::new();

        tasks.push(Box::pin(async move {
            if let Ok(error) = error_receiver.await {
                return Err(error);
            }

            Ok(())
        }));

        let handlers = Arc::<Handlers>::default();
        let (start_sender, mut start_receiver) = broadcast::channel::<()>(1);
        let (stop_sender, mut stop_receiver) = broadcast::channel::<()>(1);
        let sectors_being_modified = Arc::<AsyncRwLock<HashSet<SectorIndex>>>::default();
        let (sectors_to_plot_sender, sectors_to_plot_receiver) = mpsc::channel(1);
        // Some sectors may already be plotted, skip them
        let sectors_indices_left_to_plot =
            metadata_header.plotted_sector_count..target_sector_count;

        let farming_thread_pool = ThreadPoolBuilder::new()
            .thread_name(move |thread_index| format!("farming-{farm_index}.{thread_index}"))
            .num_threads(farming_thread_pool_size)
            .spawn_handler(tokio_rayon_spawn_handler())
            .build()
            .map_err(SingleDiskFarmError::FailedToCreateThreadPool)?;
        let farming_plot_fut = task::spawn_blocking(|| {
            farming_thread_pool
                .install(move || {
                    RayonFiles::open_with(directory.join(Self::PLOT_FILE), |path| {
                        DirectIoFile::open(path)
                    })
                })
                .map(|farming_plot| (farming_plot, farming_thread_pool))
        });

        let (farming_plot, farming_thread_pool) =
            AsyncJoinOnDrop::new(farming_plot_fut, false).await??;

        faster_read_sector_record_chunks_mode_barrier.wait().await;

        let (read_sector_record_chunks_mode, farming_plot, farming_thread_pool) =
            if let Some(mode) = read_sector_record_chunks_mode {
                (mode, farming_plot, farming_thread_pool)
            } else {
                // Error doesn't matter here
                let _permit = faster_read_sector_record_chunks_mode_concurrency
                    .acquire()
                    .await;
                let span = span.clone();
                let plot_file = Arc::clone(&plot_file);

                let read_sector_record_chunks_mode_fut = task::spawn_blocking(move || {
                    farming_thread_pool
                        .install(move || {
                            let _span_guard = span.enter();

                            faster_read_sector_record_chunks_mode(
                                &*plot_file,
                                &farming_plot,
                                sector_size,
                                metadata_header.plotted_sector_count,
                            )
                            .map(|mode| (mode, farming_plot))
                        })
                        .map(|(mode, farming_plot)| (mode, farming_plot, farming_thread_pool))
                });

                AsyncJoinOnDrop::new(read_sector_record_chunks_mode_fut, false).await??
            };

        faster_read_sector_record_chunks_mode_barrier.wait().await;

        let plotting_join_handle = task::spawn_blocking({
            let sectors_metadata = Arc::clone(&sectors_metadata);
            let handlers = Arc::clone(&handlers);
            let sectors_being_modified = Arc::clone(&sectors_being_modified);
            let node_client = node_client.clone();
            let plot_file = Arc::clone(&plot_file);
            let error_sender = Arc::clone(&error_sender);
            let span = span.clone();
            let global_mutex = Arc::clone(&global_mutex);
            let metrics = metrics.clone();

            move || {
                let _span_guard = span.enter();

                let plotting_options = PlottingOptions {
                    metadata_header,
                    sectors_metadata: &sectors_metadata,
                    sectors_being_modified: &sectors_being_modified,
                    sectors_to_plot_receiver,
                    sector_plotting_options: SectorPlottingOptions {
                        public_key,
                        node_client: &node_client,
                        pieces_in_sector,
                        sector_size,
                        plot_file,
                        metadata_file: Arc::new(metadata_file),
                        handlers: &handlers,
                        global_mutex: &global_mutex,
                        plotter,
                        metrics,
                    },
                    max_plotting_sectors_per_farm,
                };

                let plotting_fut = async {
                    if start_receiver.recv().await.is_err() {
                        // Dropped before starting
                        return Ok(());
                    }

                    if let Some(plotting_delay) = plotting_delay {
                        if plotting_delay.await.is_err() {
                            // Dropped before resolving
                            return Ok(());
                        }
                    }

                    plotting(plotting_options).await
                };

                Handle::current().block_on(async {
                    select! {
                        plotting_result = plotting_fut.fuse() => {
                            if let Err(error) = plotting_result
                                && let Some(error_sender) = error_sender.lock().take()
                                && let Err(error) = error_sender.send(error.into())
                            {
                                error!(
                                    %error,
                                    "Plotting failed to send error to background task"
                                );
                            }
                        }
                        _ = stop_receiver.recv().fuse() => {
                            // Nothing, just exit
                        }
                    }
                });
            }
        });
        let plotting_join_handle = AsyncJoinOnDrop::new(plotting_join_handle, false);

        tasks.push(Box::pin(async move {
            // Panic will already be printed by now
            plotting_join_handle.await.map_err(|_error| {
                BackgroundTaskError::BackgroundTaskPanicked {
                    task: format!("plotting-{farm_index}"),
                }
            })
        }));

        let plotting_scheduler_options = PlottingSchedulerOptions {
            public_key_hash: public_key.hash(),
            sectors_indices_left_to_plot,
            target_sector_count,
            last_archived_segment_index: farmer_app_info.protocol_info.history_size.segment_index(),
            min_sector_lifetime: farmer_app_info.protocol_info.min_sector_lifetime,
            node_client: node_client.clone(),
            handlers: Arc::clone(&handlers),
            sectors_metadata: Arc::clone(&sectors_metadata),
            sectors_to_plot_sender,
            new_segment_processing_delay: NEW_SEGMENT_PROCESSING_DELAY,
            metrics: metrics.clone(),
        };
        tasks.push(Box::pin(plotting_scheduler(plotting_scheduler_options)));

        let (slot_info_forwarder_sender, slot_info_forwarder_receiver) = mpsc::channel(0);

        tasks.push(Box::pin({
            let node_client = node_client.clone();
            let metrics = metrics.clone();

            async move {
                slot_notification_forwarder(&node_client, slot_info_forwarder_sender, metrics)
                    .await
                    .map_err(BackgroundTaskError::Farming)
            }
        }));

        let farming_join_handle = task::spawn_blocking({
            let erasure_coding = erasure_coding.clone();
            let handlers = Arc::clone(&handlers);
            let sectors_being_modified = Arc::clone(&sectors_being_modified);
            let sectors_metadata = Arc::clone(&sectors_metadata);
            let mut start_receiver = start_sender.subscribe();
            let mut stop_receiver = stop_sender.subscribe();
            let node_client = node_client.clone();
            let span = span.clone();
            let global_mutex = Arc::clone(&global_mutex);

            move || {
                let _span_guard = span.enter();

                let farming_fut = async move {
                    if start_receiver.recv().await.is_err() {
                        // Dropped before starting
                        return Ok(());
                    }

                    let plot_audit = PlotAudit::new(&farming_plot);

                    let farming_options = FarmingOptions {
                        public_key,
                        reward_address,
                        node_client,
                        plot_audit,
                        sectors_metadata,
                        kzg,
                        erasure_coding,
                        handlers,
                        sectors_being_modified,
                        slot_info_notifications: slot_info_forwarder_receiver,
                        thread_pool: farming_thread_pool,
                        read_sector_record_chunks_mode,
                        global_mutex,
                        metrics,
                    };
                    farming::<PosTable, _, _>(farming_options).await
                };

                Handle::current().block_on(async {
                    select! {
                        farming_result = farming_fut.fuse() => {
                            if let Err(error) = farming_result
                                && let Some(error_sender) = error_sender.lock().take()
                                && let Err(error) = error_sender.send(error.into())
                            {
                                error!(
                                    %error,
                                    "Farming failed to send error to background task",
                                );
                            }
                        }
                        _ = stop_receiver.recv().fuse() => {
                            // Nothing, just exit
                        }
                    }
                });
            }
        });
        let farming_join_handle = AsyncJoinOnDrop::new(farming_join_handle, false);

        tasks.push(Box::pin(async move {
            // Panic will already be printed by now
            farming_join_handle.await.map_err(|_error| {
                BackgroundTaskError::BackgroundTaskPanicked {
                    task: format!("farming-{farm_index}"),
                }
            })
        }));

        let (piece_reader, reading_fut) = DiskPieceReader::new::<PosTable>(
            public_key,
            pieces_in_sector,
            plot_file,
            Arc::clone(&sectors_metadata),
            erasure_coding,
            sectors_being_modified,
            read_sector_record_chunks_mode,
            global_mutex,
        );

        let reading_join_handle = task::spawn_blocking({
            let mut stop_receiver = stop_sender.subscribe();
            let reading_fut = reading_fut.instrument(span.clone());

            move || {
                Handle::current().block_on(async {
                    select! {
                        _ = reading_fut.fuse() => {
                            // Nothing, just exit
                        }
                        _ = stop_receiver.recv().fuse() => {
                            // Nothing, just exit
                        }
                    }
                });
            }
        });

        let reading_join_handle = AsyncJoinOnDrop::new(reading_join_handle, false);

        tasks.push(Box::pin(async move {
            // Panic will already be printed by now
            reading_join_handle.await.map_err(|_error| {
                BackgroundTaskError::BackgroundTaskPanicked {
                    task: format!("reading-{farm_index}"),
                }
            })
        }));

        tasks.push(Box::pin(async move {
            match reward_signing(node_client, identity).await {
                Ok(reward_signing_fut) => {
                    reward_signing_fut.await;
                }
                Err(error) => {
                    return Err(BackgroundTaskError::RewardSigning(anyhow::anyhow!(
                        "Failed to subscribe to reward signing notifications: {error}"
                    )));
                }
            }

            Ok(())
        }));

        let farm = Self {
            farmer_protocol_info: farmer_app_info.protocol_info,
            single_disk_farm_info,
            sectors_metadata,
            pieces_in_sector,
            total_sectors_count: target_sector_count,
            span,
            tasks,
            handlers,
            piece_cache,
            plot_cache,
            piece_reader,
            start_sender: Some(start_sender),
            stop_sender: Some(stop_sender),
            _single_disk_farm_info_lock: single_disk_farm_info_lock,
        };
        Ok(farm)
    }

    fn init(
        directory: &PathBuf,
        farmer_app_info: &FarmerAppInfo,
        allocated_space: u64,
        max_pieces_in_sector: u16,
        cache_percentage: u8,
        disable_farm_locking: bool,
        create: bool,
    ) -> Result<SingleDiskFarmInit, SingleDiskFarmError> {
        fs::create_dir_all(directory)?;

        let identity = if create {
            Identity::open_or_create(directory)?
        } else {
            Identity::open(directory)?.ok_or_else(|| {
                IdentityError::Io(io::Error::new(
                    io::ErrorKind::NotFound,
                    "Farm does not exist and creation was explicitly disabled",
                ))
            })?
        };
        let public_key = identity.public_key().to_bytes().into();

        let (single_disk_farm_info, single_disk_farm_info_lock) =
            match SingleDiskFarmInfo::load_from(directory)? {
                Some(mut single_disk_farm_info) => {
                    if &farmer_app_info.genesis_hash != single_disk_farm_info.genesis_hash() {
                        return Err(SingleDiskFarmError::WrongChain {
                            id: *single_disk_farm_info.id(),
                            correct_chain: hex::encode(single_disk_farm_info.genesis_hash()),
                            wrong_chain: hex::encode(farmer_app_info.genesis_hash),
                        });
                    }

                    if &public_key != single_disk_farm_info.public_key() {
                        return Err(SingleDiskFarmError::IdentityMismatch {
                            id: *single_disk_farm_info.id(),
                            correct_public_key: *single_disk_farm_info.public_key(),
                            wrong_public_key: public_key,
                        });
                    }

                    let pieces_in_sector = single_disk_farm_info.pieces_in_sector();

                    if max_pieces_in_sector < pieces_in_sector {
                        return Err(SingleDiskFarmError::InvalidPiecesInSector {
                            id: *single_disk_farm_info.id(),
                            max_supported: max_pieces_in_sector,
                            initialized_with: pieces_in_sector,
                        });
                    }

                    if max_pieces_in_sector > pieces_in_sector {
                        info!(
                            pieces_in_sector,
                            max_pieces_in_sector,
                            "Farm initialized with smaller number of pieces in sector, farm needs \
                            to be re-created for increase"
                        );
                    }

                    let mut single_disk_farm_info_lock = None;

                    if allocated_space != single_disk_farm_info.allocated_space() {
                        info!(
                            old_space = %bytesize::to_string(single_disk_farm_info.allocated_space(), true),
                            new_space = %bytesize::to_string(allocated_space, true),
                            "Farm size has changed"
                        );

                        let new_allocated_space = allocated_space;
                        match &mut single_disk_farm_info {
                            SingleDiskFarmInfo::V0 {
                                allocated_space, ..
                            } => {
                                *allocated_space = new_allocated_space;
                            }
                        }

                        single_disk_farm_info_lock =
                            single_disk_farm_info.store_to(directory, !disable_farm_locking)?;
                    } else if !disable_farm_locking {
                        single_disk_farm_info_lock = Some(
                            SingleDiskFarmInfo::try_lock(directory)
                                .map_err(SingleDiskFarmError::LikelyAlreadyInUse)?,
                        );
                    }

                    (single_disk_farm_info, single_disk_farm_info_lock)
                }
                None => {
                    let single_disk_farm_info = SingleDiskFarmInfo::new(
                        FarmId::new(),
                        farmer_app_info.genesis_hash,
                        public_key,
                        max_pieces_in_sector,
                        allocated_space,
                    );

                    let single_disk_farm_info_lock =
                        single_disk_farm_info.store_to(directory, !disable_farm_locking)?;

                    (single_disk_farm_info, single_disk_farm_info_lock)
                }
            };

        let pieces_in_sector = single_disk_farm_info.pieces_in_sector();
        let sector_size = sector_size(pieces_in_sector) as u64;
        let sector_metadata_size = SectorMetadataChecksummed::encoded_size();
        let allocated_space_distribution = AllocatedSpaceDistribution::new(
            allocated_space,
            sector_size,
            cache_percentage,
            sector_metadata_size as u64,
        )?;
        let target_sector_count = allocated_space_distribution.target_sector_count;

        let metadata_file_path = directory.join(Self::METADATA_FILE);
        let metadata_file = DirectIoFile::open(&metadata_file_path)?;

        let metadata_size = metadata_file.size()?;
        let expected_metadata_size = allocated_space_distribution.metadata_file_size;
        // Align plot file size for disk sector size
        let expected_metadata_size =
            expected_metadata_size.div_ceil(DISK_SECTOR_SIZE as u64) * DISK_SECTOR_SIZE as u64;
        let metadata_header = if metadata_size == 0 {
            let metadata_header = PlotMetadataHeader {
                version: SingleDiskFarm::SUPPORTED_PLOT_VERSION,
                plotted_sector_count: 0,
            };

            metadata_file
                .preallocate(expected_metadata_size)
                .map_err(SingleDiskFarmError::CantPreallocateMetadataFile)?;
            metadata_file.write_all_at(metadata_header.encode().as_slice(), 0)?;

            metadata_header
        } else {
            if metadata_size != expected_metadata_size {
                // Allocating the whole file (`set_len` below can create a sparse file, which will
                // cause writes to fail later)
                metadata_file
                    .preallocate(expected_metadata_size)
                    .map_err(SingleDiskFarmError::CantPreallocateMetadataFile)?;
                // Truncating file (if necessary)
                metadata_file.set_len(expected_metadata_size)?;
            }

            let mut metadata_header_bytes = vec![0; PlotMetadataHeader::encoded_size()];
            metadata_file.read_exact_at(&mut metadata_header_bytes, 0)?;

            let mut metadata_header =
                PlotMetadataHeader::decode(&mut metadata_header_bytes.as_ref())
                    .map_err(SingleDiskFarmError::FailedToDecodeMetadataHeader)?;

            if metadata_header.version != SingleDiskFarm::SUPPORTED_PLOT_VERSION {
                return Err(SingleDiskFarmError::UnexpectedMetadataVersion(
                    metadata_header.version,
                ));
            }

            if metadata_header.plotted_sector_count > target_sector_count {
                metadata_header.plotted_sector_count = target_sector_count;
                metadata_file.write_all_at(&metadata_header.encode(), 0)?;
            }

            metadata_header
        };

        let sectors_metadata = {
            let mut sectors_metadata =
                Vec::<SectorMetadataChecksummed>::with_capacity(usize::from(target_sector_count));

            let mut sector_metadata_bytes = vec![0; sector_metadata_size];
            for sector_index in 0..metadata_header.plotted_sector_count {
                let sector_offset =
                    RESERVED_PLOT_METADATA + sector_metadata_size as u64 * u64::from(sector_index);
                metadata_file.read_exact_at(&mut sector_metadata_bytes, sector_offset)?;

                let sector_metadata =
                    match SectorMetadataChecksummed::decode(&mut sector_metadata_bytes.as_ref()) {
                        Ok(sector_metadata) => sector_metadata,
                        Err(error) => {
                            warn!(
                                path = %metadata_file_path.display(),
                                %error,
                                %sector_index,
                                "Failed to decode sector metadata, replacing with dummy expired \
                                sector metadata"
                            );

                            let dummy_sector = SectorMetadataChecksummed::from(SectorMetadata {
                                sector_index,
                                pieces_in_sector,
                                s_bucket_sizes: Box::new([0; Record::NUM_S_BUCKETS]),
                                history_size: HistorySize::from(SegmentIndex::ZERO),
                            });
                            metadata_file.write_all_at(&dummy_sector.encode(), sector_offset)?;

                            dummy_sector
                        }
                    };
                sectors_metadata.push(sector_metadata);
            }

            Arc::new(AsyncRwLock::new(sectors_metadata))
        };

        let plot_file = DirectIoFile::open(directory.join(Self::PLOT_FILE))?;

        if plot_file.size()? != allocated_space_distribution.plot_file_size {
            // Allocating the whole file (`set_len` below can create a sparse file, which will cause
            // writes to fail later)
            plot_file
                .preallocate(allocated_space_distribution.plot_file_size)
                .map_err(SingleDiskFarmError::CantPreallocatePlotFile)?;
            // Truncating file (if necessary)
            plot_file.set_len(allocated_space_distribution.plot_file_size)?;
        }

        let plot_file = Arc::new(plot_file);

        let plot_cache = DiskPlotCache::new(
            &plot_file,
            &sectors_metadata,
            target_sector_count,
            sector_size,
        );

        Ok(SingleDiskFarmInit {
            identity,
            single_disk_farm_info,
            single_disk_farm_info_lock,
            plot_file,
            metadata_file,
            metadata_header,
            target_sector_count,
            sectors_metadata,
            piece_cache_capacity: allocated_space_distribution.piece_cache_capacity,
            plot_cache,
        })
    }

    /// Collect summary of single disk farm for presentational purposes
    pub fn collect_summary(directory: PathBuf) -> SingleDiskFarmSummary {
        let single_disk_farm_info = match SingleDiskFarmInfo::load_from(&directory) {
            Ok(Some(single_disk_farm_info)) => single_disk_farm_info,
            Ok(None) => {
                return SingleDiskFarmSummary::NotFound { directory };
            }
            Err(error) => {
                return SingleDiskFarmSummary::Error { directory, error };
            }
        };

        SingleDiskFarmSummary::Found {
            info: single_disk_farm_info,
            directory,
        }
    }

    /// Effective on-disk allocation of the files related to the farm (takes some buffer space
    /// into consideration).
    ///
    /// This is a helpful number in case some files were not allocated properly or were removed and
    /// do not correspond to allocated space in the farm info accurately.
    pub fn effective_disk_usage(
        directory: &Path,
        cache_percentage: u8,
    ) -> Result<u64, SingleDiskFarmError> {
        let mut effective_disk_usage;
        match SingleDiskFarmInfo::load_from(directory)? {
            Some(single_disk_farm_info) => {
                let allocated_space_distribution = AllocatedSpaceDistribution::new(
                    single_disk_farm_info.allocated_space(),
                    sector_size(single_disk_farm_info.pieces_in_sector()) as u64,
                    cache_percentage,
                    SectorMetadataChecksummed::encoded_size() as u64,
                )?;

                effective_disk_usage = single_disk_farm_info.allocated_space();
                effective_disk_usage -= Identity::file_size() as u64;
                effective_disk_usage -= allocated_space_distribution.metadata_file_size;
                effective_disk_usage -= allocated_space_distribution.plot_file_size;
                effective_disk_usage -= allocated_space_distribution.piece_cache_file_size;
            }
            None => {
                // No farm info, try to collect actual file sizes is any
                effective_disk_usage = 0;
            }
        };

        if Identity::open(directory)?.is_some() {
            effective_disk_usage += Identity::file_size() as u64;
        }

        match OpenOptions::new()
            .read(true)
            .open(directory.join(Self::METADATA_FILE))
        {
            Ok(metadata_file) => {
                effective_disk_usage += metadata_file.size()?;
            }
            Err(error) => {
                if error.kind() == io::ErrorKind::NotFound {
                    // File is not stored on disk
                } else {
                    return Err(error.into());
                }
            }
        };

        match OpenOptions::new()
            .read(true)
            .open(directory.join(Self::PLOT_FILE))
        {
            Ok(plot_file) => {
                effective_disk_usage += plot_file.size()?;
            }
            Err(error) => {
                if error.kind() == io::ErrorKind::NotFound {
                    // File is not stored on disk
                } else {
                    return Err(error.into());
                }
            }
        };

        match OpenOptions::new()
            .read(true)
            .open(directory.join(DiskPieceCache::FILE_NAME))
        {
            Ok(piece_cache) => {
                effective_disk_usage += piece_cache.size()?;
            }
            Err(error) => {
                if error.kind() == io::ErrorKind::NotFound {
                    // File is not stored on disk
                } else {
                    return Err(error.into());
                }
            }
        };

        Ok(effective_disk_usage)
    }

    /// Read all sectors metadata
    pub fn read_all_sectors_metadata(
        directory: &Path,
    ) -> io::Result<Vec<SectorMetadataChecksummed>> {
        let metadata_file = DirectIoFile::open(directory.join(Self::METADATA_FILE))?;

        let metadata_size = metadata_file.size()?;
        let sector_metadata_size = SectorMetadataChecksummed::encoded_size();

        let mut metadata_header_bytes = vec![0; PlotMetadataHeader::encoded_size()];
        metadata_file.read_exact_at(&mut metadata_header_bytes, 0)?;

        let metadata_header = PlotMetadataHeader::decode(&mut metadata_header_bytes.as_ref())
            .map_err(|error| {
                io::Error::new(
                    io::ErrorKind::Other,
                    format!("Failed to decode metadata header: {}", error),
                )
            })?;

        if metadata_header.version != SingleDiskFarm::SUPPORTED_PLOT_VERSION {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!("Unsupported metadata version {}", metadata_header.version),
            ));
        }

        let mut sectors_metadata = Vec::<SectorMetadataChecksummed>::with_capacity(
            ((metadata_size - RESERVED_PLOT_METADATA) / sector_metadata_size as u64) as usize,
        );

        let mut sector_metadata_bytes = vec![0; sector_metadata_size];
        for sector_index in 0..metadata_header.plotted_sector_count {
            metadata_file.read_exact_at(
                &mut sector_metadata_bytes,
                RESERVED_PLOT_METADATA + sector_metadata_size as u64 * u64::from(sector_index),
            )?;
            sectors_metadata.push(
                SectorMetadataChecksummed::decode(&mut sector_metadata_bytes.as_ref()).map_err(
                    |error| {
                        io::Error::new(
                            io::ErrorKind::Other,
                            format!("Failed to decode sector metadata: {}", error),
                        )
                    },
                )?,
            );
        }

        Ok(sectors_metadata)
    }

    /// ID of this farm
    pub fn id(&self) -> &FarmId {
        self.single_disk_farm_info.id()
    }

    /// Info of this farm
    pub fn info(&self) -> &SingleDiskFarmInfo {
        &self.single_disk_farm_info
    }

    /// Number of sectors in this farm
    pub fn total_sectors_count(&self) -> SectorIndex {
        self.total_sectors_count
    }

    /// Read information about sectors plotted so far
    pub fn plotted_sectors(&self) -> SingleDiskPlottedSectors {
        SingleDiskPlottedSectors {
            public_key: *self.single_disk_farm_info.public_key(),
            pieces_in_sector: self.pieces_in_sector,
            farmer_protocol_info: self.farmer_protocol_info,
            sectors_metadata: Arc::clone(&self.sectors_metadata),
        }
    }

    /// Get piece cache instance
    pub fn piece_cache(&self) -> SingleDiskPieceCache {
        self.piece_cache.clone()
    }

    /// Get plot cache instance
    pub fn plot_cache(&self) -> DiskPlotCache {
        self.plot_cache.clone()
    }

    /// Get piece reader to read plotted pieces later
    pub fn piece_reader(&self) -> DiskPieceReader {
        self.piece_reader.clone()
    }

    /// Subscribe to sector updates
    pub fn on_sector_update(&self, callback: HandlerFn<(SectorIndex, SectorUpdate)>) -> HandlerId {
        self.handlers.sector_update.add(callback)
    }

    /// Subscribe to farming notifications
    pub fn on_farming_notification(&self, callback: HandlerFn<FarmingNotification>) -> HandlerId {
        self.handlers.farming_notification.add(callback)
    }

    /// Subscribe to new solution notification
    pub fn on_solution(&self, callback: HandlerFn<SolutionResponse>) -> HandlerId {
        self.handlers.solution.add(callback)
    }

    /// Run and wait for background threads to exit or return an error
    pub async fn run(mut self) -> anyhow::Result<()> {
        if let Some(start_sender) = self.start_sender.take() {
            // Do not care if anyone is listening on the other side
            let _ = start_sender.send(());
        }

        while let Some(result) = self.tasks.next().instrument(self.span.clone()).await {
            result?;
        }

        Ok(())
    }

    /// Wipe everything that belongs to this single disk farm
    pub fn wipe(directory: &Path) -> io::Result<()> {
        let single_disk_info_info_path = directory.join(SingleDiskFarmInfo::FILE_NAME);
        match SingleDiskFarmInfo::load_from(directory) {
            Ok(Some(single_disk_farm_info)) => {
                info!("Found single disk farm {}", single_disk_farm_info.id());
            }
            Ok(None) => {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!(
                        "Single disk farm info not found at {}",
                        single_disk_info_info_path.display()
                    ),
                ));
            }
            Err(error) => {
                warn!("Found unknown single disk farm: {}", error);
            }
        }

        {
            let plot = directory.join(Self::PLOT_FILE);
            if plot.exists() {
                info!("Deleting plot file at {}", plot.display());
                fs::remove_file(plot)?;
            }
        }
        {
            let metadata = directory.join(Self::METADATA_FILE);
            if metadata.exists() {
                info!("Deleting metadata file at {}", metadata.display());
                fs::remove_file(metadata)?;
            }
        }
        // TODO: Identity should be able to wipe itself instead of assuming a specific file name
        //  here
        {
            let identity = directory.join("identity.bin");
            if identity.exists() {
                info!("Deleting identity file at {}", identity.display());
                fs::remove_file(identity)?;
            }
        }

        DiskPieceCache::wipe(directory)?;

        info!(
            "Deleting info file at {}",
            single_disk_info_info_path.display()
        );
        fs::remove_file(single_disk_info_info_path)
    }

    /// Check the farm for corruption and repair errors (caused by disk errors or something else),
    /// returns an error when irrecoverable errors occur.
    pub fn scrub(
        directory: &Path,
        disable_farm_locking: bool,
        target: ScrubTarget,
        dry_run: bool,
    ) -> Result<(), SingleDiskFarmScrubError> {
        let span = Span::current();

        if dry_run {
            info!("Dry run is used, no changes will be written to disk");
        }

        if target.metadata() || target.plot() {
            let info = {
                let file = directory.join(SingleDiskFarmInfo::FILE_NAME);
                info!(path = %file.display(), "Checking info file");

                match SingleDiskFarmInfo::load_from(directory) {
                    Ok(Some(info)) => info,
                    Ok(None) => {
                        return Err(SingleDiskFarmScrubError::FarmInfoFileDoesNotExist { file });
                    }
                    Err(error) => {
                        return Err(SingleDiskFarmScrubError::FarmInfoCantBeOpened { file, error });
                    }
                }
            };

            let _single_disk_farm_info_lock = if disable_farm_locking {
                None
            } else {
                Some(
                    SingleDiskFarmInfo::try_lock(directory)
                        .map_err(SingleDiskFarmScrubError::LikelyAlreadyInUse)?,
                )
            };

            let identity = {
                let file = directory.join(Identity::FILE_NAME);
                info!(path = %file.display(), "Checking identity file");

                match Identity::open(directory) {
                    Ok(Some(identity)) => identity,
                    Ok(None) => {
                        return Err(SingleDiskFarmScrubError::IdentityFileDoesNotExist { file });
                    }
                    Err(error) => {
                        return Err(SingleDiskFarmScrubError::IdentityCantBeOpened { file, error });
                    }
                }
            };

            if PublicKey::from(identity.public.to_bytes()) != *info.public_key() {
                return Err(SingleDiskFarmScrubError::PublicKeyMismatch {
                    identity: PublicKey::from(identity.public.to_bytes()),
                    info: *info.public_key(),
                });
            }

            let sector_metadata_size = SectorMetadataChecksummed::encoded_size();

            let metadata_file_path = directory.join(Self::METADATA_FILE);
            let (metadata_file, mut metadata_header) = {
                info!(path = %metadata_file_path.display(), "Checking metadata file");

                let metadata_file = match OpenOptions::new()
                    .read(true)
                    .write(!dry_run)
                    .open(&metadata_file_path)
                {
                    Ok(metadata_file) => metadata_file,
                    Err(error) => {
                        return Err(if error.kind() == io::ErrorKind::NotFound {
                            SingleDiskFarmScrubError::MetadataFileDoesNotExist {
                                file: metadata_file_path,
                            }
                        } else {
                            SingleDiskFarmScrubError::MetadataCantBeOpened {
                                file: metadata_file_path,
                                error,
                            }
                        });
                    }
                };

                // Error doesn't matter here
                let _ = metadata_file.advise_sequential_access();

                let metadata_size = match metadata_file.size() {
                    Ok(metadata_size) => metadata_size,
                    Err(error) => {
                        return Err(SingleDiskFarmScrubError::FailedToDetermineFileSize {
                            file: metadata_file_path,
                            error,
                        });
                    }
                };

                if metadata_size < RESERVED_PLOT_METADATA {
                    return Err(SingleDiskFarmScrubError::MetadataFileTooSmall {
                        file: metadata_file_path,
                        reserved_size: RESERVED_PLOT_METADATA,
                        size: metadata_size,
                    });
                }

                let mut metadata_header = {
                    let mut reserved_metadata = vec![0; RESERVED_PLOT_METADATA as usize];

                    if let Err(error) = metadata_file.read_exact_at(&mut reserved_metadata, 0) {
                        return Err(SingleDiskFarmScrubError::FailedToReadBytes {
                            file: metadata_file_path,
                            size: RESERVED_PLOT_METADATA,
                            offset: 0,
                            error,
                        });
                    }

                    PlotMetadataHeader::decode(&mut reserved_metadata.as_slice())
                        .map_err(SingleDiskFarmScrubError::FailedToDecodeMetadataHeader)?
                };

                if metadata_header.version != SingleDiskFarm::SUPPORTED_PLOT_VERSION {
                    return Err(SingleDiskFarmScrubError::UnexpectedMetadataVersion(
                        metadata_header.version,
                    ));
                }

                let plotted_sector_count = metadata_header.plotted_sector_count;

                let expected_metadata_size = RESERVED_PLOT_METADATA
                    + sector_metadata_size as u64 * u64::from(plotted_sector_count);

                if metadata_size < expected_metadata_size {
                    warn!(
                        %metadata_size,
                        %expected_metadata_size,
                        "Metadata file size is smaller than expected, shrinking number of plotted \
                        sectors to correct value"
                    );

                    metadata_header.plotted_sector_count =
                        ((metadata_size - RESERVED_PLOT_METADATA) / sector_metadata_size as u64)
                            as SectorIndex;
                    let metadata_header_bytes = metadata_header.encode();

                    if !dry_run {
                        if let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) {
                            return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
                                file: metadata_file_path,
                                size: metadata_header_bytes.len() as u64,
                                offset: 0,
                                error,
                            });
                        }
                    }
                }

                (metadata_file, metadata_header)
            };

            let pieces_in_sector = info.pieces_in_sector();
            let sector_size = sector_size(pieces_in_sector) as u64;

            let plot_file_path = directory.join(Self::PLOT_FILE);
            let plot_file = {
                let plot_file_path = directory.join(Self::PLOT_FILE);
                info!(path = %plot_file_path.display(), "Checking plot file");

                let plot_file = match OpenOptions::new()
                    .read(true)
                    .write(!dry_run)
                    .open(&plot_file_path)
                {
                    Ok(plot_file) => plot_file,
                    Err(error) => {
                        return Err(if error.kind() == io::ErrorKind::NotFound {
                            SingleDiskFarmScrubError::MetadataFileDoesNotExist {
                                file: plot_file_path,
                            }
                        } else {
                            SingleDiskFarmScrubError::MetadataCantBeOpened {
                                file: plot_file_path,
                                error,
                            }
                        });
                    }
                };

                // Error doesn't matter here
                let _ = plot_file.advise_sequential_access();

                let plot_size = match plot_file.size() {
                    Ok(metadata_size) => metadata_size,
                    Err(error) => {
                        return Err(SingleDiskFarmScrubError::FailedToDetermineFileSize {
                            file: plot_file_path,
                            error,
                        });
                    }
                };

                let min_expected_plot_size =
                    u64::from(metadata_header.plotted_sector_count) * sector_size;
                if plot_size < min_expected_plot_size {
                    warn!(
                        %plot_size,
                        %min_expected_plot_size,
                        "Plot file size is smaller than expected, shrinking number of plotted \
                        sectors to correct value"
                    );

                    metadata_header.plotted_sector_count = (plot_size / sector_size) as SectorIndex;
                    let metadata_header_bytes = metadata_header.encode();

                    if !dry_run {
                        if let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) {
                            return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
                                file: plot_file_path,
                                size: metadata_header_bytes.len() as u64,
                                offset: 0,
                                error,
                            });
                        }
                    }
                }

                plot_file
            };

            let sector_bytes_range = 0..(sector_size as usize - Blake3Hash::SIZE);

            info!("Checking sectors and corresponding metadata");
            (0..metadata_header.plotted_sector_count)
                .into_par_iter()
                .map_init(
                    || vec![0u8; Record::SIZE],
                    |scratch_buffer, sector_index| {
                        let _span_guard = span.enter();

                        let offset = RESERVED_PLOT_METADATA
                            + u64::from(sector_index) * sector_metadata_size as u64;
                        if let Err(error) = metadata_file
                            .read_exact_at(&mut scratch_buffer[..sector_metadata_size], offset)
                        {
                            warn!(
                                path = %metadata_file_path.display(),
                                %error,
                                %offset,
                                size = %sector_metadata_size,
                                %sector_index,
                                "Failed to read sector metadata, replacing with dummy expired \
                                sector metadata"
                            );

                            if !dry_run {
                                write_dummy_sector_metadata(
                                    &metadata_file,
                                    &metadata_file_path,
                                    sector_index,
                                    pieces_in_sector,
                                )?;
                            }
                            return Ok(());
                        }

                        let sector_metadata = match SectorMetadataChecksummed::decode(
                            &mut &scratch_buffer[..sector_metadata_size],
                        ) {
                            Ok(sector_metadata) => sector_metadata,
                            Err(error) => {
                                warn!(
                                    path = %metadata_file_path.display(),
                                    %error,
                                    %sector_index,
                                    "Failed to decode sector metadata, replacing with dummy \
                                    expired sector metadata"
                                );

                                if !dry_run {
                                    write_dummy_sector_metadata(
                                        &metadata_file,
                                        &metadata_file_path,
                                        sector_index,
                                        pieces_in_sector,
                                    )?;
                                }
                                return Ok(());
                            }
                        };

                        if sector_metadata.sector_index != sector_index {
                            warn!(
                                path = %metadata_file_path.display(),
                                %sector_index,
                                found_sector_index = sector_metadata.sector_index,
                                "Sector index mismatch, replacing with dummy expired sector \
                                metadata"
                            );

                            if !dry_run {
                                write_dummy_sector_metadata(
                                    &metadata_file,
                                    &metadata_file_path,
                                    sector_index,
                                    pieces_in_sector,
                                )?;
                            }
                            return Ok(());
                        }

                        if sector_metadata.pieces_in_sector != pieces_in_sector {
                            warn!(
                                path = %metadata_file_path.display(),
                                %sector_index,
                                %pieces_in_sector,
                                found_pieces_in_sector = sector_metadata.pieces_in_sector,
                                "Pieces in sector mismatch, replacing with dummy expired sector \
                                metadata"
                            );

                            if !dry_run {
                                write_dummy_sector_metadata(
                                    &metadata_file,
                                    &metadata_file_path,
                                    sector_index,
                                    pieces_in_sector,
                                )?;
                            }
                            return Ok(());
                        }

                        if target.plot() {
                            let mut hasher = blake3::Hasher::new();
                            // Read sector bytes and compute checksum
                            for offset_in_sector in
                                sector_bytes_range.clone().step_by(scratch_buffer.len())
                            {
                                let offset =
                                    u64::from(sector_index) * sector_size + offset_in_sector as u64;
                                let bytes_to_read = (offset_in_sector + scratch_buffer.len())
                                    .min(sector_bytes_range.end)
                                    - offset_in_sector;

                                let bytes = &mut scratch_buffer[..bytes_to_read];

                                if let Err(error) = plot_file.read_exact_at(bytes, offset) {
                                    warn!(
                                        path = %plot_file_path.display(),
                                        %error,
                                        %sector_index,
                                        %offset,
                                        size = %bytes.len() as u64,
                                        "Failed to read sector bytes"
                                    );

                                    continue;
                                }

                                hasher.update(bytes);
                            }

                            let actual_checksum = *hasher.finalize().as_bytes();
                            let mut expected_checksum = [0; Blake3Hash::SIZE];
                            {
                                let offset = u64::from(sector_index) * sector_size
                                    + sector_bytes_range.end as u64;
                                if let Err(error) =
                                    plot_file.read_exact_at(&mut expected_checksum, offset)
                                {
                                    warn!(
                                        path = %plot_file_path.display(),
                                        %error,
                                        %sector_index,
                                        %offset,
                                        size = %expected_checksum.len() as u64,
                                        "Failed to read sector checksum bytes"
                                    );
                                }
                            }

                            // Verify checksum
                            if actual_checksum != expected_checksum {
                                warn!(
                                    path = %plot_file_path.display(),
                                    %sector_index,
                                    actual_checksum = %hex::encode(actual_checksum),
                                    expected_checksum = %hex::encode(expected_checksum),
                                    "Plotted sector checksum mismatch, replacing with dummy \
                                    expired sector"
                                );

                                if !dry_run {
                                    write_dummy_sector_metadata(
                                        &metadata_file,
                                        &metadata_file_path,
                                        sector_index,
                                        pieces_in_sector,
                                    )?;
                                }

                                scratch_buffer.fill(0);

                                hasher.reset();
                                // Fill sector with zeroes and compute checksum
                                for offset_in_sector in
                                    sector_bytes_range.clone().step_by(scratch_buffer.len())
                                {
                                    let offset = u64::from(sector_index) * sector_size
                                        + offset_in_sector as u64;
                                    let bytes_to_write = (offset_in_sector + scratch_buffer.len())
                                        .min(sector_bytes_range.end)
                                        - offset_in_sector;
                                    let bytes = &mut scratch_buffer[..bytes_to_write];

                                    if !dry_run {
                                        if let Err(error) = plot_file.write_all_at(bytes, offset) {
                                            return Err(
                                                SingleDiskFarmScrubError::FailedToWriteBytes {
                                                    file: plot_file_path.clone(),
                                                    size: scratch_buffer.len() as u64,
                                                    offset,
                                                    error,
                                                },
                                            );
                                        }
                                    }

                                    hasher.update(bytes);
                                }
                                // Write checksum
                                {
                                    let checksum = *hasher.finalize().as_bytes();
                                    let offset = u64::from(sector_index) * sector_size
                                        + sector_bytes_range.end as u64;
                                    if !dry_run {
                                        if let Err(error) =
                                            plot_file.write_all_at(&checksum, offset)
                                        {
                                            return Err(
                                                SingleDiskFarmScrubError::FailedToWriteBytes {
                                                    file: plot_file_path.clone(),
                                                    size: checksum.len() as u64,
                                                    offset,
                                                    error,
                                                },
                                            );
                                        }
                                    }
                                }

                                return Ok(());
                            }
                        }

                        trace!(%sector_index, "Sector is in good shape");

                        Ok(())
                    },
                )
                .try_for_each({
                    let span = &span;
                    let checked_sectors = AtomicUsize::new(0);

                    move |result| {
                        let _span_guard = span.enter();

                        let checked_sectors = checked_sectors.fetch_add(1, Ordering::Relaxed);
                        if checked_sectors > 1 && checked_sectors % 10 == 0 {
                            info!(
                                "Checked {}/{} sectors",
                                checked_sectors, metadata_header.plotted_sector_count
                            );
                        }

                        result
                    }
                })?;
        }

        if target.cache() {
            Self::scrub_cache(directory, dry_run)?;
        }

        info!("Farm check completed");

        Ok(())
    }

    fn scrub_cache(directory: &Path, dry_run: bool) -> Result<(), SingleDiskFarmScrubError> {
        let span = Span::current();

        let file = directory.join(DiskPieceCache::FILE_NAME);
        info!(path = %file.display(), "Checking cache file");

        let cache_file = match OpenOptions::new().read(true).write(!dry_run).open(&file) {
            Ok(plot_file) => plot_file,
            Err(error) => {
                return if error.kind() == io::ErrorKind::NotFound {
                    warn!(
                        file = %file.display(),
                        "Cache file does not exist, this is expected in farming cluster"
                    );
                    Ok(())
                } else {
                    Err(SingleDiskFarmScrubError::CacheCantBeOpened { file, error })
                };
            }
        };

        // Error doesn't matter here
        let _ = cache_file.advise_sequential_access();

        let cache_size = match cache_file.size() {
            Ok(cache_size) => cache_size,
            Err(error) => {
                return Err(SingleDiskFarmScrubError::FailedToDetermineFileSize { file, error });
            }
        };

        let element_size = DiskPieceCache::element_size();
        let number_of_cached_elements = cache_size / u64::from(element_size);
        let dummy_element = vec![0; element_size as usize];
        (0..number_of_cached_elements)
            .into_par_iter()
            .map_with(vec![0; element_size as usize], |element, cache_offset| {
                let _span_guard = span.enter();

                let offset = cache_offset * u64::from(element_size);
                if let Err(error) = cache_file.read_exact_at(element, offset) {
                    warn!(
                        path = %file.display(),
                        %cache_offset,
                        size = %element.len() as u64,
                        %offset,
                        %error,
                        "Failed to read cached piece, replacing with dummy element"
                    );

                    if !dry_run {
                        if let Err(error) = cache_file.write_all_at(&dummy_element, offset) {
                            return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
                                file: file.clone(),
                                size: u64::from(element_size),
                                offset,
                                error,
                            });
                        }
                    }

                    return Ok(());
                }

                let (index_and_piece_bytes, expected_checksum) =
                    element.split_at(element_size as usize - Blake3Hash::SIZE);
                let actual_checksum = blake3_hash(index_and_piece_bytes);
                if *actual_checksum != *expected_checksum && element != &dummy_element {
                    warn!(
                        %cache_offset,
                        actual_checksum = %hex::encode(actual_checksum),
                        expected_checksum = %hex::encode(expected_checksum),
                        "Cached piece checksum mismatch, replacing with dummy element"
                    );

                    if !dry_run {
                        if let Err(error) = cache_file.write_all_at(&dummy_element, offset) {
                            return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
                                file: file.clone(),
                                size: u64::from(element_size),
                                offset,
                                error,
                            });
                        }
                    }

                    return Ok(());
                }

                Ok(())
            })
            .try_for_each({
                let span = &span;
                let checked_elements = AtomicUsize::new(0);

                move |result| {
                    let _span_guard = span.enter();

                    let checked_elements = checked_elements.fetch_add(1, Ordering::Relaxed);
                    if checked_elements > 1 && checked_elements % 1000 == 0 {
                        info!(
                            "Checked {}/{} cache elements",
                            checked_elements, number_of_cached_elements
                        );
                    }

                    result
                }
            })?;

        Ok(())
    }
}

fn write_dummy_sector_metadata(
    metadata_file: &File,
    metadata_file_path: &Path,
    sector_index: SectorIndex,
    pieces_in_sector: u16,
) -> Result<(), SingleDiskFarmScrubError> {
    let dummy_sector_bytes = SectorMetadataChecksummed::from(SectorMetadata {
        sector_index,
        pieces_in_sector,
        s_bucket_sizes: Box::new([0; Record::NUM_S_BUCKETS]),
        history_size: HistorySize::from(SegmentIndex::ZERO),
    })
    .encode();
    let sector_offset = RESERVED_PLOT_METADATA
        + u64::from(sector_index) * SectorMetadataChecksummed::encoded_size() as u64;
    metadata_file
        .write_all_at(&dummy_sector_bytes, sector_offset)
        .map_err(|error| SingleDiskFarmScrubError::FailedToWriteBytes {
            file: metadata_file_path.to_path_buf(),
            size: dummy_sector_bytes.len() as u64,
            offset: sector_offset,
            error,
        })
}

fn faster_read_sector_record_chunks_mode<OP, FP>(
    original_plot: &OP,
    farming_plot: &FP,
    sector_size: usize,
    mut plotted_sector_count: SectorIndex,
) -> Result<ReadSectorRecordChunksMode, SingleDiskFarmError>
where
    OP: FileExt + Sync,
    FP: ReadAtSync,
{
    info!("Benchmarking faster proving method");

    let mut sector_bytes = vec![0u8; sector_size];

    if plotted_sector_count == 0 {
        thread_rng().fill_bytes(&mut sector_bytes);
        original_plot.write_all_at(&sector_bytes, 0)?;

        plotted_sector_count = 1;
    }

    let mut fastest_mode = ReadSectorRecordChunksMode::ConcurrentChunks;
    let mut fastest_time = Duration::MAX;

    for _ in 0..3 {
        let sector_offset =
            sector_size as u64 * thread_rng().gen_range(0..plotted_sector_count) as u64;
        let farming_plot = farming_plot.offset(sector_offset);

        // Reading the whole sector at once
        {
            let start = Instant::now();
            farming_plot.read_at(&mut sector_bytes, 0)?;
            let elapsed = start.elapsed();

            debug!(?elapsed, "Whole sector");

            if elapsed >= INTERNAL_BENCHMARK_READ_TIMEOUT {
                debug!(
                    ?elapsed,
                    "Reading whole sector is too slow, using chunks instead"
                );

                fastest_mode = ReadSectorRecordChunksMode::ConcurrentChunks;
                break;
            }

            if fastest_time > elapsed {
                fastest_mode = ReadSectorRecordChunksMode::WholeSector;
                fastest_time = elapsed;
            }
        }

        // A lot simplified version of concurrent chunks
        {
            let start = Instant::now();
            (0..Record::NUM_CHUNKS).into_par_iter().try_for_each(|_| {
                let offset = thread_rng().gen_range(0_usize..sector_size / ScalarBytes::FULL_BYTES)
                    * ScalarBytes::FULL_BYTES;
                farming_plot.read_at(&mut [0; ScalarBytes::FULL_BYTES], offset as u64)
            })?;
            let elapsed = start.elapsed();

            debug!(?elapsed, "Chunks");

            if fastest_time > elapsed {
                fastest_mode = ReadSectorRecordChunksMode::ConcurrentChunks;
                fastest_time = elapsed;
            }
        }
    }

    info!(?fastest_mode, "Faster proving method found");

    Ok(fastest_mode)
}