|
| 1 | +//! Blockstore implementation is borrowed from https://github.com/filecoin-project/builtin-actors/blob/6df845dcdf9872beb6e871205eb34dcc8f7550b5/runtime/src/runtime/actor_blockstore.rs |
| 2 | +//! This impl will likely be made redundant if low-level SDKs export blockstore implementations |
| 3 | +use std::convert::TryFrom; |
| 4 | + |
| 5 | +use anyhow::{anyhow, Result}; |
| 6 | +use cid::multihash::Code; |
| 7 | +use cid::Cid; |
| 8 | +use fvm_ipld_blockstore::Block; |
| 9 | +use fvm_sdk::ipld; |
| 10 | + |
| 11 | +/// A blockstore that delegates to IPLD syscalls. |
| 12 | +#[derive(Default, Debug, Copy, Clone)] |
| 13 | +pub struct Blockstore; |
| 14 | + |
| 15 | +impl fvm_ipld_blockstore::Blockstore for Blockstore { |
| 16 | + fn get(&self, cid: &Cid) -> Result<Option<Vec<u8>>> { |
| 17 | + // If this fails, the _CID_ is invalid. I.e., we have a bug. |
| 18 | + ipld::get(cid) |
| 19 | + .map(Some) |
| 20 | + .map_err(|e| anyhow!("get failed with {:?} on CID '{}'", e, cid)) |
| 21 | + } |
| 22 | + |
| 23 | + fn put_keyed(&self, k: &Cid, block: &[u8]) -> Result<()> { |
| 24 | + let code = Code::try_from(k.hash().code()).map_err(|e| anyhow!(e.to_string()))?; |
| 25 | + let k2 = self.put(code, &Block::new(k.codec(), block))?; |
| 26 | + if k != &k2 { |
| 27 | + return Err(anyhow!("put block with cid {} but has cid {}", k, k2)); |
| 28 | + } |
| 29 | + Ok(()) |
| 30 | + } |
| 31 | + |
| 32 | + fn put<D>(&self, code: Code, block: &Block<D>) -> Result<Cid> |
| 33 | + where |
| 34 | + D: AsRef<[u8]>, |
| 35 | + { |
| 36 | + // TODO: Don't hard-code the size. Unfortunately, there's no good way to get it from the |
| 37 | + // codec at the moment. |
| 38 | + const SIZE: u32 = 32; |
| 39 | + let k = ipld::put(code.into(), SIZE, block.codec, block.data.as_ref()) |
| 40 | + .map_err(|e| anyhow!("put failed with {:?}", e))?; |
| 41 | + Ok(k) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// TODO: put this somewhere more appropriate when a tests folder exists |
| 46 | +/// An in-memory blockstore impl taken from filecoin-project/ref-fvm |
| 47 | +#[derive(Debug, Default, Clone)] |
| 48 | +pub struct MemoryBlockstore { |
| 49 | + blocks: RefCell<HashMap<Cid, Vec<u8>>>, |
| 50 | +} |
| 51 | + |
| 52 | +use std::{cell::RefCell, collections::HashMap}; |
| 53 | +impl MemoryBlockstore { |
| 54 | + pub fn new() -> Self { |
| 55 | + Self::default() |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +impl fvm_ipld_blockstore::Blockstore for MemoryBlockstore { |
| 60 | + fn has(&self, k: &Cid) -> Result<bool> { |
| 61 | + Ok(self.blocks.borrow().contains_key(k)) |
| 62 | + } |
| 63 | + |
| 64 | + fn get(&self, k: &Cid) -> Result<Option<Vec<u8>>> { |
| 65 | + Ok(self.blocks.borrow().get(k).cloned()) |
| 66 | + } |
| 67 | + |
| 68 | + fn put_keyed(&self, k: &Cid, block: &[u8]) -> Result<()> { |
| 69 | + self.blocks.borrow_mut().insert(*k, block.into()); |
| 70 | + Ok(()) |
| 71 | + } |
| 72 | +} |
0 commit comments