Skip to main content

ab_farmer_components/
lib.rs

1//! Components of the reference implementation of Subspace Farmer for Subspace Network Blockchain.
2//!
3//! These components are used to implement farmer itself, but can also be used independently if
4//! necessary.
5
6#![feature(
7    const_block_items,
8    const_convert,
9    const_trait_impl,
10    gen_blocks,
11    iter_array_chunks,
12    maybe_uninit_array_assume_init,
13    maybe_uninit_fill,
14    portable_simd,
15    try_blocks
16)]
17#![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)]
18
19pub mod auditing;
20pub mod file_ext;
21pub mod plotting;
22pub mod proving;
23pub mod reading;
24pub mod sector;
25mod segment_reconstruction;
26pub mod shard_commitment;
27
28use crate::file_ext::FileExt;
29use ab_aligned_buffer::OwnedAlignedBuffer;
30use ab_aligned_buffer::alignment::Align1;
31use ab_core_primitives::segments::HistorySize;
32use ab_direct_io_file::{DirectIoFile, IoBufError, OwnedPages};
33use parity_scale_codec::{Decode, Encode};
34use serde::{Deserialize, Serialize};
35use std::fs::File;
36use std::future::Future;
37use std::io;
38
39/// Enum to encapsulate the selection between [`ReadAtSync`] and [`ReadAtAsync]` variants
40#[derive(Debug, Copy, Clone)]
41pub enum ReadAt<S, A>
42where
43    S: ReadAtSync,
44    A: ReadAtAsync,
45{
46    /// Sync variant
47    Sync(S),
48    /// Async variant
49    Async(A),
50}
51
52impl<S> ReadAt<S, !>
53where
54    S: ReadAtSync,
55{
56    /// Instantiate [`ReadAt`] from some [`ReadAtSync`] implementation
57    pub fn from_sync(value: S) -> Self {
58        Self::Sync(value)
59    }
60}
61
62impl<A> ReadAt<!, A>
63where
64    A: ReadAtAsync,
65{
66    /// Instantiate [`ReadAt`] from some [`ReadAtAsync`] implementation
67    pub fn from_async(value: A) -> Self {
68        Self::Async(value)
69    }
70}
71
72/// Sync version of [`ReadAt`], it is both [`Send`] and [`Sync`] and is supposed to be used with a
73/// thread pool
74pub trait ReadAtSync: Send + Sync {
75    /// Get implementation of [`ReadAtSync`] that add specified offset to all attempted reads
76    fn offset(&self, offset: u64) -> ReadAtOffset<'_, Self>
77    where
78        Self: Sized,
79    {
80        ReadAtOffset {
81            inner: self,
82            offset,
83        }
84    }
85
86    /// Read `len` bytes at `offset` into `buffer`, replacing its contents.
87    ///
88    /// The allocation of the buffer is reused when possible and grows otherwise, allocation
89    /// failure is returned as an error. Existing contents are never copied. On success, the
90    /// contents are exactly the requested bytes. The buffer is returned back on error too.
91    ///
92    /// The returned buffer can be reused for the next read with
93    /// [`OwnedAlignedBuffer::into_empty()`].
94    fn read_at(
95        &self,
96        buffer: OwnedPages,
97        len: u32,
98        offset: u64,
99    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>>;
100}
101
102impl<T> ReadAtSync for &T
103where
104    T: ReadAtSync + ?Sized,
105{
106    #[inline]
107    fn read_at(
108        &self,
109        buffer: OwnedPages,
110        len: u32,
111        offset: u64,
112    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
113        (**self).read_at(buffer, len, offset)
114    }
115}
116
117impl ReadAtSync for ! {
118    fn read_at(
119        &self,
120        _buffer: OwnedPages,
121        _len: u32,
122        _offset: u64,
123    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
124        unreachable!("Is never called")
125    }
126}
127
128impl ReadAtSync for [u8] {
129    fn read_at(
130        &self,
131        mut buffer: OwnedPages,
132        len: u32,
133        offset: u64,
134    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
135        let maybe_bytes = offset
136            .checked_add(u64::from(len))
137            .and_then(|end| self.get(usize::try_from(offset).ok()?..usize::try_from(end).ok()?));
138        let Some(bytes) = maybe_bytes else {
139            return Err(IoBufError {
140                error: io::Error::new(
141                    io::ErrorKind::InvalidInput,
142                    "Buffer length with offset exceeds own length",
143                )
144                .into(),
145                buffer,
146            });
147        };
148
149        // Grow the buffer while it is page-aligned, such that the allocation can be reused for
150        // further reads
151        buffer.truncate(0);
152        if let Err(error) = buffer.try_ensure_capacity(len) {
153            return Err(IoBufError {
154                error: error.into(),
155                buffer,
156            });
157        }
158
159        let mut contents = buffer.into_start_align::<Align1>();
160        contents
161            .append(bytes)
162            .expect("Capacity for `len` bytes is ensured above; qed");
163
164        Ok(contents)
165    }
166}
167
168impl ReadAtSync for Vec<u8> {
169    #[inline]
170    fn read_at(
171        &self,
172        buffer: OwnedPages,
173        len: u32,
174        offset: u64,
175    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
176        self.as_slice().read_at(buffer, len, offset)
177    }
178}
179
180impl ReadAtSync for File {
181    fn read_at(
182        &self,
183        mut buffer: OwnedPages,
184        len: u32,
185        offset: u64,
186    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
187        buffer.truncate(0);
188        if let Err(error) = buffer.try_ensure_capacity(len) {
189            return Err(IoBufError {
190                error: error.into(),
191                buffer,
192            });
193        }
194        buffer.spare_capacity_mut()[..len as usize].write_filled(0);
195        // SAFETY: Capacity for `len` bytes is ensured and they are initialized with zeroes above
196        unsafe {
197            buffer.set_len(len);
198        }
199
200        if let Err(error) = self.read_exact_at(buffer.as_mut_slice(), offset) {
201            buffer.truncate(0);
202            return Err(IoBufError {
203                error: error.into(),
204                buffer,
205            });
206        }
207
208        Ok(buffer.into_start_align())
209    }
210}
211
212impl ReadAtSync for DirectIoFile {
213    #[inline]
214    fn read_at(
215        &self,
216        buffer: OwnedPages,
217        len: u32,
218        offset: u64,
219    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
220        DirectIoFile::read_at(self, buffer, len, offset)
221    }
222}
223
224/// Async version of [`ReadAt`], it is neither [`Send`] nor [`Sync`] and is supposed to be used with
225/// concurrent async combinators
226pub trait ReadAtAsync {
227    /// Get implementation of [`ReadAtAsync`] that add specified offset to all attempted reads
228    fn offset(&self, offset: u64) -> ReadAtOffset<'_, Self>
229    where
230        Self: Sized,
231    {
232        ReadAtOffset {
233            inner: self,
234            offset,
235        }
236    }
237
238    /// Read `len` bytes at `offset` into `buffer`, replacing its contents, see
239    /// [`ReadAtSync::read_at()`] for details
240    fn read_at(
241        &self,
242        buffer: OwnedPages,
243        len: u32,
244        offset: u64,
245    ) -> impl Future<Output = Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>>>;
246}
247
248impl<T> ReadAtAsync for &T
249where
250    T: ReadAtAsync + ?Sized,
251{
252    #[inline]
253    fn read_at(
254        &self,
255        buffer: OwnedPages,
256        len: u32,
257        offset: u64,
258    ) -> impl Future<Output = Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>>> {
259        (**self).read_at(buffer, len, offset)
260    }
261}
262
263impl ReadAtAsync for ! {
264    async fn read_at(
265        &self,
266        _buffer: OwnedPages,
267        _len: u32,
268        _offset: u64,
269    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
270        unreachable!("Is never called")
271    }
272}
273
274/// Reader with fixed offset added to all attempted reads
275#[derive(Debug, Copy, Clone)]
276pub struct ReadAtOffset<'a, T> {
277    inner: &'a T,
278    offset: u64,
279}
280
281impl<T> ReadAtSync for ReadAtOffset<'_, T>
282where
283    T: ReadAtSync,
284{
285    #[inline]
286    fn read_at(
287        &self,
288        buffer: OwnedPages,
289        len: u32,
290        offset: u64,
291    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
292        let Some(offset) = offset.checked_add(self.offset) else {
293            return Err(IoBufError {
294                error: io::Error::new(io::ErrorKind::InvalidInput, "Offset overflow").into(),
295                buffer,
296            });
297        };
298
299        self.inner.read_at(buffer, len, offset)
300    }
301}
302
303impl<T> ReadAtAsync for ReadAtOffset<'_, T>
304where
305    T: ReadAtAsync,
306{
307    #[inline]
308    async fn read_at(
309        &self,
310        buffer: OwnedPages,
311        len: u32,
312        offset: u64,
313    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
314        let Some(offset) = offset.checked_add(self.offset) else {
315            return Err(IoBufError {
316                error: io::Error::new(io::ErrorKind::InvalidInput, "Offset overflow").into(),
317                buffer,
318            });
319        };
320
321        self.inner.read_at(buffer, len, offset).await
322    }
323}
324
325// Refuse to compile on non-64-bit platforms, offsets may fail on those when converting from u64 to
326// usize depending on chain parameters
327const {
328    assert!(size_of::<usize>() >= size_of::<u64>());
329}
330
331/// Information about the protocol necessary for farmer operation
332#[derive(Debug, Copy, Clone, Encode, Decode, Serialize, Deserialize)]
333#[serde(rename_all = "camelCase")]
334pub struct FarmerProtocolInfo {
335    /// Size of the blockchain history
336    pub history_size: HistorySize,
337    /// How many pieces one sector is supposed to contain (max)
338    pub max_pieces_in_sector: u16,
339    /// Number of latest archived segments that are considered "recent history".
340    pub recent_segments: HistorySize,
341    /// Fraction of pieces from the "recent history" (`recent_segments`) in each sector.
342    pub recent_history_fraction: (HistorySize, HistorySize),
343    /// Minimum lifetime of a plotted sector, measured in archived segment
344    pub min_sector_lifetime: HistorySize,
345}