Skip to main content

ab_farmer/
single_disk_farm.rs

1//! Primary [`Farm`] implementation that deals with hardware directly
2//!
3//! Single disk farm is an abstraction that contains an identity, associated plot with metadata and
4//! a small piece cache. It fully manages farming and plotting process, including listening to node
5//! notifications, producing solutions and sealing blocks.
6
7mod block_sealing;
8pub mod farming;
9pub mod identity;
10mod metrics;
11pub mod piece_cache;
12pub mod piece_reader;
13pub mod plot_cache;
14mod plotted_sectors;
15mod plotting;
16#[cfg(test)]
17mod tests;
18
19use crate::disk_piece_cache::{DiskPieceCache, DiskPieceCacheError};
20use crate::farm::{
21    Farm, FarmId, FarmingError, FarmingNotification, HandlerFn, PieceCacheId, PieceReader,
22    PlottedSectors, SectorUpdate,
23};
24use crate::node_client::NodeClient;
25use crate::plotter::Plotter;
26use crate::single_disk_farm::block_sealing::block_sealing;
27use crate::single_disk_farm::farming::rayon_files::RayonFiles;
28use crate::single_disk_farm::farming::{
29    FarmingOptions, PlotAudit, farming, slot_notification_forwarder,
30};
31use crate::single_disk_farm::identity::{Identity, IdentityError};
32use crate::single_disk_farm::metrics::SingleDiskFarmMetrics;
33use crate::single_disk_farm::piece_cache::SingleDiskPieceCache;
34use crate::single_disk_farm::piece_reader::DiskPieceReader;
35use crate::single_disk_farm::plot_cache::DiskPlotCache;
36use crate::single_disk_farm::plotted_sectors::SingleDiskPlottedSectors;
37pub use crate::single_disk_farm::plotting::PlottingError;
38use crate::single_disk_farm::plotting::{
39    PlottingOptions, PlottingSchedulerOptions, SectorPlottingOptions, plotting, plotting_scheduler,
40};
41use crate::utils::{AsyncJoinOnDrop, tokio_rayon_spawn_handler};
42use crate::{KNOWN_PEERS_CACHE_SIZE, farm};
43use ab_core_primitives::address::Address;
44use ab_core_primitives::block::BlockRoot;
45use ab_core_primitives::ed25519::Ed25519PublicKey;
46use ab_core_primitives::hashes::Blake3Hash;
47use ab_core_primitives::pieces::{Piece, PieceIndex, Record};
48use ab_core_primitives::sectors::SectorIndex;
49use ab_core_primitives::segments::{HistorySize, SegmentIndex};
50use ab_direct_io_file::{DirectIoFile, IoBufError, OwnedPages};
51use ab_erasure_coding::ErasureCoding;
52use ab_farmer_components::FarmerProtocolInfo;
53use ab_farmer_components::file_ext::FileExt;
54use ab_farmer_components::sector::{SectorMetadata, SectorMetadataChecksummed, sector_size};
55use ab_farmer_components::shard_commitment::ShardCommitmentsRootsCache;
56use ab_farmer_rpc_primitives::{FarmerAppInfo, SolutionResponse};
57use ab_networking::KnownPeersManager;
58use ab_proof_of_space::Table;
59use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock};
60use async_trait::async_trait;
61use bytesize::ByteSize;
62use event_listener_primitives::{Bag, HandlerId};
63use fs4::FileExt as _;
64use futures::channel::{mpsc, oneshot};
65use futures::stream::FuturesUnordered;
66use futures::{FutureExt, StreamExt, select};
67use parity_scale_codec::{Decode, Encode};
68use parking_lot::Mutex;
69use prometheus_client::registry::Registry;
70use rayon::prelude::*;
71use rayon::{ThreadPoolBuildError, ThreadPoolBuilder};
72use serde::{Deserialize, Serialize};
73use std::collections::HashSet;
74use std::fs::{File, OpenOptions};
75use std::future::Future;
76use std::io::Write;
77use std::num::{NonZeroU32, NonZeroUsize};
78use std::path::{Path, PathBuf};
79use std::pin::Pin;
80use std::str::FromStr;
81use std::sync::Arc as StdArc;
82use std::sync::atomic::{AtomicUsize, Ordering};
83use std::time::Duration;
84use std::{fmt, fs, io};
85use thiserror::Error;
86use tokio::runtime::Handle;
87use tokio::sync::broadcast;
88use tokio::task;
89use tracing::{Instrument, Span, error, info, trace, warn};
90use triomphe::Arc;
91
92// Refuse to compile on non-64-bit platforms, offsets may fail on those when converting from u64 to
93// usize depending on chain parameters
94const {
95    assert!(size_of::<usize>() >= size_of::<u64>());
96}
97
98/// Reserve 1M of space for plot metadata (for potential future expansion)
99const RESERVED_PLOT_METADATA: u64 = 1024 * 1024;
100/// [`RESERVED_PLOT_METADATA`] in pages of [`OwnedPages::ALIGN`] bytes
101const RESERVED_PLOT_METADATA_PAGES: u64 = {
102    assert!(RESERVED_PLOT_METADATA.is_multiple_of(OwnedPages::ALIGN as u64));
103    RESERVED_PLOT_METADATA / OwnedPages::ALIGN as u64
104};
105/// Reserve 1M of space for farm info (for potential future expansion)
106const RESERVED_FARM_INFO: u64 = 1024 * 1024;
107const NEW_SEGMENT_PROCESSING_DELAY: Duration = Duration::from_mins(10);
108/// Maximum number of sector metadata entries read from the metadata file at once, about 1 MiB
109const SECTOR_METADATA_READ_BATCH: u16 = {
110    let batch = 1024 * 1024 / SectorMetadataChecksummed::disk_size();
111    assert!(batch > 0 && batch <= u16::MAX as usize);
112    batch as u16
113};
114
115/// Read metadata of `plotted_sector_count` sectors from `metadata_file` in batches of up to
116/// [`SECTOR_METADATA_READ_BATCH`] sectors, calling `process` with each sector index and its bytes
117/// in order
118fn read_sectors_metadata<E, F>(
119    metadata_file: &DirectIoFile,
120    plotted_sector_count: u16,
121    mut process: F,
122) -> Result<(), E>
123where
124    E: From<IoBufError<OwnedPages>>,
125    F: FnMut(SectorIndex, &[u8; SectorMetadataChecksummed::disk_size()]) -> Result<(), E>,
126{
127    let mut batch_bytes = OwnedPages::EMPTY;
128    for first_sector_index in
129        (0..plotted_sector_count).step_by(usize::from(SECTOR_METADATA_READ_BATCH))
130    {
131        let batch_len = SECTOR_METADATA_READ_BATCH.min(plotted_sector_count - first_sector_index);
132        batch_bytes = metadata_file.read_pages_at(
133            batch_bytes,
134            u32::from(batch_len) * SectorMetadataChecksummed::DISK_PAGES,
135            RESERVED_PLOT_METADATA_PAGES
136                + u64::from(SectorMetadataChecksummed::DISK_PAGES) * u64::from(first_sector_index),
137        )?;
138
139        // Whole entries were read, so there is no remainder
140        let (sectors_metadata_bytes, _remainder) = batch_bytes
141            .as_slice()
142            .as_chunks::<{ SectorMetadataChecksummed::disk_size() }>();
143        for (sector_index, sector_metadata_bytes) in
144            (first_sector_index..).zip(sectors_metadata_bytes)
145        {
146            process(SectorIndex::from(sector_index), sector_metadata_bytes)?;
147        }
148    }
149
150    Ok(())
151}
152
153/// Exclusive lock for single disk farm info file, ensuring no concurrent edits by cooperating
154/// processes is done
155#[derive(Debug)]
156#[must_use = "Lock file must be kept around or as long as farm is used"]
157pub struct SingleDiskFarmInfoLock {
158    _file: File,
159}
160
161/// Important information about the contents of the `SingleDiskFarm`
162#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164pub enum SingleDiskFarmInfo {
165    /// V0 of the info
166    #[serde(rename_all = "camelCase")]
167    V0 {
168        /// ID of the farm
169        id: FarmId,
170        /// Genesis root of the beacon chain used for farm creation
171        genesis_root: BlockRoot,
172        /// Public key of identity used for farm creation
173        public_key: Ed25519PublicKey,
174        /// Seed used for deriving shard commitments
175        shard_commitments_seed: Blake3Hash,
176        /// How many pieces does one sector contain.
177        pieces_in_sector: u16,
178        /// How much space in bytes is allocated for this farm
179        allocated_space: u64,
180    },
181}
182
183impl SingleDiskFarmInfo {
184    const FILE_NAME: &'static str = "single_disk_farm.json";
185
186    /// Create a new instance
187    pub fn new(
188        id: FarmId,
189        genesis_root: BlockRoot,
190        public_key: Ed25519PublicKey,
191        shard_commitments_seed: Blake3Hash,
192        pieces_in_sector: u16,
193        allocated_space: u64,
194    ) -> Self {
195        Self::V0 {
196            id,
197            genesis_root,
198            public_key,
199            shard_commitments_seed,
200            pieces_in_sector,
201            allocated_space,
202        }
203    }
204
205    /// Load `SingleDiskFarm` from path is supposed to be stored, `None` means no info file was
206    /// found, happens during first start.
207    pub fn load_from(directory: &Path) -> io::Result<Option<Self>> {
208        let bytes = match fs::read(directory.join(Self::FILE_NAME)) {
209            Ok(bytes) => bytes,
210            Err(error) => {
211                return if error.kind() == io::ErrorKind::NotFound {
212                    Ok(None)
213                } else {
214                    Err(error)
215                };
216            }
217        };
218
219        serde_json::from_slice(&bytes)
220            .map(Some)
221            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
222    }
223
224    /// Store `SingleDiskFarm` info to path, so it can be loaded again upon restart.
225    ///
226    /// Can optionally return a lock.
227    pub fn store_to(
228        &self,
229        directory: &Path,
230        lock: bool,
231    ) -> io::Result<Option<SingleDiskFarmInfoLock>> {
232        let mut file = OpenOptions::new()
233            .write(true)
234            .create(true)
235            .truncate(false)
236            .open(directory.join(Self::FILE_NAME))?;
237        if lock {
238            file.try_lock()?;
239        }
240        file.set_len(0)?;
241        file.write_all(&serde_json::to_vec(self).expect("Info serialization never fails; qed"))?;
242
243        Ok(lock.then_some(SingleDiskFarmInfoLock { _file: file }))
244    }
245
246    /// Try to acquire exclusive lock on the single disk farm info file, ensuring no concurrent
247    /// edits by cooperating processes is done
248    pub fn try_lock(directory: &Path) -> io::Result<SingleDiskFarmInfoLock> {
249        let file = File::open(directory.join(Self::FILE_NAME))?;
250        file.try_lock()?;
251
252        Ok(SingleDiskFarmInfoLock { _file: file })
253    }
254
255    /// ID of the farm
256    #[expect(
257        clippy::rest_pattern_accessible_field,
258        reason = "Do not need other fields"
259    )]
260    pub fn id(&self) -> &FarmId {
261        let Self::V0 { id, .. } = self;
262        id
263    }
264
265    /// Genesis hash of the chain used for farm creation
266    #[expect(
267        clippy::rest_pattern_accessible_field,
268        reason = "Do not need other fields"
269    )]
270    pub fn genesis_root(&self) -> &BlockRoot {
271        let Self::V0 { genesis_root, .. } = self;
272        genesis_root
273    }
274
275    /// Public key of identity used for farm creation
276    #[expect(
277        clippy::rest_pattern_accessible_field,
278        reason = "Do not need other fields"
279    )]
280    pub fn public_key(&self) -> &Ed25519PublicKey {
281        let Self::V0 { public_key, .. } = self;
282        public_key
283    }
284
285    /// Seed used for deriving shard commitments
286    #[expect(
287        clippy::rest_pattern_accessible_field,
288        reason = "Do not need other fields"
289    )]
290    pub fn shard_commitments_seed(&self) -> &Blake3Hash {
291        let Self::V0 {
292            shard_commitments_seed,
293            ..
294        } = self;
295        shard_commitments_seed
296    }
297
298    /// How many pieces does one sector contain
299    #[expect(
300        clippy::rest_pattern_accessible_field,
301        reason = "Do not need other fields"
302    )]
303    pub fn pieces_in_sector(&self) -> u16 {
304        match self {
305            SingleDiskFarmInfo::V0 {
306                pieces_in_sector, ..
307            } => *pieces_in_sector,
308        }
309    }
310
311    /// How much space in bytes is allocated for this farm
312    #[expect(
313        clippy::rest_pattern_accessible_field,
314        reason = "Do not need other fields"
315    )]
316    pub fn allocated_space(&self) -> u64 {
317        match self {
318            SingleDiskFarmInfo::V0 {
319                allocated_space, ..
320            } => *allocated_space,
321        }
322    }
323}
324
325/// Summary of single disk farm for presentational purposes
326#[derive(Debug)]
327pub enum SingleDiskFarmSummary {
328    /// Farm was found and read successfully
329    Found {
330        /// Farm info
331        info: SingleDiskFarmInfo,
332        /// Path to directory where farm is stored.
333        directory: PathBuf,
334    },
335    /// Farm was not found
336    NotFound {
337        /// Path to directory where farm is stored.
338        directory: PathBuf,
339    },
340    /// Failed to open farm
341    Error {
342        /// Path to directory where farm is stored.
343        directory: PathBuf,
344        /// Error itself
345        error: io::Error,
346    },
347}
348
349#[derive(Debug, Encode, Decode)]
350struct PlotMetadataHeader {
351    version: u8,
352    plotted_sector_count: u16,
353}
354
355impl PlotMetadataHeader {
356    /// Encode header into a whole disk page, padded with zeroes, such that it can be written
357    /// without read-modify-write
358    fn encode_page(&self) -> OwnedPages {
359        let mut page = OwnedPages::zeroed(OwnedPages::ALIGN);
360        self.encode_to(&mut page.as_mut_slice());
361        page
362    }
363}
364
365/// Options used to open single disk farm
366#[derive(Debug)]
367pub struct SingleDiskFarmOptions<'a, NC>
368where
369    NC: Clone,
370{
371    /// Path to directory where farm is stored.
372    pub directory: PathBuf,
373    /// Information necessary for farmer application
374    pub farmer_app_info: FarmerAppInfo,
375    /// The amount of space in bytes that was allocated
376    pub allocated_space: u64,
377    /// How many pieces one sector is supposed to contain (max)
378    pub max_pieces_in_sector: u16,
379    /// RPC client connected to the node
380    pub node_client: NC,
381    /// Address where farming rewards should go
382    pub reward_address: Address,
383    /// Plotter
384    pub plotter: StdArc<dyn Plotter + Send + Sync>,
385    /// Erasure coding instance to use.
386    pub erasure_coding: ErasureCoding,
387    /// Percentage of allocated space dedicated for caching purposes
388    pub cache_percentage: u8,
389    /// Thread pool size used for farming (mostly for blocking I/O, but also for some
390    /// compute-intensive operations during proving)
391    pub farming_thread_pool_size: usize,
392    /// Notification for plotter to start, can be used to delay plotting until some initialization
393    /// has happened externally
394    pub plotting_delay: Option<oneshot::Receiver<()>>,
395    /// Global mutex that can restrict concurrency of resource-intensive operations and make sure
396    /// that those operations that are very sensitive (like proving) have all the resources
397    /// available to them for the highest probability of success
398    pub global_mutex: Arc<AsyncMutex<()>>,
399    /// How many sectors a will be plotted concurrently per farm
400    pub max_plotting_sectors_per_farm: NonZeroUsize,
401    /// Disable farm locking, for example if file system doesn't support it
402    pub disable_farm_locking: bool,
403    /// Prometheus registry
404    pub registry: Option<&'a Mutex<&'a mut Registry>>,
405    /// Whether to create a farm if it doesn't yet exist
406    pub create: bool,
407}
408
409/// Errors happening when trying to create/open single disk farm
410#[derive(Debug, Error)]
411pub enum SingleDiskFarmError {
412    /// Failed to open or create identity
413    #[error("Failed to open or create identity: {0}")]
414    FailedToOpenIdentity(#[from] IdentityError),
415    /// Farm is likely already in use, make sure no other farmer is using it
416    #[error("Farm is likely already in use, make sure no other farmer is using it: {0}")]
417    LikelyAlreadyInUse(io::Error),
418    /// I/O error occurred
419    #[error("Single disk farm I/O error: {0}")]
420    Io(#[from] io::Error),
421    /// Failed to spawn task for blocking thread
422    #[error("Failed to spawn task for blocking thread: {0}")]
423    TokioJoinError(#[from] task::JoinError),
424    /// Piece cache error
425    #[error("Piece cache error: {0}")]
426    PieceCacheError(#[from] DiskPieceCacheError),
427    /// Can't preallocate metadata file, probably not enough space on disk
428    #[error("Can't preallocate metadata file, probably not enough space on disk: {0}")]
429    CantPreallocateMetadataFile(io::Error),
430    /// Can't preallocate plot file, probably not enough space on disk
431    #[error("Can't preallocate plot file, probably not enough space on disk: {0}")]
432    CantPreallocatePlotFile(io::Error),
433    /// Wrong chain (genesis hash)
434    #[error(
435        "Genesis hash of farm {id} {wrong_chain} is different from {correct_chain} when farm was \
436        created, it is not possible to use farm on a different chain"
437    )]
438    WrongChain {
439        /// Farm ID
440        id: FarmId,
441        /// Hex-encoded genesis hash during farm creation
442        // TODO: Wrapper type with `Display` impl for genesis hash
443        correct_chain: String,
444        /// Hex-encoded current genesis hash
445        wrong_chain: String,
446    },
447    /// Public key in identity doesn't match metadata
448    #[error(
449        "Public key of farm {id} {wrong_public_key} is different from {correct_public_key} when \
450        farm was created, something went wrong, likely due to manual edits"
451    )]
452    IdentityMismatch {
453        /// Farm ID
454        id: FarmId,
455        /// Public key used during farm creation
456        correct_public_key: Ed25519PublicKey,
457        /// Current public key
458        wrong_public_key: Ed25519PublicKey,
459    },
460    /// Invalid number pieces in sector
461    #[error(
462        "Invalid number pieces in sector: max supported {max_supported}, farm initialized with \
463        {initialized_with}"
464    )]
465    InvalidPiecesInSector {
466        /// Farm ID
467        id: FarmId,
468        /// Max supported pieces in sector
469        max_supported: u16,
470        /// Number of pieces in sector farm is initialized with
471        initialized_with: u16,
472    },
473    /// Failed to decode metadata header
474    #[error("Failed to decode metadata header: {0}")]
475    FailedToDecodeMetadataHeader(parity_scale_codec::Error),
476    /// Unexpected metadata version
477    #[error("Unexpected metadata version {0}")]
478    UnexpectedMetadataVersion(u8),
479    /// Allocated space is not enough for one sector
480    #[error(
481        "Allocated space is not enough for one sector. \
482        The lowest acceptable value for allocated space is {min_space} bytes, \
483        provided {allocated_space} bytes."
484    )]
485    InsufficientAllocatedSpace {
486        /// Minimal allocated space
487        min_space: u64,
488        /// Current allocated space
489        allocated_space: u64,
490    },
491    /// Farm is too large
492    #[error(
493        "Farm is too large: allocated {allocated_sectors} sectors ({allocated_space} bytes), max \
494        supported is {max_sectors} ({max_space} bytes). Consider creating multiple smaller farms \
495        instead."
496    )]
497    FarmTooLarge {
498        /// Allocated space
499        allocated_space: u64,
500        /// Allocated space in sectors
501        allocated_sectors: u64,
502        /// Max supported allocated space
503        max_space: u64,
504        /// Max supported allocated space in sectors
505        max_sectors: u16,
506    },
507    /// Failed to create thread pool
508    #[error("Failed to create thread pool: {0}")]
509    FailedToCreateThreadPool(ThreadPoolBuildError),
510}
511
512impl<B> From<IoBufError<B>> for SingleDiskFarmError {
513    #[inline]
514    fn from(error: IoBufError<B>) -> Self {
515        Self::Io(error.into())
516    }
517}
518
519/// Errors happening during scrubbing
520#[derive(Debug, Error)]
521pub enum SingleDiskFarmScrubError {
522    /// Farm is likely already in use, make sure no other farmer is using it
523    #[error("Farm is likely already in use, make sure no other farmer is using it: {0}")]
524    LikelyAlreadyInUse(io::Error),
525    /// Failed to determine file size
526    #[error("Failed to file size of {file}: {error}")]
527    FailedToDetermineFileSize {
528        /// Affected file
529        file: PathBuf,
530        /// Low-level error
531        error: io::Error,
532    },
533    /// Failed to read bytes from file
534    #[error("Failed to read {size} bytes from {file} at offset {offset}: {error}")]
535    FailedToReadBytes {
536        /// Affected file
537        file: PathBuf,
538        /// Number of bytes to read
539        size: u64,
540        /// Offset in the file
541        offset: u64,
542        /// Low-level error
543        error: io::Error,
544    },
545    /// Failed to write bytes from file
546    #[error("Failed to write {size} bytes from {file} at offset {offset}: {error}")]
547    FailedToWriteBytes {
548        /// Affected file
549        file: PathBuf,
550        /// Number of bytes to read
551        size: u64,
552        /// Offset in the file
553        offset: u64,
554        /// Low-level error
555        error: io::Error,
556    },
557    /// Farm info file does not exist
558    #[error("Farm info file does not exist at {file}")]
559    FarmInfoFileDoesNotExist {
560        /// Info file
561        file: PathBuf,
562    },
563    /// Farm info can't be opened
564    #[error("Farm info at {file} can't be opened: {error}")]
565    FarmInfoCantBeOpened {
566        /// Info file
567        file: PathBuf,
568        /// Low-level error
569        error: io::Error,
570    },
571    /// Identity file does not exist
572    #[error("Identity file does not exist at {file}")]
573    IdentityFileDoesNotExist {
574        /// Identity file
575        file: PathBuf,
576    },
577    /// Identity can't be opened
578    #[error("Identity at {file} can't be opened: {error}")]
579    IdentityCantBeOpened {
580        /// Identity file
581        file: PathBuf,
582        /// Low-level error
583        error: IdentityError,
584    },
585    /// Identity public key doesn't match public key in the disk farm info
586    #[error("Identity public key {identity} doesn't match public key in the disk farm info {info}")]
587    PublicKeyMismatch {
588        /// Identity public key
589        identity: Ed25519PublicKey,
590        /// Disk farm info public key
591        info: Ed25519PublicKey,
592    },
593    /// Metadata file does not exist
594    #[error("Metadata file does not exist at {file}")]
595    MetadataFileDoesNotExist {
596        /// Metadata file
597        file: PathBuf,
598    },
599    /// Metadata can't be opened
600    #[error("Metadata at {file} can't be opened: {error}")]
601    MetadataCantBeOpened {
602        /// Metadata file
603        file: PathBuf,
604        /// Low-level error
605        error: io::Error,
606    },
607    /// Metadata file too small
608    #[error(
609        "Metadata file at {file} is too small: reserved size is {reserved_size} bytes, file size \
610        is {size}"
611    )]
612    MetadataFileTooSmall {
613        /// Metadata file
614        file: PathBuf,
615        /// Reserved size
616        reserved_size: u64,
617        /// File size
618        size: u64,
619    },
620    /// Failed to decode metadata header
621    #[error("Failed to decode metadata header: {0}")]
622    FailedToDecodeMetadataHeader(parity_scale_codec::Error),
623    /// Unexpected metadata version
624    #[error("Unexpected metadata version {0}")]
625    UnexpectedMetadataVersion(u8),
626    /// Cache can't be opened
627    #[error("Cache at {file} can't be opened: {error}")]
628    CacheCantBeOpened {
629        /// Cache file
630        file: PathBuf,
631        /// Low-level error
632        error: io::Error,
633    },
634}
635
636/// Errors that happen in background tasks
637#[derive(Debug, Error)]
638pub enum BackgroundTaskError {
639    /// Plotting error
640    #[error(transparent)]
641    Plotting(#[from] PlottingError),
642    /// Farming error
643    #[error(transparent)]
644    Farming(#[from] FarmingError),
645    /// Block sealing
646    #[error(transparent)]
647    BlockSealing(#[from] anyhow::Error),
648    /// Background task panicked
649    #[error("Background task {task} panicked")]
650    BackgroundTaskPanicked {
651        /// Name of the task
652        task: String,
653    },
654}
655
656type BackgroundTask = Pin<Box<dyn Future<Output = Result<(), BackgroundTaskError>> + Send>>;
657
658/// Scrub target
659#[derive(Debug, Copy, Clone)]
660pub enum ScrubTarget {
661    /// Scrub everything
662    All,
663    /// Scrub just metadata
664    Metadata,
665    /// Scrub metadata and corresponding plot
666    Plot,
667    /// Only scrub cache
668    Cache,
669}
670
671impl fmt::Display for ScrubTarget {
672    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673        match self {
674            Self::All => f.write_str("all"),
675            Self::Metadata => f.write_str("metadata"),
676            Self::Plot => f.write_str("plot"),
677            Self::Cache => f.write_str("cache"),
678        }
679    }
680}
681
682impl FromStr for ScrubTarget {
683    type Err = String;
684
685    fn from_str(s: &str) -> Result<Self, Self::Err> {
686        match s {
687            "all" => Ok(Self::All),
688            "metadata" => Ok(Self::Metadata),
689            "plot" => Ok(Self::Plot),
690            "cache" => Ok(Self::Cache),
691            s => Err(format!("Can't parse {s} as `ScrubTarget`")),
692        }
693    }
694}
695
696impl ScrubTarget {
697    fn metadata(self) -> bool {
698        match self {
699            Self::All | Self::Metadata | Self::Plot => true,
700            Self::Cache => false,
701        }
702    }
703
704    fn plot(self) -> bool {
705        match self {
706            Self::All | Self::Plot => true,
707            Self::Metadata | Self::Cache => false,
708        }
709    }
710
711    fn cache(self) -> bool {
712        match self {
713            Self::All | Self::Cache => true,
714            Self::Metadata | Self::Plot => false,
715        }
716    }
717}
718
719struct AllocatedSpaceDistribution {
720    piece_cache_file_size: u64,
721    piece_cache_capacity: u32,
722    plot_file_size: u64,
723    target_sector_count: u16,
724    metadata_file_size: u64,
725}
726
727impl AllocatedSpaceDistribution {
728    fn new(
729        allocated_space: u64,
730        sector_size: u64,
731        cache_percentage: u8,
732        sector_metadata_size: u64,
733    ) -> Result<Self, SingleDiskFarmError> {
734        let single_sector_overhead = sector_size + sector_metadata_size;
735        // Fixed space usage regardless of plot size
736        let fixed_space_usage = RESERVED_PLOT_METADATA
737            + RESERVED_FARM_INFO
738            + Identity::file_size() as u64
739            + KnownPeersManager::file_size(KNOWN_PEERS_CACHE_SIZE) as u64;
740        // Calculate how many sectors can fit
741        let target_sector_count = {
742            let potentially_plottable_space = allocated_space.saturating_sub(fixed_space_usage)
743                / 100
744                * (100 - u64::from(cache_percentage));
745            // Do the rounding to make sure we have exactly as much space as fits whole number of
746            // sectors, account for disk sector size just in case
747            (potentially_plottable_space - u64::from(OwnedPages::ALIGN)) / single_sector_overhead
748        };
749
750        if target_sector_count == 0 {
751            let mut single_plot_with_cache_space =
752                single_sector_overhead.div_ceil(100 - u64::from(cache_percentage)) * 100;
753            // Cache must not be empty, ensure it contains at least one element even if
754            // percentage-wise it will use more space
755            if single_plot_with_cache_space - single_sector_overhead
756                < u64::from(DiskPieceCache::element_size())
757            {
758                single_plot_with_cache_space =
759                    single_sector_overhead + u64::from(DiskPieceCache::element_size());
760            }
761
762            return Err(SingleDiskFarmError::InsufficientAllocatedSpace {
763                min_space: fixed_space_usage + single_plot_with_cache_space,
764                allocated_space,
765            });
766        }
767        let plot_file_size = target_sector_count * sector_size;
768        // Align plot file size for disk sector size
769        let plot_file_size = plot_file_size.next_multiple_of(u64::from(OwnedPages::ALIGN));
770
771        // Remaining space will be used for caching purposes
772        let piece_cache_capacity = if cache_percentage > 0 {
773            let cache_space = allocated_space
774                - fixed_space_usage
775                - plot_file_size
776                - (sector_metadata_size * target_sector_count);
777            (cache_space / u64::from(DiskPieceCache::element_size())) as u32
778        } else {
779            0
780        };
781        let target_sector_count = match u16::try_from(target_sector_count).map(SectorIndex::from) {
782            Ok(target_sector_count) if target_sector_count < SectorIndex::MAX => {
783                u16::from(target_sector_count)
784            }
785            _ => {
786                // We use `u16` for both count and index, hence index must not reach actual `MAX`
787                // (consensus doesn't care about this, just farmer implementation detail)
788                let max_sectors = u16::from(SectorIndex::MAX) - 1;
789                return Err(SingleDiskFarmError::FarmTooLarge {
790                    allocated_space: target_sector_count * sector_size,
791                    allocated_sectors: target_sector_count,
792                    max_space: u64::from(max_sectors) * sector_size,
793                    max_sectors,
794                });
795            }
796        };
797
798        Ok(Self {
799            piece_cache_file_size: u64::from(piece_cache_capacity)
800                * u64::from(DiskPieceCache::element_size()),
801            piece_cache_capacity,
802            plot_file_size,
803            target_sector_count,
804            metadata_file_size: RESERVED_PLOT_METADATA
805                + sector_metadata_size * u64::from(target_sector_count),
806        })
807    }
808}
809
810type Handler<A> = Bag<HandlerFn<A>, A>;
811
812#[derive(Default, Debug)]
813struct Handlers {
814    sector_update: Handler<(SectorIndex, SectorUpdate)>,
815    farming_notification: Handler<FarmingNotification>,
816    solution: Handler<SolutionResponse>,
817}
818
819struct SingleDiskFarmInit {
820    identity: Identity,
821    single_disk_farm_info: SingleDiskFarmInfo,
822    single_disk_farm_info_lock: Option<SingleDiskFarmInfoLock>,
823    plot_file: StdArc<DirectIoFile>,
824    metadata_file: DirectIoFile,
825    metadata_header: PlotMetadataHeader,
826    target_sector_count: u16,
827    sectors_metadata: StdArc<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
828    piece_cache_capacity: u32,
829    plot_cache: DiskPlotCache,
830}
831
832/// Single disk farm abstraction is a container for everything necessary to plot/farm with a single
833/// disk.
834///
835/// Farm starts operating during creation and doesn't stop until dropped (or error happens).
836#[derive(Debug)]
837#[must_use = "Plot does not function properly unless run() method is called"]
838pub struct SingleDiskFarm {
839    farmer_protocol_info: FarmerProtocolInfo,
840    single_disk_farm_info: SingleDiskFarmInfo,
841    shard_commitments_roots_cache: ShardCommitmentsRootsCache,
842    /// Metadata of all sectors plotted so far
843    sectors_metadata: StdArc<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
844    pieces_in_sector: u16,
845    total_sectors_count: u16,
846    span: Span,
847    tasks: FuturesUnordered<BackgroundTask>,
848    handlers: Arc<Handlers>,
849    piece_cache: SingleDiskPieceCache,
850    plot_cache: DiskPlotCache,
851    piece_reader: DiskPieceReader,
852    /// Sender that will be used to signal to background threads that they should start
853    start_sender: Option<broadcast::Sender<()>>,
854    /// Sender that will be used to signal to background threads that they must stop
855    stop_sender: Option<broadcast::Sender<()>>,
856    _single_disk_farm_info_lock: Option<SingleDiskFarmInfoLock>,
857}
858
859impl Drop for SingleDiskFarm {
860    #[inline]
861    fn drop(&mut self) {
862        self.piece_reader.close_all_readers();
863        // Make background threads that are waiting to do something exit immediately
864        self.start_sender.take();
865        // Notify background tasks that they must stop
866        self.stop_sender.take();
867    }
868}
869
870#[async_trait(?Send)]
871impl Farm for SingleDiskFarm {
872    fn id(&self) -> &FarmId {
873        self.id()
874    }
875
876    fn total_sectors_count(&self) -> u16 {
877        self.total_sectors_count
878    }
879
880    fn plotted_sectors(&self) -> StdArc<dyn PlottedSectors + 'static> {
881        StdArc::new(self.plotted_sectors())
882    }
883
884    fn piece_reader(&self) -> StdArc<dyn PieceReader + 'static> {
885        StdArc::new(self.piece_reader())
886    }
887
888    fn on_sector_update(
889        &self,
890        callback: HandlerFn<(SectorIndex, SectorUpdate)>,
891    ) -> Box<dyn farm::HandlerId> {
892        Box::new(self.on_sector_update(callback))
893    }
894
895    fn on_farming_notification(
896        &self,
897        callback: HandlerFn<FarmingNotification>,
898    ) -> Box<dyn farm::HandlerId> {
899        Box::new(self.on_farming_notification(callback))
900    }
901
902    fn on_solution(&self, callback: HandlerFn<SolutionResponse>) -> Box<dyn farm::HandlerId> {
903        Box::new(self.on_solution(callback))
904    }
905
906    fn run(self: Box<Self>) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {
907        Box::pin((*self).run())
908    }
909}
910
911impl SingleDiskFarm {
912    /// Name of the plot file
913    pub const PLOT_FILE: &'static str = "plot.bin";
914    /// Name of the metadata file
915    pub const METADATA_FILE: &'static str = "metadata.bin";
916    const SUPPORTED_PLOT_VERSION: u8 = 0;
917
918    /// Create new single disk farm instance
919    pub async fn new<NC, PosTable>(
920        options: SingleDiskFarmOptions<'_, NC>,
921        farm_index: usize,
922    ) -> Result<Self, SingleDiskFarmError>
923    where
924        NC: NodeClient + Clone,
925        PosTable: Table,
926    {
927        let span = Span::current();
928
929        let SingleDiskFarmOptions {
930            directory,
931            farmer_app_info,
932            allocated_space,
933            max_pieces_in_sector,
934            node_client,
935            reward_address,
936            plotter,
937            erasure_coding,
938            cache_percentage,
939            farming_thread_pool_size,
940            plotting_delay,
941            global_mutex,
942            max_plotting_sectors_per_farm,
943            disable_farm_locking,
944            registry,
945            create,
946        } = options;
947
948        let single_disk_farm_init_fut = task::spawn_blocking({
949            let directory = directory.clone();
950            let farmer_app_info = farmer_app_info.clone();
951            let span = span.clone();
952
953            move || {
954                let _span_guard = span.enter();
955                Self::init(
956                    &directory,
957                    &farmer_app_info,
958                    allocated_space,
959                    max_pieces_in_sector,
960                    cache_percentage,
961                    disable_farm_locking,
962                    create,
963                )
964            }
965        });
966
967        let single_disk_farm_init =
968            AsyncJoinOnDrop::new(single_disk_farm_init_fut, false).await??;
969
970        let SingleDiskFarmInit {
971            identity,
972            single_disk_farm_info,
973            single_disk_farm_info_lock,
974            plot_file,
975            metadata_file,
976            metadata_header,
977            target_sector_count,
978            sectors_metadata,
979            piece_cache_capacity,
980            plot_cache,
981        } = single_disk_farm_init;
982
983        let piece_cache = {
984            // Convert farm ID into cache ID for single disk farm
985            let FarmId::Ulid(id) = *single_disk_farm_info.id();
986            let id = PieceCacheId::Ulid(id);
987
988            SingleDiskPieceCache::new(
989                id,
990                if let Some(piece_cache_capacity) = NonZeroU32::new(piece_cache_capacity) {
991                    Some(task::block_in_place(|| {
992                        if let Some(registry) = registry {
993                            DiskPieceCache::open(
994                                &directory,
995                                piece_cache_capacity,
996                                Some(id),
997                                Some(*registry.lock()),
998                            )
999                        } else {
1000                            DiskPieceCache::open(&directory, piece_cache_capacity, Some(id), None)
1001                        }
1002                    })?)
1003                } else {
1004                    None
1005                },
1006            )
1007        };
1008
1009        let public_key = *single_disk_farm_info.public_key();
1010        let shard_commitments_roots_cache =
1011            ShardCommitmentsRootsCache::new(*single_disk_farm_info.shard_commitments_seed());
1012        let pieces_in_sector = single_disk_farm_info.pieces_in_sector();
1013        let sector_size = sector_size(pieces_in_sector);
1014
1015        let metrics = registry.map(|registry| {
1016            Arc::new(SingleDiskFarmMetrics::new(
1017                *registry.lock(),
1018                single_disk_farm_info.id(),
1019                target_sector_count,
1020                sectors_metadata.read_blocking().len() as u16,
1021            ))
1022        });
1023
1024        let (error_sender, error_receiver) = oneshot::channel();
1025        let error_sender = Arc::new(Mutex::new(Some(error_sender)));
1026
1027        let tasks = FuturesUnordered::<BackgroundTask>::new();
1028
1029        tasks.push(Box::pin(async move {
1030            if let Ok(error) = error_receiver.await {
1031                return Err(error);
1032            }
1033
1034            Ok(())
1035        }));
1036
1037        let handlers = Arc::<Handlers>::default();
1038        let (start_sender, mut start_receiver) = broadcast::channel::<()>(1);
1039        let (stop_sender, mut stop_receiver) = broadcast::channel::<()>(1);
1040        let sectors_being_modified = Arc::<AsyncRwLock<HashSet<SectorIndex>>>::default();
1041        let (sectors_to_plot_sender, sectors_to_plot_receiver) = mpsc::channel(1);
1042        // Some sectors may already be plotted, skip them
1043        let sectors_indices_left_to_plot = SectorIndex::from(metadata_header.plotted_sector_count)
1044            ..SectorIndex::from(target_sector_count);
1045
1046        let farming_thread_pool = ThreadPoolBuilder::new()
1047            .thread_name(move |thread_index| format!("farming-{farm_index}.{thread_index}"))
1048            .num_threads(farming_thread_pool_size)
1049            .spawn_handler(tokio_rayon_spawn_handler())
1050            .build()
1051            .map_err(SingleDiskFarmError::FailedToCreateThreadPool)?;
1052        let farming_plot_fut = task::spawn_blocking(|| {
1053            farming_thread_pool
1054                .install(move || {
1055                    RayonFiles::open_with(directory.join(Self::PLOT_FILE), |path| {
1056                        let mut open_options = OpenOptions::new();
1057                        open_options
1058                            .read(true)
1059                            .write(true)
1060                            .create(true)
1061                            .truncate(false);
1062                        DirectIoFile::open(open_options, path)
1063                    })
1064                })
1065                .map(|farming_plot| (farming_plot, farming_thread_pool))
1066        });
1067
1068        let (farming_plot, farming_thread_pool) =
1069            AsyncJoinOnDrop::new(farming_plot_fut, false).await??;
1070
1071        let plotting_join_handle = task::spawn_blocking({
1072            let shard_commitments_roots_cache = shard_commitments_roots_cache.clone();
1073            let sectors_metadata = StdArc::clone(&sectors_metadata);
1074            let handlers = Arc::clone(&handlers);
1075            let sectors_being_modified = Arc::clone(&sectors_being_modified);
1076            let node_client = node_client.clone();
1077            let plot_file = StdArc::clone(&plot_file);
1078            let error_sender = Arc::clone(&error_sender);
1079            let span = span.clone();
1080            let global_mutex = Arc::clone(&global_mutex);
1081            let metrics = metrics.clone();
1082
1083            move || {
1084                let _span_guard = span.enter();
1085
1086                let plotting_options = PlottingOptions {
1087                    metadata_header,
1088                    sectors_metadata: &sectors_metadata,
1089                    sectors_being_modified: &sectors_being_modified,
1090                    sectors_to_plot_receiver,
1091                    sector_plotting_options: SectorPlottingOptions {
1092                        public_key,
1093                        shard_commitments_roots_cache,
1094                        node_client: &node_client,
1095                        pieces_in_sector,
1096                        sector_size,
1097                        plot_file,
1098                        metadata_file: Arc::new(metadata_file),
1099                        handlers: &handlers,
1100                        global_mutex: &global_mutex,
1101                        plotter,
1102                        metrics,
1103                    },
1104                    max_plotting_sectors_per_farm,
1105                };
1106
1107                let plotting_fut = async {
1108                    if start_receiver.recv().await.is_err() {
1109                        // Dropped before starting
1110                        return Ok(());
1111                    }
1112
1113                    if let Some(plotting_delay) = plotting_delay
1114                        && plotting_delay.await.is_err()
1115                    {
1116                        // Dropped before resolving
1117                        return Ok(());
1118                    }
1119
1120                    plotting(plotting_options).await
1121                };
1122
1123                Handle::current().block_on(async {
1124                    select! {
1125                        plotting_result = plotting_fut.fuse() => {
1126                            if let Err(error) = plotting_result
1127                                && let Some(error_sender) = error_sender.lock().take()
1128                                && let Err(error) = error_sender.send(error.into())
1129                            {
1130                                error!(
1131                                    %error,
1132                                    "Plotting failed to send error to background task"
1133                                );
1134                            }
1135                        }
1136                        _ = stop_receiver.recv().fuse() => {
1137                            // Nothing, just exit
1138                        }
1139                    }
1140                });
1141            }
1142        });
1143        let plotting_join_handle = AsyncJoinOnDrop::new(plotting_join_handle, false);
1144
1145        tasks.push(Box::pin(async move {
1146            // Panic will already be printed by now
1147            plotting_join_handle.await.map_err(|_error| {
1148                BackgroundTaskError::BackgroundTaskPanicked {
1149                    task: format!("plotting-{farm_index}"),
1150                }
1151            })
1152        }));
1153
1154        let public_key_hash = public_key.hash();
1155
1156        let plotting_scheduler_options = PlottingSchedulerOptions {
1157            public_key_hash,
1158            shard_commitments_roots_cache: shard_commitments_roots_cache.clone(),
1159            sectors_indices_left_to_plot,
1160            target_sector_count,
1161            last_archived_segment_index: farmer_app_info.protocol_info.history_size.segment_index(),
1162            min_sector_lifetime: farmer_app_info.protocol_info.min_sector_lifetime,
1163            node_client: node_client.clone(),
1164            handlers: Arc::clone(&handlers),
1165            sectors_metadata: StdArc::clone(&sectors_metadata),
1166            sectors_to_plot_sender,
1167            new_segment_processing_delay: NEW_SEGMENT_PROCESSING_DELAY,
1168            metrics: metrics.clone(),
1169        };
1170        tasks.push(Box::pin(plotting_scheduler(plotting_scheduler_options)));
1171
1172        let (slot_info_forwarder_sender, slot_info_forwarder_receiver) = mpsc::channel(0);
1173
1174        tasks.push(Box::pin({
1175            let node_client = node_client.clone();
1176            let metrics = metrics.clone();
1177
1178            async move {
1179                slot_notification_forwarder(&node_client, slot_info_forwarder_sender, metrics)
1180                    .await
1181                    .map_err(BackgroundTaskError::Farming)
1182            }
1183        }));
1184
1185        let farming_join_handle = task::spawn_blocking({
1186            let shard_commitments_roots_cache = shard_commitments_roots_cache.clone();
1187            let erasure_coding = erasure_coding.clone();
1188            let handlers = Arc::clone(&handlers);
1189            let sectors_being_modified = Arc::clone(&sectors_being_modified);
1190            let sectors_metadata = StdArc::clone(&sectors_metadata);
1191            let mut start_receiver = start_sender.subscribe();
1192            let mut stop_receiver = stop_sender.subscribe();
1193            let node_client = node_client.clone();
1194            let span = span.clone();
1195            let global_mutex = Arc::clone(&global_mutex);
1196
1197            move || {
1198                let _span_guard = span.enter();
1199
1200                let farming_fut = async move {
1201                    if start_receiver.recv().await.is_err() {
1202                        // Dropped before starting
1203                        return Ok(());
1204                    }
1205
1206                    let plot_audit = PlotAudit::new(&farming_plot);
1207
1208                    let farming_options = FarmingOptions {
1209                        public_key_hash,
1210                        shard_commitments_roots_cache,
1211                        reward_address,
1212                        node_client,
1213                        plot_audit,
1214                        sectors_metadata,
1215                        erasure_coding,
1216                        handlers,
1217                        sectors_being_modified,
1218                        slot_info_notifications: slot_info_forwarder_receiver,
1219                        thread_pool: farming_thread_pool,
1220                        global_mutex,
1221                        metrics,
1222                    };
1223                    farming::<PosTable, _, _>(farming_options).await
1224                };
1225
1226                Handle::current().block_on(async {
1227                    select! {
1228                        farming_result = farming_fut.fuse() => {
1229                            if let Err(error) = farming_result
1230                                && let Some(error_sender) = error_sender.lock().take()
1231                                && let Err(error) = error_sender.send(error.into())
1232                            {
1233                                error!(
1234                                    %error,
1235                                    "Farming failed to send error to background task",
1236                                );
1237                            }
1238                        }
1239                        _ = stop_receiver.recv().fuse() => {
1240                            // Nothing, just exit
1241                        }
1242                    }
1243                });
1244            }
1245        });
1246        let farming_join_handle = AsyncJoinOnDrop::new(farming_join_handle, false);
1247
1248        tasks.push(Box::pin(async move {
1249            // Panic will already be printed by now
1250            farming_join_handle.await.map_err(|_error| {
1251                BackgroundTaskError::BackgroundTaskPanicked {
1252                    task: format!("farming-{farm_index}"),
1253                }
1254            })
1255        }));
1256
1257        let (piece_reader, reading_fut) = DiskPieceReader::new::<PosTable>(
1258            public_key_hash,
1259            shard_commitments_roots_cache.clone(),
1260            pieces_in_sector,
1261            plot_file,
1262            StdArc::clone(&sectors_metadata),
1263            erasure_coding,
1264            sectors_being_modified,
1265            global_mutex,
1266        );
1267
1268        let reading_join_handle = task::spawn_blocking({
1269            let mut stop_receiver = stop_sender.subscribe();
1270            let reading_fut = reading_fut.instrument(span.clone());
1271
1272            move || {
1273                Handle::current().block_on(async {
1274                    select! {
1275                        () = reading_fut.fuse() => {
1276                            // Nothing, just exit
1277                        }
1278                        _ = stop_receiver.recv().fuse() => {
1279                            // Nothing, just exit
1280                        }
1281                    }
1282                });
1283            }
1284        });
1285
1286        let reading_join_handle = AsyncJoinOnDrop::new(reading_join_handle, false);
1287
1288        tasks.push(Box::pin(async move {
1289            // Panic will already be printed by now
1290            reading_join_handle.await.map_err(|_error| {
1291                BackgroundTaskError::BackgroundTaskPanicked {
1292                    task: format!("reading-{farm_index}"),
1293                }
1294            })
1295        }));
1296
1297        tasks.push(Box::pin(async move {
1298            match block_sealing(node_client, identity).await {
1299                Ok(block_sealing_fut) => {
1300                    block_sealing_fut.await;
1301                }
1302                Err(error) => {
1303                    return Err(BackgroundTaskError::BlockSealing(anyhow::anyhow!(
1304                        "Failed to subscribe to block sealing notifications: {error}"
1305                    )));
1306                }
1307            }
1308
1309            Ok(())
1310        }));
1311
1312        let farm = Self {
1313            farmer_protocol_info: farmer_app_info.protocol_info,
1314            single_disk_farm_info,
1315            shard_commitments_roots_cache,
1316            sectors_metadata,
1317            pieces_in_sector,
1318            total_sectors_count: target_sector_count,
1319            span,
1320            tasks,
1321            handlers,
1322            piece_cache,
1323            plot_cache,
1324            piece_reader,
1325            start_sender: Some(start_sender),
1326            stop_sender: Some(stop_sender),
1327            _single_disk_farm_info_lock: single_disk_farm_info_lock,
1328        };
1329        Ok(farm)
1330    }
1331
1332    fn init(
1333        directory: &PathBuf,
1334        farmer_app_info: &FarmerAppInfo,
1335        allocated_space: u64,
1336        max_pieces_in_sector: u16,
1337        cache_percentage: u8,
1338        disable_farm_locking: bool,
1339        create: bool,
1340    ) -> Result<SingleDiskFarmInit, SingleDiskFarmError> {
1341        fs::create_dir_all(directory)?;
1342
1343        let identity = if create {
1344            Identity::open_or_create(directory)?
1345        } else {
1346            Identity::open(directory)?.ok_or_else(|| {
1347                IdentityError::Io(io::Error::new(
1348                    io::ErrorKind::NotFound,
1349                    "Farm does not exist and creation was explicitly disabled",
1350                ))
1351            })?
1352        };
1353        let public_key = identity.public_key();
1354
1355        let (single_disk_farm_info, single_disk_farm_info_lock) = if let Some(
1356            mut single_disk_farm_info,
1357        ) =
1358            SingleDiskFarmInfo::load_from(directory)?
1359        {
1360            if &farmer_app_info.genesis_root != single_disk_farm_info.genesis_root() {
1361                return Err(SingleDiskFarmError::WrongChain {
1362                    id: *single_disk_farm_info.id(),
1363                    correct_chain: hex::encode(single_disk_farm_info.genesis_root()),
1364                    wrong_chain: hex::encode(farmer_app_info.genesis_root),
1365                });
1366            }
1367
1368            if &public_key != single_disk_farm_info.public_key() {
1369                return Err(SingleDiskFarmError::IdentityMismatch {
1370                    id: *single_disk_farm_info.id(),
1371                    correct_public_key: *single_disk_farm_info.public_key(),
1372                    wrong_public_key: public_key,
1373                });
1374            }
1375
1376            let pieces_in_sector = single_disk_farm_info.pieces_in_sector();
1377
1378            if max_pieces_in_sector < pieces_in_sector {
1379                return Err(SingleDiskFarmError::InvalidPiecesInSector {
1380                    id: *single_disk_farm_info.id(),
1381                    max_supported: max_pieces_in_sector,
1382                    initialized_with: pieces_in_sector,
1383                });
1384            }
1385
1386            if max_pieces_in_sector > pieces_in_sector {
1387                info!(
1388                    pieces_in_sector,
1389                    max_pieces_in_sector,
1390                    "Farm initialized with smaller number of pieces in sector, farm needs \
1391                        to be re-created for increase"
1392                );
1393            }
1394
1395            let mut single_disk_farm_info_lock = None;
1396
1397            if allocated_space != single_disk_farm_info.allocated_space() {
1398                info!(
1399                    old_space = %ByteSize::b(single_disk_farm_info.allocated_space()).display().iec(),
1400                    new_space = %ByteSize::b(allocated_space).display().iec(),
1401                    "Farm size has changed"
1402                );
1403
1404                let new_allocated_space = allocated_space;
1405                #[expect(
1406                    clippy::rest_pattern_accessible_field,
1407                    reason = "Do not need other fields"
1408                )]
1409                match &mut single_disk_farm_info {
1410                    SingleDiskFarmInfo::V0 {
1411                        allocated_space, ..
1412                    } => {
1413                        *allocated_space = new_allocated_space;
1414                    }
1415                }
1416
1417                single_disk_farm_info_lock =
1418                    single_disk_farm_info.store_to(directory, !disable_farm_locking)?;
1419            } else if !disable_farm_locking {
1420                single_disk_farm_info_lock = Some(
1421                    SingleDiskFarmInfo::try_lock(directory)
1422                        .map_err(SingleDiskFarmError::LikelyAlreadyInUse)?,
1423                );
1424            }
1425
1426            (single_disk_farm_info, single_disk_farm_info_lock)
1427        } else {
1428            let single_disk_farm_info = SingleDiskFarmInfo::new(
1429                FarmId::new(),
1430                farmer_app_info.genesis_root,
1431                public_key,
1432                identity.shard_commitments_seed(),
1433                max_pieces_in_sector,
1434                allocated_space,
1435            );
1436
1437            let single_disk_farm_info_lock =
1438                single_disk_farm_info.store_to(directory, !disable_farm_locking)?;
1439
1440            (single_disk_farm_info, single_disk_farm_info_lock)
1441        };
1442
1443        let pieces_in_sector = single_disk_farm_info.pieces_in_sector();
1444        let sector_size = sector_size(pieces_in_sector) as u64;
1445        let sector_metadata_size = SectorMetadataChecksummed::disk_size();
1446        let allocated_space_distribution = AllocatedSpaceDistribution::new(
1447            allocated_space,
1448            sector_size,
1449            cache_percentage,
1450            sector_metadata_size as u64,
1451        )?;
1452        let target_sector_count = allocated_space_distribution.target_sector_count;
1453
1454        let metadata_file_path = directory.join(Self::METADATA_FILE);
1455        let mut open_options = OpenOptions::new();
1456        open_options
1457            .read(true)
1458            .write(true)
1459            .create(true)
1460            .truncate(false);
1461        let metadata_file = DirectIoFile::open(open_options.clone(), &metadata_file_path)?;
1462
1463        let metadata_size = metadata_file.len()?;
1464        let expected_metadata_size = allocated_space_distribution.metadata_file_size;
1465        // Align plot file size for disk sector size
1466        let expected_metadata_size =
1467            expected_metadata_size.next_multiple_of(u64::from(OwnedPages::ALIGN));
1468        let metadata_header = if metadata_size == 0 {
1469            let metadata_header = PlotMetadataHeader {
1470                version: SingleDiskFarm::SUPPORTED_PLOT_VERSION,
1471                plotted_sector_count: 0,
1472            };
1473
1474            metadata_file
1475                .file()
1476                .allocate(expected_metadata_size)
1477                .map_err(SingleDiskFarmError::CantPreallocateMetadataFile)?;
1478            metadata_file.write_at(metadata_header.encode_page(), 0)?;
1479
1480            metadata_header
1481        } else {
1482            let metadata_header_page = metadata_file.read_pages_at(OwnedPages::EMPTY, 1, 0)?;
1483
1484            let mut metadata_header =
1485                PlotMetadataHeader::decode(&mut metadata_header_page.as_slice())
1486                    .map_err(SingleDiskFarmError::FailedToDecodeMetadataHeader)?;
1487
1488            // Check version before resizing, such that metadata file of unsupported version is not
1489            // modified
1490            if metadata_header.version != SingleDiskFarm::SUPPORTED_PLOT_VERSION {
1491                return Err(SingleDiskFarmError::UnexpectedMetadataVersion(
1492                    metadata_header.version,
1493                ));
1494            }
1495
1496            if metadata_size != expected_metadata_size {
1497                // Allocating the whole file (`set_len` below can create a sparse file, which will
1498                // cause writes to fail later)
1499                metadata_file
1500                    .file()
1501                    .allocate(expected_metadata_size)
1502                    .map_err(SingleDiskFarmError::CantPreallocateMetadataFile)?;
1503                // Truncating file (if necessary)
1504                metadata_file.set_len(expected_metadata_size)?;
1505            }
1506
1507            if metadata_header.plotted_sector_count > target_sector_count {
1508                metadata_header.plotted_sector_count = target_sector_count;
1509                metadata_file.write_at(metadata_header.encode_page(), 0)?;
1510            }
1511
1512            metadata_header
1513        };
1514
1515        let sectors_metadata = {
1516            let mut sectors_metadata =
1517                Vec::<SectorMetadataChecksummed>::with_capacity(usize::from(target_sector_count));
1518
1519            read_sectors_metadata::<SingleDiskFarmError, _>(
1520                &metadata_file,
1521                metadata_header.plotted_sector_count,
1522                |sector_index, sector_metadata_bytes| {
1523                    let sector_metadata = match SectorMetadataChecksummed::decode_from_disk(
1524                        sector_metadata_bytes,
1525                    ) {
1526                        Ok(sector_metadata) => sector_metadata,
1527                        Err(error) => {
1528                            warn!(
1529                                path = %metadata_file_path.display(),
1530                                %error,
1531                                %sector_index,
1532                                "Failed to decode sector metadata, replacing with dummy expired \
1533                                sector metadata"
1534                            );
1535
1536                            let dummy_sector = SectorMetadataChecksummed::from(SectorMetadata {
1537                                sector_index,
1538                                pieces_in_sector,
1539                                s_bucket_sizes: Box::new([0; Record::NUM_S_BUCKETS]),
1540                                history_size: HistorySize::from(SegmentIndex::ZERO),
1541                            });
1542                            let sector_page_offset = RESERVED_PLOT_METADATA_PAGES
1543                                + u64::from(SectorMetadataChecksummed::DISK_PAGES)
1544                                    * u64::from(sector_index);
1545                            metadata_file.write_at(
1546                                dummy_sector.encode_for_disk(),
1547                                sector_page_offset * u64::from(OwnedPages::ALIGN),
1548                            )?;
1549
1550                            dummy_sector
1551                        }
1552                    };
1553                    sectors_metadata.push(sector_metadata);
1554
1555                    Ok(())
1556                },
1557            )?;
1558
1559            StdArc::new(AsyncRwLock::new(sectors_metadata))
1560        };
1561
1562        let plot_file = DirectIoFile::open(open_options, directory.join(Self::PLOT_FILE))?;
1563
1564        if plot_file.len()? != allocated_space_distribution.plot_file_size {
1565            // Allocating the whole file (`set_len` below can create a sparse file, which will cause
1566            // writes to fail later)
1567            plot_file
1568                .file()
1569                .allocate(allocated_space_distribution.plot_file_size)
1570                .map_err(SingleDiskFarmError::CantPreallocatePlotFile)?;
1571            // Truncating file (if necessary)
1572            plot_file.set_len(allocated_space_distribution.plot_file_size)?;
1573        }
1574
1575        let plot_file = StdArc::new(plot_file);
1576
1577        let plot_cache = DiskPlotCache::new(
1578            &plot_file,
1579            &sectors_metadata,
1580            target_sector_count,
1581            sector_size,
1582        );
1583
1584        Ok(SingleDiskFarmInit {
1585            identity,
1586            single_disk_farm_info,
1587            single_disk_farm_info_lock,
1588            plot_file,
1589            metadata_file,
1590            metadata_header,
1591            target_sector_count,
1592            sectors_metadata,
1593            piece_cache_capacity: allocated_space_distribution.piece_cache_capacity,
1594            plot_cache,
1595        })
1596    }
1597
1598    /// Collect summary of single disk farm for presentational purposes
1599    pub fn collect_summary(directory: PathBuf) -> SingleDiskFarmSummary {
1600        let single_disk_farm_info = match SingleDiskFarmInfo::load_from(&directory) {
1601            Ok(Some(single_disk_farm_info)) => single_disk_farm_info,
1602            Ok(None) => {
1603                return SingleDiskFarmSummary::NotFound { directory };
1604            }
1605            Err(error) => {
1606                return SingleDiskFarmSummary::Error { directory, error };
1607            }
1608        };
1609
1610        SingleDiskFarmSummary::Found {
1611            info: single_disk_farm_info,
1612            directory,
1613        }
1614    }
1615
1616    /// Effective on-disk allocation of the files related to the farm (takes some buffer space
1617    /// into consideration).
1618    ///
1619    /// This is a helpful number in case some files were not allocated properly or were removed and
1620    /// do not correspond to allocated space in the farm info accurately.
1621    pub fn effective_disk_usage(
1622        directory: &Path,
1623        cache_percentage: u8,
1624    ) -> Result<u64, SingleDiskFarmError> {
1625        let mut effective_disk_usage;
1626        match SingleDiskFarmInfo::load_from(directory)? {
1627            Some(single_disk_farm_info) => {
1628                let allocated_space_distribution = AllocatedSpaceDistribution::new(
1629                    single_disk_farm_info.allocated_space(),
1630                    sector_size(single_disk_farm_info.pieces_in_sector()) as u64,
1631                    cache_percentage,
1632                    SectorMetadataChecksummed::disk_size() as u64,
1633                )?;
1634
1635                effective_disk_usage = single_disk_farm_info.allocated_space();
1636                effective_disk_usage -= Identity::file_size() as u64;
1637                effective_disk_usage -= allocated_space_distribution.metadata_file_size;
1638                effective_disk_usage -= allocated_space_distribution.plot_file_size;
1639                effective_disk_usage -= allocated_space_distribution.piece_cache_file_size;
1640            }
1641            None => {
1642                // No farm info, try to collect actual file sizes is any
1643                effective_disk_usage = 0;
1644            }
1645        }
1646
1647        if Identity::open(directory)?.is_some() {
1648            effective_disk_usage += Identity::file_size() as u64;
1649        }
1650
1651        match OpenOptions::new()
1652            .read(true)
1653            .open(directory.join(Self::METADATA_FILE))
1654        {
1655            Ok(metadata_file) => {
1656                effective_disk_usage += metadata_file.size()?;
1657            }
1658            Err(error) => {
1659                if error.kind() == io::ErrorKind::NotFound {
1660                    // File is not stored on disk
1661                } else {
1662                    return Err(error.into());
1663                }
1664            }
1665        }
1666
1667        match OpenOptions::new()
1668            .read(true)
1669            .open(directory.join(Self::PLOT_FILE))
1670        {
1671            Ok(plot_file) => {
1672                effective_disk_usage += plot_file.size()?;
1673            }
1674            Err(error) => {
1675                if error.kind() == io::ErrorKind::NotFound {
1676                    // File is not stored on disk
1677                } else {
1678                    return Err(error.into());
1679                }
1680            }
1681        }
1682
1683        match OpenOptions::new()
1684            .read(true)
1685            .open(directory.join(DiskPieceCache::FILE_NAME))
1686        {
1687            Ok(piece_cache) => {
1688                effective_disk_usage += piece_cache.size()?;
1689            }
1690            Err(error) => {
1691                if error.kind() == io::ErrorKind::NotFound {
1692                    // File is not stored on disk
1693                } else {
1694                    return Err(error.into());
1695                }
1696            }
1697        }
1698
1699        Ok(effective_disk_usage)
1700    }
1701
1702    /// Read all sectors metadata
1703    pub fn read_all_sectors_metadata(
1704        directory: &Path,
1705    ) -> io::Result<Vec<SectorMetadataChecksummed>> {
1706        let mut open_options = OpenOptions::new();
1707        open_options
1708            .read(true)
1709            .write(true)
1710            .create(true)
1711            .truncate(false);
1712        let metadata_file = DirectIoFile::open(open_options, directory.join(Self::METADATA_FILE))?;
1713
1714        let metadata_size = metadata_file.len()?;
1715        let sector_metadata_size = SectorMetadataChecksummed::disk_size();
1716
1717        let metadata_header_page = metadata_file.read_pages_at(OwnedPages::EMPTY, 1, 0)?;
1718
1719        let metadata_header = PlotMetadataHeader::decode(&mut metadata_header_page.as_slice())
1720            .map_err(|error| {
1721                io::Error::other(format!("Failed to decode metadata header: {error}"))
1722            })?;
1723
1724        if metadata_header.version != SingleDiskFarm::SUPPORTED_PLOT_VERSION {
1725            return Err(io::Error::other(format!(
1726                "Unsupported metadata version {}",
1727                metadata_header.version
1728            )));
1729        }
1730
1731        let mut sectors_metadata = Vec::<SectorMetadataChecksummed>::with_capacity(
1732            ((metadata_size - RESERVED_PLOT_METADATA) / sector_metadata_size as u64) as usize,
1733        );
1734
1735        read_sectors_metadata::<io::Error, _>(
1736            &metadata_file,
1737            metadata_header.plotted_sector_count,
1738            |_sector_index, sector_metadata_bytes| {
1739                sectors_metadata.push(
1740                    SectorMetadataChecksummed::decode_from_disk(sector_metadata_bytes).map_err(
1741                        |error| {
1742                            io::Error::other(format!("Failed to decode sector metadata: {error}"))
1743                        },
1744                    )?,
1745                );
1746
1747                Ok(())
1748            },
1749        )?;
1750
1751        Ok(sectors_metadata)
1752    }
1753
1754    /// ID of this farm
1755    pub fn id(&self) -> &FarmId {
1756        self.single_disk_farm_info.id()
1757    }
1758
1759    /// Info of this farm
1760    pub fn info(&self) -> &SingleDiskFarmInfo {
1761        &self.single_disk_farm_info
1762    }
1763
1764    /// Number of sectors in this farm
1765    pub fn total_sectors_count(&self) -> u16 {
1766        self.total_sectors_count
1767    }
1768
1769    /// Read information about sectors plotted so far
1770    pub fn plotted_sectors(&self) -> SingleDiskPlottedSectors {
1771        SingleDiskPlottedSectors {
1772            public_key_hash: self.single_disk_farm_info.public_key().hash(),
1773            shard_commitments_roots_cache: self.shard_commitments_roots_cache.clone(),
1774            pieces_in_sector: self.pieces_in_sector,
1775            farmer_protocol_info: self.farmer_protocol_info,
1776            sectors_metadata: StdArc::clone(&self.sectors_metadata),
1777        }
1778    }
1779
1780    /// Get piece cache instance
1781    pub fn piece_cache(&self) -> SingleDiskPieceCache {
1782        self.piece_cache.clone()
1783    }
1784
1785    /// Get plot cache instance
1786    pub fn plot_cache(&self) -> DiskPlotCache {
1787        self.plot_cache.clone()
1788    }
1789
1790    /// Get piece reader to read plotted pieces later
1791    pub fn piece_reader(&self) -> DiskPieceReader {
1792        self.piece_reader.clone()
1793    }
1794
1795    /// Subscribe to sector updates
1796    pub fn on_sector_update(&self, callback: HandlerFn<(SectorIndex, SectorUpdate)>) -> HandlerId {
1797        self.handlers.sector_update.add(callback)
1798    }
1799
1800    /// Subscribe to farming notifications
1801    pub fn on_farming_notification(&self, callback: HandlerFn<FarmingNotification>) -> HandlerId {
1802        self.handlers.farming_notification.add(callback)
1803    }
1804
1805    /// Subscribe to new solution notification
1806    pub fn on_solution(&self, callback: HandlerFn<SolutionResponse>) -> HandlerId {
1807        self.handlers.solution.add(callback)
1808    }
1809
1810    /// Run and wait for background threads to exit or return an error
1811    pub async fn run(mut self) -> anyhow::Result<()> {
1812        if let Some(start_sender) = self.start_sender.take() {
1813            // Do not care if anyone is listening on the other side
1814            let _: Result<_, _> = start_sender.send(());
1815        }
1816
1817        while let Some(result) = self.tasks.next().instrument(self.span.clone()).await {
1818            result?;
1819        }
1820
1821        Ok(())
1822    }
1823
1824    /// Wipe everything that belongs to this single disk farm
1825    pub fn wipe(directory: &Path) -> io::Result<()> {
1826        let single_disk_info_info_path = directory.join(SingleDiskFarmInfo::FILE_NAME);
1827        match SingleDiskFarmInfo::load_from(directory) {
1828            Ok(Some(single_disk_farm_info)) => {
1829                info!("Found single disk farm {}", single_disk_farm_info.id());
1830            }
1831            Ok(None) => {
1832                return Err(io::Error::new(
1833                    io::ErrorKind::NotFound,
1834                    format!(
1835                        "Single disk farm info not found at {}",
1836                        single_disk_info_info_path.display()
1837                    ),
1838                ));
1839            }
1840            Err(error) => {
1841                warn!("Found unknown single disk farm: {}", error);
1842            }
1843        }
1844
1845        {
1846            let plot = directory.join(Self::PLOT_FILE);
1847            if plot.exists() {
1848                info!("Deleting plot file at {}", plot.display());
1849                fs::remove_file(plot)?;
1850            }
1851        }
1852        {
1853            let metadata = directory.join(Self::METADATA_FILE);
1854            if metadata.exists() {
1855                info!("Deleting metadata file at {}", metadata.display());
1856                fs::remove_file(metadata)?;
1857            }
1858        }
1859        // TODO: Identity should be able to wipe itself instead of assuming a specific file name
1860        //  here
1861        {
1862            let identity = directory.join("identity.bin");
1863            if identity.exists() {
1864                info!("Deleting identity file at {}", identity.display());
1865                fs::remove_file(identity)?;
1866            }
1867        }
1868
1869        DiskPieceCache::wipe(directory)?;
1870
1871        info!(
1872            "Deleting info file at {}",
1873            single_disk_info_info_path.display()
1874        );
1875        fs::remove_file(single_disk_info_info_path)
1876    }
1877
1878    /// Check the farm for corruption and repair errors (caused by disk errors or something else),
1879    /// returns an error when irrecoverable errors occur.
1880    pub fn scrub(
1881        directory: &Path,
1882        disable_farm_locking: bool,
1883        target: ScrubTarget,
1884        dry_run: bool,
1885    ) -> Result<(), SingleDiskFarmScrubError> {
1886        let span = Span::current();
1887
1888        if dry_run {
1889            info!("Dry run is used, no changes will be written to disk");
1890        }
1891
1892        if target.metadata() || target.plot() {
1893            let info = {
1894                let file = directory.join(SingleDiskFarmInfo::FILE_NAME);
1895                info!(path = %file.display(), "Checking info file");
1896
1897                match SingleDiskFarmInfo::load_from(directory) {
1898                    Ok(Some(info)) => info,
1899                    Ok(None) => {
1900                        return Err(SingleDiskFarmScrubError::FarmInfoFileDoesNotExist { file });
1901                    }
1902                    Err(error) => {
1903                        return Err(SingleDiskFarmScrubError::FarmInfoCantBeOpened { file, error });
1904                    }
1905                }
1906            };
1907
1908            let _single_disk_farm_info_lock = if disable_farm_locking {
1909                None
1910            } else {
1911                Some(
1912                    SingleDiskFarmInfo::try_lock(directory)
1913                        .map_err(SingleDiskFarmScrubError::LikelyAlreadyInUse)?,
1914                )
1915            };
1916
1917            let identity = {
1918                let file = directory.join(Identity::FILE_NAME);
1919                info!(path = %file.display(), "Checking identity file");
1920
1921                match Identity::open(directory) {
1922                    Ok(Some(identity)) => identity,
1923                    Ok(None) => {
1924                        return Err(SingleDiskFarmScrubError::IdentityFileDoesNotExist { file });
1925                    }
1926                    Err(error) => {
1927                        return Err(SingleDiskFarmScrubError::IdentityCantBeOpened { file, error });
1928                    }
1929                }
1930            };
1931
1932            if &identity.public_key() != info.public_key() {
1933                return Err(SingleDiskFarmScrubError::PublicKeyMismatch {
1934                    identity: identity.public_key(),
1935                    info: *info.public_key(),
1936                });
1937            }
1938
1939            let sector_metadata_size = SectorMetadataChecksummed::disk_size();
1940
1941            let metadata_file_path = directory.join(Self::METADATA_FILE);
1942            let (metadata_file, mut metadata_header) = {
1943                info!(path = %metadata_file_path.display(), "Checking metadata file");
1944
1945                let metadata_file = match OpenOptions::new()
1946                    .read(true)
1947                    .write(!dry_run)
1948                    .open(&metadata_file_path)
1949                {
1950                    Ok(metadata_file) => metadata_file,
1951                    Err(error) => {
1952                        return Err(if error.kind() == io::ErrorKind::NotFound {
1953                            SingleDiskFarmScrubError::MetadataFileDoesNotExist {
1954                                file: metadata_file_path,
1955                            }
1956                        } else {
1957                            SingleDiskFarmScrubError::MetadataCantBeOpened {
1958                                file: metadata_file_path,
1959                                error,
1960                            }
1961                        });
1962                    }
1963                };
1964
1965                // Error doesn't matter here
1966                let _: Result<(), _> = metadata_file.advise_sequential_access();
1967
1968                let metadata_size = match metadata_file.size() {
1969                    Ok(metadata_size) => metadata_size,
1970                    Err(error) => {
1971                        return Err(SingleDiskFarmScrubError::FailedToDetermineFileSize {
1972                            file: metadata_file_path,
1973                            error,
1974                        });
1975                    }
1976                };
1977
1978                if metadata_size < RESERVED_PLOT_METADATA {
1979                    return Err(SingleDiskFarmScrubError::MetadataFileTooSmall {
1980                        file: metadata_file_path,
1981                        reserved_size: RESERVED_PLOT_METADATA,
1982                        size: metadata_size,
1983                    });
1984                }
1985
1986                let mut metadata_header = {
1987                    let mut reserved_metadata = vec![0; RESERVED_PLOT_METADATA as usize];
1988
1989                    if let Err(error) = metadata_file.read_exact_at(&mut reserved_metadata, 0) {
1990                        return Err(SingleDiskFarmScrubError::FailedToReadBytes {
1991                            file: metadata_file_path,
1992                            size: RESERVED_PLOT_METADATA,
1993                            offset: 0,
1994                            error,
1995                        });
1996                    }
1997
1998                    PlotMetadataHeader::decode(&mut reserved_metadata.as_slice())
1999                        .map_err(SingleDiskFarmScrubError::FailedToDecodeMetadataHeader)?
2000                };
2001
2002                if metadata_header.version != SingleDiskFarm::SUPPORTED_PLOT_VERSION {
2003                    return Err(SingleDiskFarmScrubError::UnexpectedMetadataVersion(
2004                        metadata_header.version,
2005                    ));
2006                }
2007
2008                let plotted_sector_count = metadata_header.plotted_sector_count;
2009
2010                let expected_metadata_size = RESERVED_PLOT_METADATA
2011                    + sector_metadata_size as u64 * u64::from(plotted_sector_count);
2012
2013                if metadata_size < expected_metadata_size {
2014                    warn!(
2015                        %metadata_size,
2016                        %expected_metadata_size,
2017                        "Metadata file size is smaller than expected, shrinking number of plotted \
2018                        sectors to correct value"
2019                    );
2020
2021                    metadata_header.plotted_sector_count =
2022                        ((metadata_size - RESERVED_PLOT_METADATA) / sector_metadata_size as u64)
2023                            as u16;
2024                    let metadata_header_bytes = metadata_header.encode_page();
2025
2026                    if !dry_run
2027                        && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0)
2028                    {
2029                        return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
2030                            file: metadata_file_path,
2031                            size: u64::from(metadata_header_bytes.len()),
2032                            offset: 0,
2033                            error,
2034                        });
2035                    }
2036                }
2037
2038                (metadata_file, metadata_header)
2039            };
2040
2041            let pieces_in_sector = info.pieces_in_sector();
2042            let sector_size = sector_size(pieces_in_sector) as u64;
2043
2044            let plot_file_path = directory.join(Self::PLOT_FILE);
2045            let plot_file = {
2046                let plot_file_path = directory.join(Self::PLOT_FILE);
2047                info!(path = %plot_file_path.display(), "Checking plot file");
2048
2049                let plot_file = match OpenOptions::new()
2050                    .read(true)
2051                    .write(!dry_run)
2052                    .open(&plot_file_path)
2053                {
2054                    Ok(plot_file) => plot_file,
2055                    Err(error) => {
2056                        return Err(if error.kind() == io::ErrorKind::NotFound {
2057                            SingleDiskFarmScrubError::MetadataFileDoesNotExist {
2058                                file: plot_file_path,
2059                            }
2060                        } else {
2061                            SingleDiskFarmScrubError::MetadataCantBeOpened {
2062                                file: plot_file_path,
2063                                error,
2064                            }
2065                        });
2066                    }
2067                };
2068
2069                // Error doesn't matter here
2070                let _: Result<(), _> = plot_file.advise_sequential_access();
2071
2072                let plot_size = match plot_file.size() {
2073                    Ok(metadata_size) => metadata_size,
2074                    Err(error) => {
2075                        return Err(SingleDiskFarmScrubError::FailedToDetermineFileSize {
2076                            file: plot_file_path,
2077                            error,
2078                        });
2079                    }
2080                };
2081
2082                let min_expected_plot_size =
2083                    u64::from(metadata_header.plotted_sector_count) * sector_size;
2084                if plot_size < min_expected_plot_size {
2085                    warn!(
2086                        %plot_size,
2087                        %min_expected_plot_size,
2088                        "Plot file size is smaller than expected, shrinking number of plotted \
2089                        sectors to correct value"
2090                    );
2091
2092                    metadata_header.plotted_sector_count = (plot_size / sector_size) as u16;
2093                    let metadata_header_bytes = metadata_header.encode_page();
2094
2095                    if !dry_run
2096                        && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0)
2097                    {
2098                        return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
2099                            file: plot_file_path,
2100                            size: u64::from(metadata_header_bytes.len()),
2101                            offset: 0,
2102                            error,
2103                        });
2104                    }
2105                }
2106
2107                plot_file
2108            };
2109
2110            let sector_bytes_range = 0..(sector_size as usize - Blake3Hash::SIZE);
2111
2112            info!("Checking sectors and corresponding metadata");
2113            (0..metadata_header.plotted_sector_count)
2114                .into_par_iter()
2115                .map(SectorIndex::from)
2116                .map_init(
2117                    || vec![0u8; Record::SIZE],
2118                    |scratch_buffer, sector_index| {
2119                        let _span_guard = span.enter();
2120
2121                        let offset = RESERVED_PLOT_METADATA
2122                            + u64::from(sector_index) * sector_metadata_size as u64;
2123                        if let Err(error) = metadata_file
2124                            .read_exact_at(&mut scratch_buffer[..sector_metadata_size], offset)
2125                        {
2126                            warn!(
2127                                path = %metadata_file_path.display(),
2128                                %error,
2129                                %offset,
2130                                size = %sector_metadata_size,
2131                                %sector_index,
2132                                "Failed to read sector metadata, replacing with dummy expired \
2133                                sector metadata"
2134                            );
2135
2136                            if !dry_run {
2137                                write_dummy_sector_metadata(
2138                                    &metadata_file,
2139                                    &metadata_file_path,
2140                                    sector_index,
2141                                    pieces_in_sector,
2142                                )?;
2143                            }
2144                            return Ok(());
2145                        }
2146
2147                        let sector_metadata = match SectorMetadataChecksummed::decode_from_disk(
2148                            scratch_buffer
2149                                .first_chunk()
2150                                .expect("Scratch buffer is larger than sector metadata; qed"),
2151                        ) {
2152                            Ok(sector_metadata) => sector_metadata,
2153                            Err(error) => {
2154                                warn!(
2155                                    path = %metadata_file_path.display(),
2156                                    %error,
2157                                    %sector_index,
2158                                    "Failed to decode sector metadata, replacing with dummy \
2159                                    expired sector metadata"
2160                                );
2161
2162                                if !dry_run {
2163                                    write_dummy_sector_metadata(
2164                                        &metadata_file,
2165                                        &metadata_file_path,
2166                                        sector_index,
2167                                        pieces_in_sector,
2168                                    )?;
2169                                }
2170                                return Ok(());
2171                            }
2172                        };
2173
2174                        if sector_metadata.sector_index != sector_index {
2175                            warn!(
2176                                path = %metadata_file_path.display(),
2177                                %sector_index,
2178                                found_sector_index = %sector_metadata.sector_index,
2179                                "Sector index mismatch, replacing with dummy expired sector \
2180                                metadata"
2181                            );
2182
2183                            if !dry_run {
2184                                write_dummy_sector_metadata(
2185                                    &metadata_file,
2186                                    &metadata_file_path,
2187                                    sector_index,
2188                                    pieces_in_sector,
2189                                )?;
2190                            }
2191                            return Ok(());
2192                        }
2193
2194                        if sector_metadata.pieces_in_sector != pieces_in_sector {
2195                            warn!(
2196                                path = %metadata_file_path.display(),
2197                                %sector_index,
2198                                %pieces_in_sector,
2199                                found_pieces_in_sector = sector_metadata.pieces_in_sector,
2200                                "Pieces in sector mismatch, replacing with dummy expired sector \
2201                                metadata"
2202                            );
2203
2204                            if !dry_run {
2205                                write_dummy_sector_metadata(
2206                                    &metadata_file,
2207                                    &metadata_file_path,
2208                                    sector_index,
2209                                    pieces_in_sector,
2210                                )?;
2211                            }
2212                            return Ok(());
2213                        }
2214
2215                        if target.plot() {
2216                            let mut hasher = blake3::Hasher::new();
2217                            // Read sector bytes and compute checksum
2218                            for offset_in_sector in
2219                                sector_bytes_range.clone().step_by(scratch_buffer.len())
2220                            {
2221                                let offset =
2222                                    u64::from(sector_index) * sector_size + offset_in_sector as u64;
2223                                let bytes_to_read = (offset_in_sector + scratch_buffer.len())
2224                                    .min(sector_bytes_range.end)
2225                                    - offset_in_sector;
2226
2227                                let bytes = &mut scratch_buffer[..bytes_to_read];
2228
2229                                if let Err(error) = plot_file.read_exact_at(bytes, offset) {
2230                                    warn!(
2231                                        path = %plot_file_path.display(),
2232                                        %error,
2233                                        %sector_index,
2234                                        %offset,
2235                                        size = %bytes.len() as u64,
2236                                        "Failed to read sector bytes"
2237                                    );
2238
2239                                    continue;
2240                                }
2241
2242                                hasher.update(bytes);
2243                            }
2244
2245                            let actual_checksum = *hasher.finalize().as_bytes();
2246                            let mut expected_checksum = [0; Blake3Hash::SIZE];
2247                            {
2248                                let offset = u64::from(sector_index) * sector_size
2249                                    + sector_bytes_range.end as u64;
2250                                if let Err(error) =
2251                                    plot_file.read_exact_at(&mut expected_checksum, offset)
2252                                {
2253                                    warn!(
2254                                        path = %plot_file_path.display(),
2255                                        %error,
2256                                        %sector_index,
2257                                        %offset,
2258                                        size = %expected_checksum.len() as u64,
2259                                        "Failed to read sector checksum bytes"
2260                                    );
2261                                }
2262                            }
2263
2264                            // Verify checksum
2265                            if actual_checksum != expected_checksum {
2266                                warn!(
2267                                    path = %plot_file_path.display(),
2268                                    %sector_index,
2269                                    actual_checksum = %hex::encode(actual_checksum),
2270                                    expected_checksum = %hex::encode(expected_checksum),
2271                                    "Plotted sector checksum mismatch, replacing with dummy \
2272                                    expired sector"
2273                                );
2274
2275                                if !dry_run {
2276                                    write_dummy_sector_metadata(
2277                                        &metadata_file,
2278                                        &metadata_file_path,
2279                                        sector_index,
2280                                        pieces_in_sector,
2281                                    )?;
2282                                }
2283
2284                                scratch_buffer.fill(0);
2285
2286                                hasher.reset();
2287                                // Fill sector with zeroes and compute checksum
2288                                for offset_in_sector in
2289                                    sector_bytes_range.clone().step_by(scratch_buffer.len())
2290                                {
2291                                    let offset = u64::from(sector_index) * sector_size
2292                                        + offset_in_sector as u64;
2293                                    let bytes_to_write = (offset_in_sector + scratch_buffer.len())
2294                                        .min(sector_bytes_range.end)
2295                                        - offset_in_sector;
2296                                    let bytes = &mut scratch_buffer[..bytes_to_write];
2297
2298                                    if !dry_run
2299                                        && let Err(error) = plot_file.write_all_at(bytes, offset)
2300                                    {
2301                                        return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
2302                                            file: plot_file_path.clone(),
2303                                            size: scratch_buffer.len() as u64,
2304                                            offset,
2305                                            error,
2306                                        });
2307                                    }
2308
2309                                    hasher.update(bytes);
2310                                }
2311                                // Write checksum
2312                                {
2313                                    let checksum = *hasher.finalize().as_bytes();
2314                                    let offset = u64::from(sector_index) * sector_size
2315                                        + sector_bytes_range.end as u64;
2316                                    if !dry_run
2317                                        && let Err(error) =
2318                                            plot_file.write_all_at(&checksum, offset)
2319                                    {
2320                                        return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
2321                                            file: plot_file_path.clone(),
2322                                            size: checksum.len() as u64,
2323                                            offset,
2324                                            error,
2325                                        });
2326                                    }
2327                                }
2328
2329                                return Ok(());
2330                            }
2331                        }
2332
2333                        trace!(%sector_index, "Sector is in good shape");
2334
2335                        Ok(())
2336                    },
2337                )
2338                .try_for_each({
2339                    let span = &span;
2340                    let checked_sectors = AtomicUsize::new(0);
2341
2342                    move |result| {
2343                        let _span_guard = span.enter();
2344
2345                        let checked_sectors = checked_sectors.fetch_add(1, Ordering::Relaxed);
2346                        if checked_sectors > 1 && checked_sectors.is_multiple_of(10) {
2347                            info!(
2348                                "Checked {}/{} sectors",
2349                                checked_sectors, metadata_header.plotted_sector_count
2350                            );
2351                        }
2352
2353                        result
2354                    }
2355                })?;
2356        }
2357
2358        if target.cache() {
2359            Self::scrub_cache(directory, dry_run)?;
2360        }
2361
2362        info!("Farm check completed");
2363
2364        Ok(())
2365    }
2366
2367    fn scrub_cache(directory: &Path, dry_run: bool) -> Result<(), SingleDiskFarmScrubError> {
2368        let span = Span::current();
2369
2370        let file = directory.join(DiskPieceCache::FILE_NAME);
2371        info!(path = %file.display(), "Checking cache file");
2372
2373        let cache_file = match OpenOptions::new().read(true).write(!dry_run).open(&file) {
2374            Ok(plot_file) => plot_file,
2375            Err(error) => {
2376                return if error.kind() == io::ErrorKind::NotFound {
2377                    warn!(
2378                        file = %file.display(),
2379                        "Cache file does not exist, this is expected in farming cluster"
2380                    );
2381                    Ok(())
2382                } else {
2383                    Err(SingleDiskFarmScrubError::CacheCantBeOpened { file, error })
2384                };
2385            }
2386        };
2387
2388        // Error doesn't matter here
2389        let _: Result<(), _> = cache_file.advise_sequential_access();
2390
2391        let cache_size = match cache_file.size() {
2392            Ok(cache_size) => cache_size,
2393            Err(error) => {
2394                return Err(SingleDiskFarmScrubError::FailedToDetermineFileSize { file, error });
2395            }
2396        };
2397
2398        let element_size = DiskPieceCache::element_size();
2399        let number_of_cached_elements = cache_size / u64::from(element_size);
2400        let dummy_element = vec![0; element_size as usize];
2401        (0..number_of_cached_elements)
2402            .into_par_iter()
2403            .map_with(vec![0; element_size as usize], |element, cache_offset| {
2404                let _span_guard = span.enter();
2405
2406                let offset = cache_offset * u64::from(element_size);
2407                if let Err(error) = cache_file.read_exact_at(element, offset) {
2408                    warn!(
2409                        path = %file.display(),
2410                        %cache_offset,
2411                        size = %element.len() as u64,
2412                        %offset,
2413                        %error,
2414                        "Failed to read cached piece, replacing with dummy element"
2415                    );
2416
2417                    if !dry_run && let Err(error) = cache_file.write_all_at(&dummy_element, offset)
2418                    {
2419                        return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
2420                            file: file.clone(),
2421                            size: u64::from(element_size),
2422                            offset,
2423                            error,
2424                        });
2425                    }
2426
2427                    return Ok(());
2428                }
2429
2430                let (index_and_piece_bytes, remaining_bytes) =
2431                    element.split_at(PieceIndex::SIZE + Piece::SIZE);
2432                // The rest of the element after the checksum is zero padding
2433                let (expected_checksum, _padding) = remaining_bytes.split_at(Blake3Hash::SIZE);
2434                let actual_checksum = *blake3::hash(index_and_piece_bytes).as_bytes();
2435                if actual_checksum != expected_checksum && element != &dummy_element {
2436                    warn!(
2437                        %cache_offset,
2438                        actual_checksum = %hex::encode(actual_checksum),
2439                        expected_checksum = %hex::encode(expected_checksum),
2440                        "Cached piece checksum mismatch, replacing with dummy element"
2441                    );
2442
2443                    if !dry_run && let Err(error) = cache_file.write_all_at(&dummy_element, offset)
2444                    {
2445                        return Err(SingleDiskFarmScrubError::FailedToWriteBytes {
2446                            file: file.clone(),
2447                            size: u64::from(element_size),
2448                            offset,
2449                            error,
2450                        });
2451                    }
2452
2453                    return Ok(());
2454                }
2455
2456                Ok(())
2457            })
2458            .try_for_each({
2459                let span = &span;
2460                let checked_elements = AtomicUsize::new(0);
2461
2462                move |result| {
2463                    let _span_guard = span.enter();
2464
2465                    let checked_elements = checked_elements.fetch_add(1, Ordering::Relaxed);
2466                    if checked_elements > 1 && checked_elements.is_multiple_of(1000) {
2467                        info!(
2468                            "Checked {}/{} cache elements",
2469                            checked_elements, number_of_cached_elements
2470                        );
2471                    }
2472
2473                    result
2474                }
2475            })?;
2476
2477        Ok(())
2478    }
2479}
2480
2481fn write_dummy_sector_metadata(
2482    metadata_file: &File,
2483    metadata_file_path: &Path,
2484    sector_index: SectorIndex,
2485    pieces_in_sector: u16,
2486) -> Result<(), SingleDiskFarmScrubError> {
2487    let dummy_sector_bytes = SectorMetadataChecksummed::from(SectorMetadata {
2488        sector_index,
2489        pieces_in_sector,
2490        s_bucket_sizes: Box::new([0; Record::NUM_S_BUCKETS]),
2491        history_size: HistorySize::from(SegmentIndex::ZERO),
2492    })
2493    .encode_for_disk();
2494    let sector_offset = RESERVED_PLOT_METADATA
2495        + u64::from(sector_index) * SectorMetadataChecksummed::disk_size() as u64;
2496    metadata_file
2497        .write_all_at(dummy_sector_bytes.as_slice(), sector_offset)
2498        .map_err(|error| SingleDiskFarmScrubError::FailedToWriteBytes {
2499            file: metadata_file_path.to_path_buf(),
2500            size: u64::from(dummy_sector_bytes.len()),
2501            offset: sector_offset,
2502            error,
2503        })
2504}