//! Transaction-local `ATrium` block overlay and verified content-addressed reads. use std::collections::{HashMap, HashSet}; use atrium_repo::{ Cid, blockstore::{ AsyncBlockStoreRead, AsyncBlockStoreWrite, DAG_CBOR, Error as BlockError, SHA2_256, }, }; use crate::error::{Error, Result}; use super::Database; /// `ATrium` writes into this in-memory overlay. `SQLite` is read on demand, but no /// staged write is visible until [`Database::commit_repo`] publishes the batch. pub(crate) struct RepoBlockStore { database: Database, writes: HashMap>, } impl RepoBlockStore { pub(crate) fn new(database: Database) -> Self { Self { database, writes: HashMap::new(), } } pub(crate) fn reachable_writes( &self, reachable: impl IntoIterator, ) -> Result)>> { let reachable = reachable.into_iter().collect::>(); for cid in &reachable { if !self.writes.contains_key(cid) { self.database.repo_block(*cid)?; } } Ok(self .writes .iter() .filter(move |(cid, _)| reachable.contains(cid))) } pub(crate) fn writes(&self) -> Vec<(Cid, Vec)> { self.writes .iter() .map(|(cid, bytes)| (*cid, bytes.clone())) .collect() } } impl AsyncBlockStoreRead for RepoBlockStore { fn read_block_into( &mut self, cid: Cid, contents: &mut Vec, ) -> impl Future> + Send { let block = self .writes .get(&cid) .cloned() .map_or_else(|| self.database.repo_block(cid), Ok) .map_err(block_error); async move { contents.clear(); contents.extend_from_slice(&block?); Ok(()) } } } impl AsyncBlockStoreWrite for RepoBlockStore { fn write_block( &mut self, codec: u64, hash: u64, contents: &[u8], ) -> impl Future> + Send { let result = block_cid(codec, hash, contents).inspect(|cid| { self.writes.insert(*cid, contents.to_vec()); }); async move { result } } } impl Database { pub(super) fn repo_block(&self, cid: Cid) -> Result> { let bytes = self .query_optional( "SELECT bytes FROM repo_blocks WHERE cid = ?1", [cid.to_string()], |row| Ok(row.get::<_, Vec>(0)?), )? .ok_or(Error::NotFound)?; verify_block(cid, &bytes)?; Ok(bytes) } } pub(super) fn verify_block(cid: Cid, bytes: &[u8]) -> Result<()> { let computed = block_cid(cid.codec(), cid.hash().code(), bytes).map_err(|error| { Error::Internal(format!("could not verify repository block {cid}: {error}")) })?; if computed == cid { Ok(()) } else { Err(Error::Internal(format!( "repository block bytes do not match CID {cid}" ))) } } pub(super) fn block_cid( codec: u64, hash: u64, contents: &[u8], ) -> std::result::Result { if codec != DAG_CBOR { return Err(BlockError::Other(Box::new(std::io::Error::other(format!( "unsupported repository codec {codec}" ))))); } if hash != SHA2_256 { return Err(BlockError::UnsupportedHash(hash)); } Ok(cpds_protocol::sha256_cid(codec, contents)) } fn block_error(error: Error) -> BlockError { match error { Error::NotFound => BlockError::CidNotFound, error => BlockError::Other(Box::new(std::io::Error::other(error.to_string()))), } }