lighthouse/beacon_node/store/src/lib.rs

224 lines
6.6 KiB
Rust
Raw Normal View History

2019-05-21 08:49:24 +00:00
//! Storage functionality for Lighthouse.
//!
//! Provides the following stores:
//!
//! - `DiskStore`: an on-disk store backed by leveldb. Used in production.
//! - `MemoryStore`: an in-memory store backed by a hash-map. Used for testing.
//!
//! Provides a simple API for storing/retrieving all types that sometimes needs type-hints. See
//! tests for implementation examples.
mod block_at_slot;
mod errors;
mod impls;
2019-05-21 06:29:34 +00:00
mod leveldb_store;
2019-05-21 08:49:24 +00:00
mod memory_store;
2019-05-21 08:20:23 +00:00
pub use self::leveldb_store::LevelDB as DiskStore;
2019-05-21 08:49:24 +00:00
pub use self::memory_store::MemoryStore;
pub use errors::Error;
pub use types::*;
2019-05-21 08:49:24 +00:00
/// An object capable of storing and retrieving objects implementing `StoreItem`.
///
/// A `Store` is fundamentally backed by a key-value database, however it provides support for
/// columns. A simple column implementation might involve prefixing a key with some bytes unique to
/// each column.
pub trait Store: Sync + Send + Sized {
2019-05-21 08:49:24 +00:00
/// Store an item in `Self`.
fn put(&self, key: &Hash256, item: &impl StoreItem) -> Result<(), Error> {
item.db_put(self, key)
}
2019-05-21 08:49:24 +00:00
/// Retrieve an item from `Self`.
fn get<I: StoreItem>(&self, key: &Hash256) -> Result<Option<I>, Error> {
I::db_get(self, key)
}
2019-05-21 08:49:24 +00:00
/// Returns `true` if the given key represents an item in `Self`.
fn exists<I: StoreItem>(&self, key: &Hash256) -> Result<bool, Error> {
I::db_exists(self, key)
}
2019-05-21 08:49:24 +00:00
/// Remove an item from `Self`.
fn delete<I: StoreItem>(&self, key: &Hash256) -> Result<(), Error> {
I::db_delete(self, key)
}
2019-05-21 08:49:24 +00:00
/// Given the root of an existing block in the store (`start_block_root`), return a parent
/// block with the specified `slot`.
///
/// Returns `None` if no parent block exists at that slot, or if `slot` is greater than the
/// slot of `start_block_root`.
fn get_block_at_preceeding_slot(
&self,
start_block_root: Hash256,
slot: Slot,
) -> Result<Option<(Hash256, BeaconBlock)>, Error> {
block_at_slot::get_block_at_preceeding_slot(self, slot, start_block_root)
}
2019-05-21 08:49:24 +00:00
/// Retrieve some bytes in `column` with `key`.
fn get_bytes(&self, column: &str, key: &[u8]) -> Result<Option<Vec<u8>>, Error>;
2019-05-21 08:49:24 +00:00
/// Store some `value` in `column`, indexed with `key`.
fn put_bytes(&self, column: &str, key: &[u8], value: &[u8]) -> Result<(), Error>;
2019-05-21 08:49:24 +00:00
/// Return `true` if `key` exists in `column`.
fn key_exists(&self, column: &str, key: &[u8]) -> Result<bool, Error>;
2019-05-21 08:49:24 +00:00
/// Removes `key` from `column`.
fn key_delete(&self, column: &str, key: &[u8]) -> Result<(), Error>;
}
2019-05-21 08:49:24 +00:00
/// A unique column identifier.
pub enum DBColumn {
BeaconBlock,
BeaconState,
BeaconChain,
}
impl<'a> Into<&'a str> for DBColumn {
/// Returns a `&str` that can be used for keying a key-value data base.
fn into(self) -> &'a str {
match self {
DBColumn::BeaconBlock => &"blk",
DBColumn::BeaconState => &"ste",
DBColumn::BeaconChain => &"bch",
}
}
}
2019-05-21 08:49:24 +00:00
/// An item that may be stored in a `Store`.
///
/// Provides default methods that are suitable for most applications, however when overridden they
/// provide full customizability of `Store` operations.
pub trait StoreItem: Sized {
2019-05-21 08:49:24 +00:00
/// Identifies which column this item should be placed in.
fn db_column() -> DBColumn;
2019-05-21 08:49:24 +00:00
/// Serialize `self` as bytes.
fn as_store_bytes(&self) -> Vec<u8>;
2019-05-21 08:49:24 +00:00
/// De-serialize `self` from bytes.
fn from_store_bytes(bytes: &mut [u8]) -> Result<Self, Error>;
2019-05-21 08:49:24 +00:00
/// Store `self`.
fn db_put(&self, store: &impl Store, key: &Hash256) -> Result<(), Error> {
let column = Self::db_column().into();
let key = key.as_bytes();
store
.put_bytes(column, key, &self.as_store_bytes())
2019-05-21 08:49:24 +00:00
.map_err(Into::into)
}
2019-05-21 08:49:24 +00:00
/// Retrieve an instance of `Self`.
fn db_get(store: &impl Store, key: &Hash256) -> Result<Option<Self>, Error> {
let column = Self::db_column().into();
let key = key.as_bytes();
match store.get_bytes(column, key)? {
Some(mut bytes) => Ok(Some(Self::from_store_bytes(&mut bytes[..])?)),
None => Ok(None),
}
}
2019-05-21 08:49:24 +00:00
/// Return `true` if an instance of `Self` exists in `Store`.
fn db_exists(store: &impl Store, key: &Hash256) -> Result<bool, Error> {
let column = Self::db_column().into();
let key = key.as_bytes();
store.key_exists(column, key)
}
2019-05-21 08:49:24 +00:00
/// Delete `self` from the `Store`.
fn db_delete(store: &impl Store, key: &Hash256) -> Result<(), Error> {
let column = Self::db_column().into();
let key = key.as_bytes();
store.key_delete(column, key)
}
}
#[cfg(test)]
mod tests {
use super::*;
use ssz::{Decode, Encode};
use ssz_derive::{Decode, Encode};
2019-05-21 06:29:34 +00:00
use tempfile::tempdir;
#[derive(PartialEq, Debug, Encode, Decode)]
struct StorableThing {
a: u64,
b: u64,
}
impl StoreItem for StorableThing {
fn db_column() -> DBColumn {
DBColumn::BeaconBlock
}
fn as_store_bytes(&self) -> Vec<u8> {
self.as_ssz_bytes()
}
fn from_store_bytes(bytes: &mut [u8]) -> Result<Self, Error> {
Self::from_ssz_bytes(bytes).map_err(Into::into)
}
}
2019-05-21 06:37:15 +00:00
fn test_impl(store: impl Store) {
2019-05-21 06:29:34 +00:00
let key = Hash256::random();
let item = StorableThing { a: 1, b: 42 };
2019-05-21 06:37:15 +00:00
assert_eq!(store.exists::<StorableThing>(&key), Ok(false));
2019-05-21 06:29:34 +00:00
store.put(&key, &item).unwrap();
2019-05-21 06:37:15 +00:00
assert_eq!(store.exists::<StorableThing>(&key), Ok(true));
2019-05-21 06:29:34 +00:00
2019-05-21 06:37:15 +00:00
let retrieved = store.get(&key).unwrap().unwrap();
2019-05-21 06:29:34 +00:00
assert_eq!(item, retrieved);
2019-05-21 06:37:15 +00:00
store.delete::<StorableThing>(&key).unwrap();
assert_eq!(store.exists::<StorableThing>(&key), Ok(false));
assert_eq!(store.get::<StorableThing>(&key), Ok(None));
2019-05-21 06:29:34 +00:00
}
#[test]
fn diskdb() {
2019-05-21 06:37:15 +00:00
let dir = tempdir().unwrap();
let path = dir.path();
2019-05-21 08:20:23 +00:00
let store = DiskStore::open(&path).unwrap();
2019-05-21 06:37:15 +00:00
test_impl(store);
}
2019-05-21 06:37:15 +00:00
#[test]
fn memorydb() {
2019-05-21 08:20:23 +00:00
let store = MemoryStore::open();
2019-05-21 06:37:15 +00:00
test_impl(store);
}
#[test]
fn exists() {
2019-05-21 08:20:23 +00:00
let store = MemoryStore::open();
let key = Hash256::random();
let item = StorableThing { a: 1, b: 42 };
assert_eq!(store.exists::<StorableThing>(&key).unwrap(), false);
store.put(&key, &item).unwrap();
assert_eq!(store.exists::<StorableThing>(&key).unwrap(), true);
store.delete::<StorableThing>(&key).unwrap();
assert_eq!(store.exists::<StorableThing>(&key).unwrap(), false);
}
}