aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/event.rs
blob: fc519d05bcc4721533f175f8602a80a8624db994 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//! The federation's events, and its checkpoints, as bytes (`docs/federation.md`, Events,
//! Checkpoints): what each holds, and what makes one none.

use super::jcs::{self, Json};
use super::keys;
use super::store::Id;
use super::version::{self, Version};
use crate::access::sshsig::PublicKey;

/// The most bytes an event may have.
pub(crate) const LARGEST: usize = 256 * 1024;

/// Dependencies an event may name.
pub(crate) const DEPENDENCIES: usize = 64;

/// An event, read from its bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Event {
    /// What a party signs.
    Signed(Signed),
    /// A version event: a version written once its proposal passed, signed by nobody.
    Version { deps: Vec<Id>, version: Id },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Signed {
    pub(crate) deps: Vec<Id>,
    pub(crate) party: String,
    /// The key it is signed with, as the event spells it.
    pub(crate) key: String,
    pub(crate) does: Does,
}

/// What a signed event does.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Does {
    /// A value at a place: `null` empties it.
    Write { path: Vec<String>, value: Json },
    /// The party's key set.
    Keys(Vec<String>),
    /// The party's node list.
    Nodes(Vec<String>),
    /// A version proposed, taken whatever it holds: whether it is one is asked where a
    /// version event names it. Its hash is the version's.
    Proposal { hash: Id, version: Json },
    /// A vote on a proposal (`proposal`) on a version (`on`).
    Vote { on: Id, proposal: Id, yes: bool },
}

impl Event {
    /// The event `bytes` are, where they are one: none where they aren't the JCS encoding
    /// of the JSON they read as, a field is missing or more, `key` or `sig` doesn't read
    /// back to itself, the signature doesn't hold, or it is larger than federation 1
    /// allows.
    pub(crate) fn read(bytes: &[u8]) -> Option<Event> {
        Self::parse(bytes, true)
    }

    /// The event `bytes` are, as `read` reads them, but for its signature, which isn't
    /// checked: for bytes a store took already, whose signature held then.
    pub(crate) fn read_taken(bytes: &[u8]) -> Option<Event> {
        Self::parse(bytes, false)
    }

    fn parse(bytes: &[u8], verify: bool) -> Option<Event> {
        if bytes.len() > LARGEST {
            return None;
        }
        let json = jcs::read(bytes)?;
        let deps = version::ascending_ids(json.get("deps")?)?;
        if deps.is_empty() || deps.len() > DEPENDENCIES {
            return None;
        }
        let names = json.names();
        if names == ["deps", "version"] {
            let version = Id::from_hex(json.get("version")?.as_str()?)?;
            return Some(Event::Version { deps, version });
        }
        let does = ["write", "keys", "nodes", "proposal", "vote"]
            .into_iter()
            .find(|name| names.contains(name))?;
        let mut expected = vec!["deps", "key", "party", "sig", does];
        expected.sort_by(|a, b| jcs::names_order(a, b));
        if names != expected {
            return None;
        }
        let party = json.get("party")?.as_str()?;
        let key = json.get("key")?.as_str()?;
        let public = keys::key(key)?;
        if !version::is_party(party) {
            return None;
        }
        let sig = json.get("sig")?.as_str()?;
        if verify && !keys::verifies(&public, sig, &json.without("sig").bytes()) {
            return None;
        }
        let what = json.get(does)?;
        let does = match does {
            "write" => {
                if what.names() != ["path", "value"] {
                    return None;
                }
                Does::Write {
                    path: version::path(what.get("path")?.as_str()?)?,
                    value: what.get("value")?.clone(),
                }
            }
            "keys" => {
                let set = strings(what)?;
                if set.len() > version::KEYS || !set.iter().all(|key| keys::key(key).is_some()) {
                    return None;
                }
                Does::Keys(set)
            }
            "nodes" => {
                let list = strings(what)?;
                if list.len() > version::NODES || !list.iter().all(|id| keys::node_id(id)) {
                    return None;
                }
                Does::Nodes(list)
            }
            "proposal" => Does::Proposal {
                hash: Id::of(&what.bytes()),
                version: what.clone(),
            },
            _ => {
                if what.names() != ["on", "proposal", "yes"] {
                    return None;
                }
                Does::Vote {
                    on: Id::from_hex(what.get("on")?.as_str()?)?,
                    proposal: Id::from_hex(what.get("proposal")?.as_str()?)?,
                    yes: what.get("yes")?.as_bool()?,
                }
            }
        };
        Some(Event::Signed(Signed {
            deps,
            party: party.to_owned(),
            key: key.to_owned(),
            does,
        }))
    }

    pub(crate) fn deps(&self) -> &[Id] {
        match self {
            Event::Signed(signed) => &signed.deps,
            Event::Version { deps, .. } => deps,
        }
    }

    /// The key a signed event is signed with.
    pub(crate) fn public(signed: &Signed) -> PublicKey {
        keys::key(&signed.key).expect("an event's key was read as one")
    }
}

/// Strings a JSON array holds, where it holds strings only, none twice.
fn strings(json: &Json) -> Option<Vec<String>> {
    let items = json
        .as_array()?
        .iter()
        .map(|item| item.as_str().map(str::to_owned))
        .collect::<Option<Vec<String>>>()?;
    let mut sorted = items.clone();
    sorted.sort();
    sorted.dedup();
    (sorted.len() == items.len()).then_some(items)
}

/// A checkpoint, a federation's root and a fork's among them: the heads it is at, the
/// events it keeps, and its version.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Checkpoint {
    pub(crate) at: Vec<Id>,
    pub(crate) keeps: Vec<Id>,
    pub(crate) version: Version,
}

impl Checkpoint {
    /// The checkpoint `bytes` are, where they are one: the JCS encoding of
    /// `{"at": [<IDs>], "keeps": [<IDs>], "version": <version>}`, its IDs ascending, its
    /// version one by itself.
    pub(crate) fn read(bytes: &[u8]) -> Option<Checkpoint> {
        let json = jcs::read(bytes)?;
        if json.names() != ["at", "keeps", "version"] {
            return None;
        }
        Some(Checkpoint {
            at: version::ascending_ids(json.get("at")?)?,
            keeps: version::ascending_ids(json.get("keeps")?)?,
            version: Version::read(json.get("version")?).ok()?,
        })
    }

    /// Its bytes.
    pub(crate) fn bytes(&self) -> Vec<u8> {
        let ids =
            |ids: &[Id]| Json::Array(ids.iter().map(|id| Json::Str(id.to_string())).collect());
        Json::object(vec![
            ("at".to_owned(), ids(&self.at)),
            ("keeps".to_owned(), ids(&self.keeps)),
            ("version".to_owned(), self.version.json.clone()),
        ])
        .expect("three names")
        .bytes()
    }
}

#[cfg(test)]
mod tests {
    use super::super::harness::{self, Party, Spec};
    use super::*;

    fn tv() -> Party {
        Party::new("tv", 1)
    }

    fn dep() -> Id {
        Id::of(b"a dependency")
    }

    #[test]
    fn every_kind_of_event_reads_back() {
        let tv = tv();
        let read = |bytes: Vec<u8>| match Event::read(&bytes) {
            Some(Event::Signed(signed)) => signed.does,
            other => panic!("not a signed event: {other:?}"),
        };
        assert!(matches!(
            read(tv.write(&[dep()], "home/tv/x", harness::str("1"))),
            Does::Write { .. }
        ));
        assert_eq!(
            read(tv.keys(&[dep()], &[tv.key_line()])),
            Does::Keys(vec![tv.key_line()])
        );
        assert_eq!(
            read(tv.nodes(&[dep()], &[harness::node_id(1)])),
            Does::Nodes(vec![harness::node_id(1)])
        );
        let spec = Spec::first(&[&tv], &[]);
        assert!(matches!(
            read(tv.propose(&[dep()], &spec.json())),
            Does::Proposal { hash, .. } if hash == spec.hash()
        ));
        assert_eq!(
            read(tv.vote(&[dep()], dep(), spec.hash(), true)),
            Does::Vote {
                on: dep(),
                proposal: spec.hash(),
                yes: true
            }
        );
        assert_eq!(
            Event::read(&harness::version_event(&[dep()], spec.hash())),
            Some(Event::Version {
                deps: vec![dep()],
                version: spec.hash()
            })
        );
    }

    #[test]
    fn an_event_spelled_otherwise_is_none() {
        let tv = tv();
        let value = || {
            (
                "write",
                harness::object(vec![("path", harness::str("a")), ("value", Json::Null)]),
            )
        };
        let none = |bytes: Vec<u8>| assert_eq!(Event::read(&bytes), None);
        // Signed by another key, or its key with a comment.
        none(tv.signed_as(&Party::new("x", 2).key, &tv.key_line(), &[dep()], value()));
        none(tv.signed_as(&tv.key, &format!("{} tv", tv.key_line()), &[dep()], value()));
        // Dependencies: none, or more than federation 1 allows.
        none(tv.sign(&[], value()));
        let many: Vec<Id> = (0..=DEPENDENCIES)
            .map(|i| Id::of(&i.to_be_bytes()))
            .collect();
        none(tv.sign(&many, value()));
        assert!(Event::read(&tv.sign(&many[1..], value())).is_some());
        // A party that is no party's name.
        none(Party::new("t v", 1).sign(&[dep()], value()));
        // A field more.
        let unsigned = harness::object(vec![
            ("deps", harness::ids(&[dep()])),
            ("party", harness::str("tv")),
            ("key", harness::str(&tv.key_line())),
            value(),
            ("more", Json::Null),
        ]);
        let sig = keys::sign(&tv.key, &unsigned.bytes());
        let Json::Object(mut members) = unsigned else {
            unreachable!()
        };
        members.push(("sig".to_owned(), Json::Str(sig)));
        none(Json::object(members).expect("an object").bytes());
        // Larger than federation 1 allows.
        none(tv.write(&[dep()], "a", Json::Str("x".repeat(LARGEST))));
        // A node ID or key spelled otherwise, or more keys than a set may hold.
        none(tv.nodes(&[dep()], &[harness::node_id(1).to_uppercase()]));
        let keys: Vec<String> = (1..=17).map(harness::key_line).collect();
        none(tv.keys(&[dep()], &keys));
        assert!(Event::read(&tv.keys(&[dep()], &keys[1..])).is_some());
        // Its bytes changed after it was signed.
        let signed = String::from_utf8(tv.write(&[dep()], "a", harness::str("1"))).expect("UTF-8");
        none(signed.replace(r#""1""#, r#""2""#).into_bytes());
    }

    #[test]
    fn a_checkpoint_reads_back_and_is_no_event() {
        let spec = Spec::first(&[&tv()], &[]);
        let checkpoint = Checkpoint {
            at: Vec::new(),
            keeps: Vec::new(),
            version: Version::read(&spec.json()).expect("a version"),
        };
        assert_eq!(
            Checkpoint::read(&checkpoint.bytes()),
            Some(checkpoint.clone())
        );
        assert_eq!(Event::read(&checkpoint.bytes()), None);
    }
}