aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/store/entry.rs
blob: f19c44ff321910bbdb934deaae7f40c3c6d7e1db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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);
    }
}