atrium_repo/
blockstore.rs

1use std::future::Future;
2
3use ipld_core::cid::Cid;
4
5mod car;
6mod diff;
7mod memory;
8
9pub use car::{CarStore, Error as CarError};
10pub use diff::DiffBlockStore;
11pub use memory::MemoryBlockStore;
12
13/// DAG-PB multicodec code
14pub const DAG_PB: u64 = 0x70;
15/// DAG-CBOR multicodec code
16pub const DAG_CBOR: u64 = 0x71;
17/// The SHA_256 multihash code
18pub const SHA2_256: u64 = 0x12;
19
20pub trait AsyncBlockStoreRead: Send {
21    /// Read a single block from the block store into the provided buffer.
22    fn read_block_into(
23        &mut self,
24        cid: Cid,
25        contents: &mut Vec<u8>,
26    ) -> impl Future<Output = Result<(), Error>> + Send;
27
28    /// Read a single block from the block store.
29    fn read_block(&mut self, cid: Cid) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
30        async move {
31            let mut contents = Vec::new();
32            self.read_block_into(cid, &mut contents).await?;
33            Ok(contents)
34        }
35    }
36}
37
38pub trait AsyncBlockStoreWrite: Send {
39    /// Write a single block into the block store.
40    /// This will return the block's computed hash.
41    fn write_block(
42        &mut self,
43        codec: u64,
44        hash: u64,
45        contents: &[u8],
46    ) -> impl Future<Output = Result<Cid, Error>> + Send;
47}
48
49impl<T: AsyncBlockStoreRead> AsyncBlockStoreRead for &mut T {
50    fn read_block_into(
51        &mut self,
52        cid: Cid,
53        contents: &mut Vec<u8>,
54    ) -> impl Future<Output = Result<(), Error>> + Send {
55        (**self).read_block_into(cid, contents)
56    }
57}
58
59impl<T: AsyncBlockStoreWrite> AsyncBlockStoreWrite for &mut T {
60    fn write_block(
61        &mut self,
62        codec: u64,
63        hash: u64,
64        contents: &[u8],
65    ) -> impl Future<Output = Result<Cid, Error>> + Send {
66        (**self).write_block(codec, hash, contents)
67    }
68}
69
70/// Errors that can occur while interacting with a block store.
71#[derive(Debug, thiserror::Error)]
72pub enum Error {
73    #[error("CID does not exist in block store")]
74    CidNotFound,
75    #[error("unsupported hashing algorithm")]
76    UnsupportedHash(u64),
77    #[error(transparent)]
78    Other(Box<dyn std::error::Error + Send + Sync>),
79}
80
81impl From<std::io::Error> for Error {
82    fn from(value: std::io::Error) -> Self {
83        Self::Other(Box::new(value))
84    }
85}