1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
//! Components of the reference implementation of Subspace Farmer for Subspace Network Blockchain.
//!
//! These components are used to implement farmer itself, but can also be used independently if necessary.

#![feature(
    array_chunks,
    const_option,
    const_trait_impl,
    int_roundings,
    iter_collect_into,
    never_type,
    new_uninit,
    portable_simd,
    try_blocks
)]
#![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)]

pub mod auditing;
pub mod file_ext;
pub mod plotting;
pub mod proving;
pub mod reading;
pub mod sector;
mod segment_reconstruction;

use crate::file_ext::FileExt;
use async_trait::async_trait;
use parity_scale_codec::{Decode, Encode};
use serde::{Deserialize, Serialize};
use static_assertions::const_assert;
use std::error::Error;
use std::fs::File;
use std::future::Future;
use std::io;
use std::sync::Arc;
use subspace_core_primitives::{ArchivedHistorySegment, HistorySize, Piece, PieceIndex};

/// Trait representing a way to get pieces
#[async_trait]
pub trait PieceGetter {
    /// Get piece by index
    async fn get_piece(
        &self,
        piece_index: PieceIndex,
    ) -> Result<Option<Piece>, Box<dyn Error + Send + Sync + 'static>>;
}

#[async_trait]
impl<T> PieceGetter for Arc<T>
where
    T: PieceGetter + Send + Sync,
{
    async fn get_piece(
        &self,
        piece_index: PieceIndex,
    ) -> Result<Option<Piece>, Box<dyn Error + Send + Sync + 'static>> {
        self.as_ref().get_piece(piece_index).await
    }
}

#[async_trait]
impl PieceGetter for ArchivedHistorySegment {
    async fn get_piece(
        &self,
        piece_index: PieceIndex,
    ) -> Result<Option<Piece>, Box<dyn Error + Send + Sync + 'static>> {
        let position = usize::try_from(u64::from(piece_index))?;

        Ok(self.pieces().nth(position))
    }
}

/// Enum to encapsulate the selection between [`ReadAtSync`] and [`ReadAtAsync]` variants
#[derive(Debug, Copy, Clone)]
pub enum ReadAt<S, A>
where
    S: ReadAtSync,
    A: ReadAtAsync,
{
    /// Sync variant
    Sync(S),
    /// Async variant
    Async(A),
}

impl<S> ReadAt<S, !>
where
    S: ReadAtSync,
{
    /// Instantiate [`ReadAt`] from some [`ReadAtSync`] implementation
    pub fn from_sync(value: S) -> Self {
        Self::Sync(value)
    }
}

impl<A> ReadAt<!, A>
where
    A: ReadAtAsync,
{
    /// Instantiate [`ReadAt`] from some [`ReadAtAsync`] implementation
    pub fn from_async(value: A) -> Self {
        Self::Async(value)
    }
}

/// Sync version of [`ReadAt`], it is both [`Send`] and [`Sync`] and is supposed to be used with a
/// thread pool
pub trait ReadAtSync: Send + Sync {
    /// Get implementation of [`ReadAtSync`] that add specified offset to all attempted reads
    fn offset(&self, offset: u64) -> ReadAtOffset<'_, Self>
    where
        Self: Sized,
    {
        ReadAtOffset {
            inner: self,
            offset,
        }
    }

    /// Fill the buffer by reading bytes at a specific offset
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()>;
}

impl ReadAtSync for ! {
    fn read_at(&self, _buf: &mut [u8], _offset: u64) -> io::Result<()> {
        unreachable!("Is never called")
    }
}

/// Container or asynchronously reading bytes using in [`ReadAtAsync`]
#[repr(transparent)]
#[derive(Debug)]
pub struct AsyncReadBytes<B>(B)
where
    B: AsMut<[u8]> + Unpin + 'static;

impl From<Vec<u8>> for AsyncReadBytes<Vec<u8>> {
    fn from(value: Vec<u8>) -> Self {
        Self(value)
    }
}

impl From<Box<[u8]>> for AsyncReadBytes<Box<[u8]>> {
    fn from(value: Box<[u8]>) -> Self {
        Self(value)
    }
}

impl<B> AsMut<[u8]> for AsyncReadBytes<B>
where
    B: AsMut<[u8]> + Unpin + 'static,
{
    fn as_mut(&mut self) -> &mut [u8] {
        self.0.as_mut()
    }
}

impl<B> AsyncReadBytes<B>
where
    B: AsMut<[u8]> + Unpin + 'static,
{
    /// Extract inner value
    pub fn into_inner(self) -> B {
        self.0
    }
}

/// Async version of [`ReadAt`], it is neither [`Send`] nor [`Sync`] and is supposed to be used with
/// concurrent async combinators
pub trait ReadAtAsync {
    /// Get implementation of [`ReadAtAsync`] that add specified offset to all attempted reads
    fn offset(&self, offset: u64) -> ReadAtOffset<'_, Self>
    where
        Self: Sized,
    {
        ReadAtOffset {
            inner: self,
            offset,
        }
    }

    /// Fill the buffer by reading bytes at a specific offset and return the buffer back
    fn read_at<B>(&self, buf: B, offset: u64) -> impl Future<Output = io::Result<B>>
    where
        AsyncReadBytes<B>: From<B>,
        B: AsMut<[u8]> + Unpin + 'static;
}

impl ReadAtAsync for ! {
    async fn read_at<B>(&self, _buf: B, _offset: u64) -> io::Result<B>
    where
        AsyncReadBytes<B>: From<B>,
        B: AsMut<[u8]> + Unpin + 'static,
    {
        unreachable!("Is never called")
    }
}

impl ReadAtSync for [u8] {
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        if buf.len() as u64 + offset > self.len() as u64 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Buffer length with offset exceeds own length",
            ));
        }

        buf.copy_from_slice(&self[offset as usize..][..buf.len()]);

        Ok(())
    }
}

impl ReadAtSync for &[u8] {
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        if buf.len() as u64 + offset > self.len() as u64 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Buffer length with offset exceeds own length",
            ));
        }

        buf.copy_from_slice(&self[offset as usize..][..buf.len()]);

        Ok(())
    }
}

impl ReadAtSync for Vec<u8> {
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.as_slice().read_at(buf, offset)
    }
}

impl ReadAtSync for &Vec<u8> {
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.as_slice().read_at(buf, offset)
    }
}

impl ReadAtSync for File {
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.read_exact_at(buf, offset)
    }
}

impl ReadAtSync for &File {
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.read_exact_at(buf, offset)
    }
}

/// Reader with fixed offset added to all attempted reads
#[derive(Debug, Copy, Clone)]
pub struct ReadAtOffset<'a, T> {
    inner: &'a T,
    offset: u64,
}

impl<T> ReadAtSync for ReadAtOffset<'_, T>
where
    T: ReadAtSync,
{
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.inner.read_at(buf, offset + self.offset)
    }
}

impl<T> ReadAtSync for &ReadAtOffset<'_, T>
where
    T: ReadAtSync,
{
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.inner.read_at(buf, offset + self.offset)
    }
}

impl<T> ReadAtAsync for ReadAtOffset<'_, T>
where
    T: ReadAtAsync,
{
    async fn read_at<B>(&self, buf: B, offset: u64) -> io::Result<B>
    where
        AsyncReadBytes<B>: From<B>,
        B: AsMut<[u8]> + Unpin + 'static,
    {
        self.inner.read_at(buf, offset + self.offset).await
    }
}

impl<T> ReadAtAsync for &ReadAtOffset<'_, T>
where
    T: ReadAtAsync,
{
    async fn read_at<B>(&self, buf: B, offset: u64) -> io::Result<B>
    where
        AsyncReadBytes<B>: From<B>,
        B: AsMut<[u8]> + Unpin + 'static,
    {
        self.inner.read_at(buf, offset + self.offset).await
    }
}

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

/// Information about the protocol necessary for farmer operation
#[derive(Debug, Copy, Clone, Encode, Decode, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FarmerProtocolInfo {
    /// Size of the blockchain history
    pub history_size: HistorySize,
    /// How many pieces one sector is supposed to contain (max)
    pub max_pieces_in_sector: u16,
    /// Number of latest archived segments that are considered "recent history".
    pub recent_segments: HistorySize,
    /// Fraction of pieces from the "recent history" (`recent_segments`) in each sector.
    pub recent_history_fraction: (HistorySize, HistorySize),
    /// Minimum lifetime of a plotted sector, measured in archived segment
    pub min_sector_lifetime: HistorySize,
}