Skip to main content

co_primitives/library/
storage.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 1io BRANDGUARDIAN GmbH
3
4use crate::{AnyBlockStorage, Block, BlockStorage, BlockStorageStoreParams, DefaultParams, StorageError, StoreParams};
5use anyhow::anyhow;
6use async_trait::async_trait;
7use cid::Cid;
8use std::{fmt::Debug, sync::Arc};
9
10#[derive(Clone)]
11pub struct CoreBlockStorage {
12	checked: bool,
13	next: Arc<dyn BlockStorage + 'static>,
14}
15impl CoreBlockStorage {
16	pub fn new(storage: impl AnyBlockStorage, checked: bool) -> Self {
17		Self { checked, next: Arc::new(storage) }
18	}
19}
20impl Debug for CoreBlockStorage {
21	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22		f.debug_struct("CoreBlockStorage").field("checked", &self.checked).finish()
23	}
24}
25#[async_trait]
26impl BlockStorage for CoreBlockStorage {
27	/// Returns a block from storage.
28	async fn get(&self, cid: &Cid) -> Result<Block, StorageError> {
29		self.next.get(cid).await
30	}
31
32	/// Inserts a block into storage.
33	async fn set(&self, block: Block) -> Result<Cid, StorageError> {
34		self.next
35			.set(if self.checked {
36				block
37					.with_store_params::<<Self as BlockStorageStoreParams>::StoreParams>()?
38					.with_verify()?
39			} else {
40				block.with_store_params::<<Self as BlockStorageStoreParams>::StoreParams>()?
41			})
42			.await
43	}
44
45	/// Remove a block.
46	async fn remove(&self, _cid: &Cid) -> Result<(), StorageError> {
47		Err(StorageError::Internal(anyhow!("Unsupported in cores")))
48	}
49
50	/// Maximum accepted block size.
51	fn max_block_size(&self) -> usize {
52		<Self as BlockStorageStoreParams>::StoreParams::MAX_BLOCK_SIZE
53	}
54}
55/// We do not want dynamic block limits in cores as this breaks determinism.
56/// Force all blocks created on cores to be max. 1MiB.
57impl BlockStorageStoreParams for CoreBlockStorage {
58	type StoreParams = DefaultParams;
59}