#![warn(
missing_debug_implementations,
missing_docs,
redundant_lifetimes,
//unsafe_code,
non_local_definitions
)]
mod builder;
mod keys;
mod replicate;
mod storage;
use futures::future::{BoxFuture, FutureExt, Shared};
use hypercore_protocol::{discovery_key, DiscoveryKey};
use keys::{key_pair_from_name, DEFAULT_NAMESPACE};
use std::{
collections::HashMap,
sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
};
use storage::StorageKind;
use hypercore::{
hypercore_handshake::CipherTrait, replication::CoreMethodsError, Hypercore, HypercoreError,
PartialKeypair, VerifyingKey,
};
pub use builder::{CorestoreBuilder, CorestoreBuilderError};
pub use replicate::CorestoreConnection;
static MAX_EVENT_QUEUE_CAPACITY: usize = 32;
const CORES_DIR_NAME: &str = "cores";
const PRIMARY_KEY_FILE_NAME: &str = "primary-key";
pub type PrimaryKey = [u8; 32];
pub type Namespace = [u8; 32];
#[non_exhaustive]
#[derive(thiserror::Error, Debug)]
#[allow(missing_docs)]
pub enum Error {
#[error("error from hypercore: {0}")]
Hypercore(#[from] HypercoreError),
#[error("error from hypercore CoreMethods: {0}")]
CoreMethods(#[from] CoreMethodsError),
#[error("Signature error")]
Signature(#[from] signature::Error),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Invalid primary key")]
InvalidPrimaryKey,
#[error("could not build the corestore: {0}")]
Builder(#[from] CorestoreBuilderError),
#[error("Could not build corestore because a primary key value was provided, but one already exists on disk at [{0}]")]
PrimaryKeyConflict(String),
#[error("libsodium's generichash function did not return `0`. Got: {0}")]
LibSodiumGenericHash(i32),
#[error("libsodium's sign_seed_keypair function did not return `0`. Got: {0}")]
LibSodiumSignSeedKeypair(i32),
#[error("error reading dirs {0}")]
ReadDir(std::io::Error),
#[error("error opening core: {0}")]
Opening(Arc<Error>),
}
type Result<T> = std::result::Result<T, Error>;
mod events {
#![allow(unused)]
use super::{Result, MAX_EVENT_QUEUE_CAPACITY};
use hypercore::VerifyingKey;
use hypercore_protocol::DiscoveryKey;
use tokio::sync::{broadcast, BarrierWaitResult};
#[derive(Debug, Clone)]
pub enum Event {
CoreAdded(VerifyingKey),
Shutdown,
}
#[derive(Debug, Clone)]
pub struct Events {
channel: broadcast::Sender<Event>,
}
impl Events {
fn new() -> Self {
Self {
channel: broadcast::channel(MAX_EVENT_QUEUE_CAPACITY).0,
}
}
pub fn send(&self, evt: Event) -> Result<()> {
let _ = self.channel.send(evt);
Ok(())
}
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
self.channel.subscribe()
}
}
impl Default for Events {
fn default() -> Self {
Events::new()
}
}
}
pub use events::Event as CorestoreEvents;
type OpeningCore = Shared<BoxFuture<'static, std::result::Result<Hypercore, Arc<Error>>>>;
#[derive(Clone)]
enum CachedCore {
Ready(Hypercore),
Opening(OpeningCore),
}
impl std::fmt::Debug for CachedCore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CachedCore::Ready(core) => f.debug_tuple("Ready").field(core).finish(),
CachedCore::Opening(_) => write!(f, "Opening"),
}
}
}
#[derive(Debug, Default)]
struct CoreCache {
verifying_key_to_cores: HashMap<VerifyingKey, CachedCore>,
}
impl CoreCache {
fn get(&self, verifying_key: &VerifyingKey) -> Option<CachedCore> {
self.verifying_key_to_cores.get(verifying_key).cloned()
}
fn insert_ready(&mut self, verifying_key: VerifyingKey, core: Hypercore) {
self.verifying_key_to_cores
.insert(verifying_key, CachedCore::Ready(core));
}
fn insert_opening(&mut self, verifying_key: VerifyingKey, opening: OpeningCore) {
self.verifying_key_to_cores
.insert(verifying_key, CachedCore::Opening(opening));
}
fn remove(&mut self, verifying_key: &VerifyingKey) {
self.verifying_key_to_cores.remove(verifying_key);
}
fn verifying_keys(&self) -> Vec<VerifyingKey> {
self.verifying_key_to_cores
.iter()
.filter(|(_, cached)| matches!(cached, CachedCore::Ready(_)))
.map(|(vk, _)| *vk)
.collect()
}
fn verifying_key_from_discovery_key(&self, dk: &DiscoveryKey) -> Option<VerifyingKey> {
self.verifying_keys()
.into_iter()
.find(|vk| dk == &discovery_key(vk.as_bytes()))
}
}
#[derive(Debug, Clone)]
pub struct Corestore {
corestore: Arc<RwLock<builder::InnerCorstore>>,
events: events::Events,
}
impl Corestore {
fn read(&self) -> RwLockReadGuard<'_, builder::InnerCorstore> {
self.corestore.read().expect("corestore lock poisoned")
}
fn write(&self) -> RwLockWriteGuard<'_, builder::InnerCorstore> {
self.corestore.write().expect("corestore lock poisoned")
}
pub fn verifying_key_from_discovery_key(&self, dk: &DiscoveryKey) -> Option<VerifyingKey> {
self.read().verifying_key_from_discovery_key(dk)
}
pub(crate) fn verifying_keys(&self) -> Vec<VerifyingKey> {
self.read().verifying_keys()
}
pub async fn get_from_name(&self, name: &str) -> Result<Hypercore> {
let primary_key = self.read().primary_key();
let key_pair = key_pair_from_name(primary_key, &DEFAULT_NAMESPACE, name)?;
self.get_core(key_pair).await
}
pub async fn get_from_verifying_key(&self, verifying_key: &VerifyingKey) -> Result<Hypercore> {
self.get_core(PartialKeypair {
public: *verifying_key,
secret: None,
})
.await
}
async fn get_core(&self, key_pair: PartialKeypair) -> Result<Hypercore> {
let verifying_key = key_pair.public;
let opening = {
let mut inner = self.write();
match inner.core_cache.get(&verifying_key) {
Some(CachedCore::Ready(core)) => return Ok(core),
Some(CachedCore::Opening(opening)) => opening,
None => {
let storage = inner.storage().clone();
let opening = async move {
storage
.get_core_from_key_pair(key_pair)
.await
.map_err(Arc::new)
}
.boxed()
.shared();
inner
.core_cache
.insert_opening(verifying_key, opening.clone());
opening
}
}
};
let opened = opening.clone().await;
let newly_ready = {
let mut inner = self.write();
let still_opening = matches!(
inner.core_cache.get(&verifying_key),
Some(CachedCore::Opening(current)) if current.ptr_eq(&opening)
);
match &opened {
Ok(core) if still_opening => {
inner.core_cache.insert_ready(verifying_key, core.clone());
true
}
Err(_) if still_opening => {
inner.core_cache.remove(&verifying_key);
false
}
_ => false,
}
};
if newly_ready {
let _ = self.events.send(CorestoreEvents::CoreAdded(verifying_key));
}
opened.map_err(Error::Opening)
}
pub async fn new_mem() -> Corestore {
CorestoreBuilder::default()
.storage(StorageKind::new_mem())
.build()
.await
.expect("should always work")
}
pub async fn new_disk(path: impl AsRef<std::path::Path>) -> Result<Corestore> {
let path = path.as_ref();
std::fs::create_dir_all(path).map_err(hypercore::HypercoreError::from)?;
CorestoreBuilder::default()
.storage(StorageKind::new_disk(path))
.build()
.await
}
pub(crate) fn subscribe(&self) -> tokio::sync::broadcast::Receiver<CorestoreEvents> {
self.events.subscribe()
}
pub fn replicate(&self, stream: impl CipherTrait + 'static) -> CorestoreConnection {
CorestoreConnection::new(self.clone(), stream)
}
}
#[cfg(test)]
mod test {
use super::{storage::get_storage_root, *};
use hypercore::{
hypercore_handshake::{
state_machine::{hc_specific::generate_keypair, SecStream},
Cipher,
},
GetOptions,
};
use std::time::Duration;
use tokio_util::compat::TokioAsyncReadCompatExt;
use uint24le_framing::Uint24LELengthPrefixedFraming;
const REPLICATION_BUDGET: Duration = Duration::from_secs(5);
async fn replicated_block(core: &Hypercore, index: u64) -> Result<Vec<u8>> {
let block = core
.get_with_options(index, GetOptions::with_timeout(REPLICATION_BUDGET))
.await?;
Ok(block.expect("a waiting get resolves with the block, never None"))
}
#[tokio::test]
async fn new_disk_round_trips_a_named_core() -> Result<()> {
let tmp = tempfile::tempdir().expect("tempdir");
let dir = tmp.path().join("store");
let key = {
let store = Corestore::new_disk(&dir).await?;
let core = store.get_from_name("feed").await?;
core.append(b"hello").await?;
core.key_pair().public
};
let store = Corestore::new_disk(&dir).await?;
let core = store.get_from_name("feed").await?;
assert_eq!(core.key_pair().public, key, "named core changed identity");
assert_eq!(core.get(0).await?.as_deref(), Some(&b"hello"[..]));
Ok(())
}
fn create_connected_streams() -> (impl CipherTrait + 'static, impl CipherTrait + 'static) {
let (a_b, b_a) = tokio::io::duplex(64 * 1024);
let a_b = Uint24LELengthPrefixedFraming::new(a_b.compat());
let b_a = Uint24LELengthPrefixedFraming::new(b_a.compat());
let keypair = generate_keypair().unwrap();
let initiator = Cipher::new(
Some(Box::new(a_b)),
SecStream::new_initiator_xx(&[]).unwrap().into(),
);
let responder = Cipher::new(
Some(Box::new(b_a)),
SecStream::new_responder_xx(&keypair, &[]).unwrap().into(),
);
(initiator, responder)
}
const TEST_PK: PrimaryKey = [
124, 229, 174, 223, 232, 201, 160, 10, 235, 143, 37, 249, 107, 92, 35, 125, 68, 246, 2,
197, 41, 248, 234, 65, 9, 222, 77, 144, 50, 243, 222, 65,
];
#[tokio::test]
async fn disk_core_by_name() -> Result<()> {
let storage_dir = tempfile::tempdir().unwrap();
let mut pk = TEST_PK;
pk[0] = 0;
let cs = CorestoreBuilder::default()
.primary_key(pk)
.storage(StorageKind::new_disk(storage_dir.path()))
.build()
.await?;
let hc = cs.get_from_name("foo").await?;
hc.append(b"hello").await?;
assert_eq!(hc.get(0).await?, Some(b"hello".to_vec()));
let vk = hc.key_pair().public;
let core_path = storage_dir.path().join(get_storage_root(&vk));
assert!(core_path.exists());
let hc2 = cs.get_from_verifying_key(&vk).await?;
assert_eq!(hc2.get(0).await?, Some(b"hello".to_vec()));
Ok(())
}
#[tokio::test]
async fn primary_key_cstore_dir_gets_used() -> Result<()> {
let storage_dir = tempfile::tempdir().unwrap();
let mut pk = TEST_PK;
pk[0] = 1;
{
let cs = CorestoreBuilder::default()
.primary_key(pk)
.storage(StorageKind::new_disk(storage_dir.path()))
.build()
.await?;
let hc = cs.get_from_name("foo").await?;
hc.append(b"hello").await?;
}
{
let cs = CorestoreBuilder::default()
.storage(StorageKind::new_disk(storage_dir.path()))
.build()
.await?;
let hc = cs.get_from_name("foo").await?;
assert_eq!(hc.get(0).await?, Some(b"hello".to_vec()));
}
{
assert!(matches!(
CorestoreBuilder::default()
.storage(StorageKind::new_disk(storage_dir.path()))
.primary_key(pk)
.build()
.await,
Err(Error::PrimaryKeyConflict(_))
));
}
Ok(())
}
#[tokio::test]
async fn prexisting_cores_replicate() -> Result<()> {
let (cs_a, cs_b) = (Corestore::new_mem().await, Corestore::new_mem().await);
let (a, b) = create_connected_streams();
let name = "foo";
let core_a = cs_a.get_from_name(name).await?;
let vk = core_a.key_pair().public;
let core_b = cs_b.get_from_verifying_key(&vk).await?;
core_a.append(b"hello").await?;
let before_replicating = core_b
.get_with_options(0, GetOptions::without_waiting())
.await?;
assert!(before_replicating.is_none());
tokio::spawn(cs_a.replicate(a));
tokio::spawn(cs_b.replicate(b));
assert_eq!(replicated_block(&core_b, 0).await?, b"hello");
Ok(())
}
#[tokio::test]
async fn new_cores_replicate() -> Result<()> {
let (cs_a, cs_b) = (Corestore::new_mem().await, Corestore::new_mem().await);
let (a, b) = create_connected_streams();
tokio::spawn(cs_a.replicate(a));
tokio::spawn(cs_b.replicate(b));
let name = "foo";
let core_a = cs_a.get_from_name(name).await?;
core_a.append(b"hello").await?;
let vk = core_a.key_pair().public;
let core_b = cs_b.get_from_verifying_key(&vk).await?;
core_a.append(b"world").await?;
assert_eq!(replicated_block(&core_b, 0).await?, b"hello");
assert_eq!(replicated_block(&core_b, 1).await?, b"world");
Ok(())
}
#[tokio::test]
async fn a_core_opened_after_the_connection_goes_quiet_replicates() -> Result<()> {
let (cs_a, cs_b) = (Corestore::new_mem().await, Corestore::new_mem().await);
let (a, b) = create_connected_streams();
let bootstrap_a = cs_a.get_from_name("bootstrap").await?;
bootstrap_a.append(b"bootstrap").await?;
let bootstrap_b = cs_b
.get_from_verifying_key(&bootstrap_a.key_pair().public)
.await?;
let late_a = cs_a.get_from_name("late").await?;
late_a.append(b"late hello").await?;
tokio::spawn(cs_a.replicate(a));
tokio::spawn(cs_b.replicate(b));
assert_eq!(replicated_block(&bootstrap_b, 0).await?, b"bootstrap");
let late_b = cs_b
.get_from_verifying_key(&late_a.key_pair().public)
.await?;
assert_eq!(replicated_block(&late_b, 0).await?, b"late hello");
Ok(())
}
#[tokio::test]
async fn concurrent_opens_of_one_key_share_one_core() -> Result<()> {
let tmp = tempfile::tempdir().expect("tempdir");
let store = Corestore::new_disk(tmp.path()).await?;
let (first, second) =
tokio::join!(store.get_from_name("feed"), store.get_from_name("feed"));
let (first, second) = (first?, second?);
first.append(b"hello").await?;
assert_eq!(second.info().length, 1, "both handles are the same core");
Ok(())
}
#[tokio::test]
async fn concurrent_opens_announce_the_core_once() -> Result<()> {
let tmp = tempfile::tempdir().expect("tempdir");
let store = Corestore::new_disk(tmp.path()).await?;
let mut events = store.subscribe();
let (first, second) =
tokio::join!(store.get_from_name("feed"), store.get_from_name("feed"));
let vk = first?.key_pair().public;
second?;
assert!(matches!(events.try_recv(), Ok(CorestoreEvents::CoreAdded(added)) if added == vk));
assert!(events.try_recv().is_err(), "announced only once");
Ok(())
}
#[tokio::test]
async fn a_failed_open_can_be_retried() -> Result<()> {
let tmp = tempfile::tempdir().expect("tempdir");
let store = Corestore::new_disk(tmp.path()).await?;
let key_pair = key_pair_from_name(store.read().primary_key(), &DEFAULT_NAMESPACE, "feed")?;
let blocker = tmp.path().join(get_storage_root(&key_pair));
std::fs::create_dir_all(blocker.parent().unwrap()).unwrap();
std::fs::write(&blocker, b"not a directory").unwrap();
assert!(matches!(
store.get_from_name("feed").await,
Err(Error::Opening(_))
));
assert!(
store.read().core_cache.get(&key_pair.public).is_none(),
"a failure is not cached"
);
std::fs::remove_file(&blocker).unwrap();
let core = store.get_from_name("feed").await?;
assert_eq!(core.key_pair().public, key_pair.public);
Ok(())
}
#[tokio::test]
async fn multiple_cores_multiplex_over_one_connection() -> Result<()> {
let (cs_a, cs_b) = (Corestore::new_mem().await, Corestore::new_mem().await);
let (a, b) = create_connected_streams();
let foo_a = cs_a.get_from_name("foo").await?;
let bar_a = cs_a.get_from_name("bar").await?;
foo_a.append(b"foo hello").await?;
bar_a.append(b"bar hello").await?;
let foo_b = cs_b
.get_from_verifying_key(&foo_a.key_pair().public)
.await?;
let bar_b = cs_b
.get_from_verifying_key(&bar_a.key_pair().public)
.await?;
tokio::spawn(cs_a.replicate(a));
tokio::spawn(cs_b.replicate(b));
assert_eq!(replicated_block(&foo_b, 0).await?, b"foo hello");
assert_eq!(replicated_block(&bar_b, 0).await?, b"bar hello");
Ok(())
}
}
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;