diff options
Diffstat (limited to 'src/federation/store')
| -rw-r--r-- | src/federation/store/entry.rs | 176 | ||||
| -rw-r--r-- | src/federation/store/memory.rs | 12 | ||||
| -rw-r--r-- | src/federation/store/mod.rs | 1 | ||||
| -rw-r--r-- | src/federation/store/set.rs | 212 | ||||
| -rw-r--r-- | src/federation/store/testfold.rs | 13 |
5 files changed, 412 insertions, 2 deletions
diff --git a/src/federation/store/entry.rs b/src/federation/store/entry.rs new file mode 100644 index 0000000..f19c44f --- /dev/null +++ b/src/federation/store/entry.rs @@ -0,0 +1,176 @@ +//! A member's entry in a set of events (`docs/document.md`, A set of events): what a +//! node says of itself, where it is reached and what else its peers read of it, written +//! by that node alone and signed with its node key. Of a node's entries the one with the +//! highest count is its entry; of two of one count, which only a node that says two +//! things at once makes, the one with the lower name. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::Id; +use crate::document::ranges::Name; +use crate::identity::{self, NodeKey}; + +/// The most bytes an entry's value may have. +pub(crate) const LARGEST: usize = 16 << 10; + +/// What a node signs of its entry, ahead of the store, itself, the count and the value. +const SIGNS: &[u8] = b"continuum-entry\0"; + +/// A node's entry, as passed on and as kept. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Entry { + /// The node's public key: its ID is of it. + #[serde(with = "serde_bytes")] + key: [u8; 32], + /// Which of the node's entries: each later one counts higher. + count: u64, + /// The entry: a JSON map, as bytes. + #[serde(with = "serde_bytes")] + value: Vec<u8>, + /// The node's signature (`SIGNS`). + #[serde(with = "serde_bytes")] + signature: [u8; 64], +} + +fn signed(store: &Id, key: &[u8; 32], count: u64, value: &[u8]) -> Vec<u8> { + let mut message = Vec::with_capacity(SIGNS.len() + 32 + 32 + 8 + value.len()); + message.extend_from_slice(SIGNS); + message.extend_from_slice(&store.0); + message.extend_from_slice(key); + message.extend_from_slice(&count.to_le_bytes()); + message.extend_from_slice(value); + message +} + +impl Entry { + /// The entry of the node with `key` in the store `store`, its `count`th, holding + /// `value`. + pub(crate) fn new(store: &Id, key: &NodeKey, count: u64, value: &serde_json::Value) -> Self { + let value = serde_json::to_vec(value).expect("JSON encodes"); + let public = key.public(); + let signature = key.sign(&signed(store, &public, count, &value)); + Self { + key: public, + count, + value, + signature, + } + } + + /// The node whose entry it is, by its ID. + pub(crate) fn node(&self) -> String { + identity::node_id_of(&self.key) + } + + pub(crate) fn count(&self) -> u64 { + self.count + } + + /// What it holds: a JSON map, where the entry checks. + pub(crate) fn value(&self) -> Option<serde_json::Map<String, serde_json::Value>> { + match serde_json::from_slice(&self.value) { + Ok(serde_json::Value::Object(map)) => Some(map), + _ => None, + } + } + + /// Why the entry isn't one of the store `store`, where it isn't: too large, no JSON + /// map, or not signed by its node for that store. + pub(crate) fn checks(&self, store: &Id) -> Result<(), &'static str> { + if self.value.len() > LARGEST { + return Err("an entry larger than an entry may be"); + } + if self.value().is_none() { + return Err("an entry that is no JSON map"); + } + let message = signed(store, &self.key, self.count, &self.value); + if !identity::verify(&self.key, &message, &self.signature) { + return Err("an entry its node didn't sign for this store"); + } + Ok(()) + } + + /// The entry as bytes, as it is passed on. + pub(crate) fn encode(&self) -> Vec<u8> { + rmp_serde::to_vec(self).expect("an entry encodes") + } + + /// An entry from its bytes, where they are one's and nothing else. + pub(crate) fn decode(bytes: &[u8]) -> Option<Self> { + let entry: Self = rmp_serde::from_slice(bytes).ok()?; + (entry.encode() == bytes).then_some(entry) + } + + /// The entry's name, to catch up by: of its bytes, as an event's is. + pub(crate) fn name(&self) -> Name { + Sha256::digest(self.encode()).into() + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn key(seed: u8) -> NodeKey { + NodeKey::from_seed([seed; 32]) + } + + #[test] + fn an_entry_checks_for_its_store_alone() { + let store = Id::of(b"a store"); + let entry = Entry::new(&store, &key(1), 3, &json!({"addresses": ["a"]})); + assert_eq!(entry.checks(&store), Ok(())); + assert_eq!(entry.node(), key(1).id()); + assert_eq!(entry.count(), 3); + assert_eq!(entry.value().expect("a map")["addresses"], json!(["a"])); + assert!(entry.checks(&Id::of(b"another")).is_err()); + } + + #[test] + fn an_entry_changed_checks_no_more() { + let store = Id::of(b"a store"); + let entry = Entry::new(&store, &key(1), 3, &json!({"alias": "a"})); + let mut counted = entry.clone(); + counted.count = 4; + assert!(counted.checks(&store).is_err()); + let mut valued = entry.clone(); + valued.value = br#"{"alias":"b"}"#.to_vec(); + assert!(valued.checks(&store).is_err()); + let mut keyed = entry; + keyed.key = key(2).public(); + assert!(keyed.checks(&store).is_err()); + } + + #[test] + fn an_entry_is_a_map_of_no_more_than_its_size() { + let store = Id::of(b"a store"); + assert!( + Entry::new(&store, &key(1), 0, &json!([1])) + .checks(&store) + .is_err() + ); + let large = "a".repeat(LARGEST); + assert!( + Entry::new(&store, &key(1), 0, &json!({"alias": large})) + .checks(&store) + .is_err() + ); + } + + #[test] + fn an_entry_reads_back_from_its_bytes() { + let store = Id::of(b"a store"); + let entry = Entry::new(&store, &key(1), 3, &json!({"alias": "a"})); + let bytes = entry.encode(); + assert_eq!(Entry::decode(&bytes), Some(entry.clone())); + assert_eq!(entry.name(), <Name>::from(Sha256::digest(&bytes))); + // Bytes that read as one and aren't its own are none. + let mut longer = bytes; + longer.push(0); + assert_eq!(Entry::decode(&longer), None); + assert_eq!(Entry::decode(b"no entry"), None); + } +} diff --git a/src/federation/store/memory.rs b/src/federation/store/memory.rs index 289e5b4..781ba01 100644 --- a/src/federation/store/memory.rs +++ b/src/federation/store/memory.rs @@ -244,6 +244,18 @@ impl<F: Fold> Store<F> { self.refused.get(id) } + /// Whether the store has seen an event: holds it, by its bytes or its name alone, + /// forgot it at a checkpoint, refused it, has it wait, or holds it back. + pub(crate) fn knows(&self, id: &Id) -> bool { + self.events.contains_key(id) + || self.kept.contains_key(id) + || self.heads.contains(id) + || self.forgotten.contains(id) + || self.refused.contains_key(id) + || self.waiting.contains_key(id) + || self.holding_back.contains(id) + } + /// Whether an event waits for dependencies the store doesn't hold. pub(crate) fn is_waiting(&self, id: &Id) -> bool { self.waiting.contains_key(id) diff --git a/src/federation/store/mod.rs b/src/federation/store/mod.rs index b678647..c3fa106 100644 --- a/src/federation/store/mod.rs +++ b/src/federation/store/mod.rs @@ -8,6 +8,7 @@ use sha2::{Digest, Sha256}; use crate::transport::Hex; +pub(crate) mod entry; pub(crate) mod memory; #[cfg(test)] mod properties; diff --git a/src/federation/store/set.rs b/src/federation/store/set.rs index 559c157..88dfa73 100644 --- a/src/federation/store/set.rs +++ b/src/federation/store/set.rs @@ -10,12 +10,16 @@ //! * what a move to a checkpoint forgot, for as long as the node's operator says: a node //! still before the checkpoint builds it from them. //! +//! And each member's entry (`entry`): its node's newest, and none of a node the store +//! doesn't name a member as it reads now. +//! //! What the fold refuses at its history, and what isn't one of its events, is held by //! nobody. use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::time::{Duration, Instant}; +use super::entry::Entry; use super::memory::{Gone, Offered, Refusal, Store}; use super::{Fold, Id, Refused}; use crate::document::ranges::Name; @@ -38,6 +42,32 @@ pub(crate) enum Beside { Forgotten(Instant), } +/// The most names of strangers' entries remembered. +const STRANGERS: usize = 1024; + +/// What became of an entry put. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Put { + /// It is its node's entry now. + Taken, + /// It is its node's entry already. + Held, + /// The document holds a newer one of its node. + Older, + /// Its node is no member, as the store reads now. + Stranger, + /// It is no entry of this store, and why. + Refused(&'static str), +} + +/// The nodes that carry `store`, as it reads now. +fn members_of<F: Fold>(store: &Store<F>) -> BTreeSet<String> { + F::members(store.state()) + .into_iter() + .map(|(node, _)| node) + .collect() +} + /// A set of events, of a fold `F`. pub(crate) struct Set<F: Fold> { store: Store<F>, @@ -48,20 +78,84 @@ pub(crate) struct Set<F: Fold> { unjudged_bytes: usize, /// For how long what a checkpoint forgot is kept. keeps_forgotten: Duration, + /// Who carries the store, as it reads now (`Fold::members`). + members: BTreeSet<String>, + /// Each member's entry, by its node. + entries: BTreeMap<String, Entry>, + /// Entries of nodes that are no members, by name: not asked for again until who is + /// one changes. No more than `STRANGERS`. + strangers: BTreeSet<Name>, } impl<F: Fold> Set<F> { /// The document of `store`, keeping what a checkpoint forgot for `keeps_forgotten`. pub(crate) fn new(store: Store<F>, keeps_forgotten: Duration) -> Self { + let members = members_of::<F>(&store); Self { store: store.telling(), beside: BTreeMap::new(), unjudged: VecDeque::new(), unjudged_bytes: 0, keeps_forgotten, + members, + entries: BTreeMap::new(), + strangers: BTreeSet::new(), + } + } + + /// Takes a member's entry, where it is its node's newest: of a higher count than the + /// one held, or of the same and a lower name. + pub(crate) fn put_entry(&mut self, entry: Entry) -> Put { + if let Err(why) = entry.checks(&self.store.id()) { + return Put::Refused(why); + } + let node = entry.node(); + if !self.members.contains(&node) { + if self.strangers.len() < STRANGERS { + self.strangers.insert(entry.name()); + } + return Put::Stranger; + } + match self.entries.get(&node) { + Some(held) if *held == entry => Put::Held, + Some(held) + if held.count() > entry.count() + || (held.count() == entry.count() && held.name() < entry.name()) => + { + Put::Older + } + _ => { + self.entries.insert(node, entry); + Put::Taken + } } } + /// The entry of the member `node`, where the document holds one. + pub(crate) fn entry(&self, node: &str) -> Option<&Entry> { + self.entries.get(node) + } + + /// The members' entries, in the order of their nodes. + pub(crate) fn entries(&self) -> impl Iterator<Item = &Entry> { + self.entries.values() + } + + /// The entry named `name`, where the document holds it. + pub(crate) fn entry_named(&self, name: &Name) -> Option<&Entry> { + self.entries.values().find(|entry| entry.name() == *name) + } + + /// Whether the document would have what is named `name`, which a peer holds: not + /// what it holds, what its store refused, waits for or let go of, nor an entry of a + /// node that is no member. + pub(crate) fn wants(&self, name: &Name) -> bool { + !self.store.knows(&Id(*name)) + && !self.beside.contains_key(&Id(*name)) + && !self.strangers.contains(name) + && self.entry_named(name).is_none() + } + /// The store: what the node reads. pub(crate) fn store(&self) -> &Store<F> { &self.store @@ -111,6 +205,12 @@ impl<F: Fold> Set<F> { /// Takes in what the store let go of. fn settle(&mut self, now: Instant) { + let members = members_of::<F>(&self.store); + if members != self.members { + self.entries.retain(|node, _| members.contains(node)); + self.strangers.clear(); + self.members = members; + } for (id, bytes, gone) in self.store.let_go() { let why = match gone { Gone::Forgotten => Beside::Forgotten(now), @@ -206,6 +306,7 @@ impl<F: Fold> Set<F> { .map(|id| id.0) .chain(self.store.kept().iter().map(|bytes| Id::of(bytes).0)) .chain(self.beside.keys().map(|id| id.0)) + .chain(self.entries.values().map(Entry::name)) .collect() } } @@ -390,4 +491,115 @@ mod tests { assert_eq!(set.get(&first_id), None); assert!(!set.names().contains(&first_id.0)); } + + fn key(seed: u8) -> crate::identity::NodeKey { + crate::identity::NodeKey::from_seed([seed; 32]) + } + + /// Makes the node of `key` a member of group `group` (none: no member), on `on`. + fn member(set: &mut Set<TestFold>, on: Id, key: u8, group: &str) -> Id { + let node = self::key(key).id(); + taken(set.offer( + testfold::put(&[on], &format!("node:{node}"), group), + Instant::now(), + )) + } + + fn entry(set: &Set<TestFold>, key: u8, count: u64, alias: &str) -> Entry { + Entry::new( + &set.store().id(), + &self::key(key), + count, + &serde_json::json!({ "alias": alias }), + ) + } + + #[test] + fn a_members_newest_entry_is_its_entry() { + let mut set = set(); + let root = set.store().id(); + member(&mut set, root, 1, "a"); + let node = key(1).id(); + let first = entry(&set, 1, 1, "one"); + assert_eq!(set.put_entry(first.clone()), Put::Taken); + assert_eq!(set.put_entry(first.clone()), Put::Held); + assert_eq!(set.entry(&node), Some(&first)); + assert!(set.names().contains(&first.name())); + assert!(!set.wants(&first.name())); + let second = entry(&set, 1, 2, "two"); + assert!(set.wants(&second.name())); + assert_eq!(set.put_entry(second.clone()), Put::Taken); + assert_eq!(set.put_entry(first.clone()), Put::Older); + assert_eq!(set.entry(&node), Some(&second)); + assert!(!set.names().contains(&first.name())); + assert_eq!(set.entry_named(&second.name()), Some(&second)); + assert_eq!(set.entries().count(), 1); + } + + #[test] + fn of_two_entries_of_one_count_the_lower_name_is_kept() { + let mut set = set(); + let root = set.store().id(); + member(&mut set, root, 1, "a"); + let (one, other) = (entry(&set, 1, 1, "one"), entry(&set, 1, 1, "other")); + let (low, high) = if one.name() < other.name() { + (one, other) + } else { + (other, one) + }; + // Whichever comes first. + assert_eq!(set.put_entry(high.clone()), Put::Taken); + assert_eq!(set.put_entry(low.clone()), Put::Taken); + assert_eq!(set.put_entry(high), Put::Older); + assert_eq!(set.entry(&key(1).id()), Some(&low)); + } + + #[test] + fn an_entry_of_no_member_is_held_by_nobody() { + let mut set = set(); + let root = set.store().id(); + let stranger = entry(&set, 2, 1, "stranger"); + assert_eq!(set.put_entry(stranger.clone()), Put::Stranger); + assert_eq!(set.entry(&key(2).id()), None); + // Not asked for again, until who is a member changes. + assert!(!set.wants(&stranger.name())); + let made = member(&mut set, root, 2, "a"); + assert!(set.wants(&stranger.name())); + assert_eq!(set.put_entry(stranger.clone()), Put::Taken); + // And gone with its node. + member(&mut set, made, 2, ""); + assert_eq!(set.entry(&key(2).id()), None); + assert!(!set.names().contains(&stranger.name())); + } + + #[test] + fn an_entry_of_another_store_or_changed_is_refused() { + let mut set = set(); + let root = set.store().id(); + member(&mut set, root, 1, "a"); + let other = Entry::new( + &Id::of(b"another store"), + &key(1), + 1, + &serde_json::json!({}), + ); + assert!(matches!(set.put_entry(other), Put::Refused(_))); + assert_eq!(set.entries().count(), 0); + } + + #[test] + fn what_the_store_has_seen_isnt_wanted() { + let mut set = set(); + let now = Instant::now(); + let root = set.store().id(); + let put = testfold::put(&[root], "a", "1"); + let junk = testfold::junk(&[root]); + let waits = testfold::put(&[Id::of(b"nowhere")], "a", "1"); + for bytes in [&put, &junk, &waits] { + assert!(set.wants(&Id::of(bytes).0)); + set.offer(bytes.clone(), now); + assert!(!set.wants(&Id::of(bytes).0)); + } + assert!(!set.wants(&root.0)); + } } diff --git a/src/federation/store/testfold.rs b/src/federation/store/testfold.rs index 6dd1460..1b26a4e 100644 --- a/src/federation/store/testfold.rs +++ b/src/federation/store/testfold.rs @@ -452,7 +452,16 @@ impl Fold for TestFold { (heads.iter().copied().collect::<BTreeSet<_>>() != now.at).then(|| heads.clone()) } - fn members(_state: &State) -> Vec<(String, String)> { - Vec::new() + /// The nodes named by what counts at keys `node:<node ID>`, each with what the key + /// holds as its group; none where it holds nothing. + fn members(state: &State) -> Vec<(String, String)> { + state + .counts() + .into_iter() + .filter_map(|(key, group)| { + let node = key.strip_prefix("node:")?; + (!group.is_empty()).then(|| (node.to_owned(), group)) + }) + .collect() } } |
