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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
//! A swarm holding a store at a node's API (`docs/store.md`, Members): whoever its operator
//! lets in may have it put events, whoever signed them; it shows its store (its ID, its
//! checkpoint and its heads), an event it holds, what its fold reads from them, what it
//! refused, and what it finds of a fork's root; and its operator has it drop what it
//! took, take it back, and make a fork's root.
use axum::{
Extension, Json, Router,
body::Bytes,
extract::{Path, State},
http::{StatusCode, header::CONTENT_TYPE},
response::{IntoResponse, Response},
routing::{get, post},
};
use serde::Deserialize;
use serde_json::{Value as JsonValue, json};
use super::auth::AuthenticatedUser;
use super::{ApiError, error_response, store_status};
use crate::federation::fold::Federation;
use crate::federation::fork;
use crate::federation::jcs::Json as Jcs;
use crate::federation::store::Id;
use crate::federation::store::memory::{Offered, Refusal, Store};
use crate::state::AppState;
pub(super) fn router() -> Router<AppState> {
Router::new()
.route("/events", get(summary).post(put))
.route("/events/counts", get(counts))
.route("/events/refused", get(refused))
.route("/events/fork", post(check_fork))
.route("/events/{id}", get(event))
.route("/admin/events/drop", post(drop_taken))
.route("/admin/events/allow", post(allow))
.route("/admin/events/vote", post(vote))
.route("/admin/events/fork", post(make_fork))
}
/// The answer while the node holds no store.
fn no_store() -> Response {
error_response(
StatusCode::NOT_FOUND,
"this node holds no store: its swarm holds none, or it hasn't read it yet",
None,
)
}
/// `f` of the node's store, as JSON; `no_store` without one.
fn with_store(state: &AppState, f: impl FnOnce(&Store<Federation>) -> JsonValue) -> Response {
match state.holding.with(f) {
Some(body) => Json(body).into_response(),
None => no_store(),
}
}
fn ids(ids: impl IntoIterator<Item = Id>) -> Vec<String> {
ids.into_iter().map(|id| id.to_string()).collect()
}
/// A JCS value as plain JSON: its integers fit, by what an event may hold.
fn plain(json: &Jcs) -> JsonValue {
serde_json::from_slice(&json.bytes()).unwrap_or(JsonValue::Null)
}
/// Why the store refused an event, said.
fn why(refusal: &Refusal) -> String {
match refusal {
Refusal::None => "none of the federation's events, or larger than it allows".to_owned(),
Refusal::Judged(why) => why.0.clone(),
Refusal::BuiltOn(id) => format!("it builds on {id}, refused"),
Refusal::NotAbove => "it isn't above the checkpoint's heads".to_owned(),
Refusal::Own => {
"its history takes it, but this node doesn't, by what it took before".to_owned()
}
Refusal::Dropped => "this node's operator had it drop it".to_owned(),
}
}
/// `GET /events`: the store's ID, its checkpoint's, its heads, and how many events it
/// took after its checkpoint.
async fn summary(State(state): State<AppState>) -> Response {
with_store(&state, |store| {
json!({
"store": store.id().to_string(),
"checkpoint": Id::of(store.checkpoint()).to_string(),
"heads": ids(store.heads()),
"taken": store.taken().len(),
})
})
}
/// `GET /events/{id}`: an event the store holds, taken or kept by its checkpoint, or its
/// checkpoint, as its bytes.
async fn event(State(state): State<AppState>, Path(id): Path<String>) -> Response {
let Some(id) = Id::from_hex(&id) else {
return error_response(StatusCode::BAD_REQUEST, "not an event's ID", None);
};
let bytes = state.holding.with(|store| {
store
.get(&id)
.map(<[u8]>::to_vec)
.or_else(|| (Id::of(store.checkpoint()) == id).then(|| store.checkpoint().to_vec()))
});
match bytes {
None => no_store(),
Some(None) => error_response(StatusCode::NOT_FOUND, "no event this store holds", None),
Some(Some(bytes)) => ([(CONTENT_TYPE, "application/json")], bytes).into_response(),
}
}
/// `GET /events/counts`: what counts, as the store reads now: the current version, each
/// party's keys and nodes, the values at places, the members, and the proposals on the
/// current version, each with the events proposing it, the votes on it, the parties
/// voting `true` and `false`, and whether it passed and whether it is dead.
async fn counts(State(state): State<AppState>) -> Response {
with_store(&state, |store| {
let read = store.state();
let current = read.current();
let parties: serde_json::Map<String, JsonValue> = current
.parties
.keys()
.map(|party| {
(
party.clone(),
json!({
"keys": read.keys_of(party, current),
"nodes": read.nodes_of(party, current),
}),
)
})
.collect();
let values: serde_json::Map<String, JsonValue> = read
.values()
.iter()
.map(|(path, value)| (path.clone(), plain(value)))
.collect();
let proposals: serde_json::Map<String, JsonValue> = read
.ballots(¤t.hash)
.into_iter()
.map(|(hash, ballot)| {
let tally = read.tally(current, &hash);
(
hash.to_string(),
json!({
"proposals": ids(ballot.proposals),
"votes": ids(ballot.votes),
"yes": tally.yes,
"no": tally.no,
"passed": tally.passed,
"dead": tally.dead,
}),
)
})
.collect();
json!({
"version": {
"number": current.number,
"hash": current.hash.to_string(),
"version": plain(¤t.json),
},
"parties": parties,
"values": values,
"members": read.members(),
"proposals": proposals,
})
})
}
/// What kind of refusal it is, as a client tells them apart, and the event it builds on,
/// for one built on a refused one.
fn kind(refusal: &Refusal) -> (&'static str, Option<&Id>) {
match refusal {
Refusal::None => ("none", None),
Refusal::Judged(_) => ("judged", None),
Refusal::BuiltOn(id) => ("builtOn", Some(id)),
Refusal::NotAbove => ("notAbove", None),
Refusal::Own => ("own", None),
Refusal::Dropped => ("dropped", None),
}
}
/// `GET /events/refused`: what the store refused: of its own, by what it took before (the
/// federation: a version changing another than the one it reads), apart; what its
/// operator had it drop; and the rest, each with its kind and why.
async fn refused(State(state): State<AppState>) -> Response {
with_store(&state, |store| {
let (own, dropped) = store.own();
let mut rest: Vec<(&Id, &Refusal)> = store
.refused()
.filter(|(_, refusal)| !matches!(refusal, Refusal::Own | Refusal::Dropped))
.collect();
rest.sort_unstable_by_key(|(id, _)| **id);
json!({
"own": ids(own),
"dropped": ids(dropped),
"refused": rest
.into_iter()
.map(|(id, refusal)| {
let (kind, on) = kind(refusal);
let mut entry = json!({"id": id.to_string(), "kind": kind, "why": why(refusal)});
if let Some(on) = on {
entry["on"] = json!(on.to_string());
}
entry
})
.collect::<Vec<_>>(),
})
})
}
/// `POST /events`: puts an event, the request's body, whoever signed it: offered to the
/// store, and written into the document at its ID unless the store refuses it. Taken,
/// held already, or waiting for what it builds on.
async fn put(
State(state): State<AppState>,
Extension(AuthenticatedUser(user)): Extension<AuthenticatedUser>,
body: Bytes,
) -> Response {
let bytes = body.to_vec();
let id = Id::of(&bytes);
let became = match state.holding.offer(bytes.clone()) {
None => return no_store(),
Some(Offered::Refused(refusal)) => {
return error_response(
StatusCode::UNPROCESSABLE_ENTITY,
"the store refuses it",
Some(json!({"id": id.to_string(), "why": why(&refusal)})),
);
}
Some(Offered::Taken(_)) => "taken",
Some(Offered::Held) => "held",
Some(Offered::Waiting) => "waiting",
};
match crate::federation::held::write(&state, Some(user), bytes).await {
Ok(()) => Json(json!({"id": id.to_string(), "event": became})).into_response(),
Err(error) => store_status(error, "Failed to put an event").into_response(),
}
}
/// A vote by hand.
#[derive(Deserialize)]
struct ByHand {
proposal: String,
yes: bool,
}
/// `POST /admin/events/vote`: a vote by hand through this node, which votes for its party
/// by itself and keeps its party's one record: `yes` on the proposal of that hash on the
/// current version, by the record, and with a `true` by the voters' rule; signed with the
/// party's key the node keeps, recorded, and put.
async fn vote(
State(state): State<AppState>,
Extension(AuthenticatedUser(user)): Extension<AuthenticatedUser>,
Json(by_hand): Json<ByHand>,
) -> Response {
let Some(proposal) = Id::from_hex(&by_hand.proposal) else {
return error_response(StatusCode::BAD_REQUEST, "not a proposal's hash", None);
};
let cast = match state.holding.vote_by_hand(proposal, by_hand.yes) {
Ok(cast) => cast,
Err(why) => return error_response(StatusCode::UNPROCESSABLE_ENTITY, why, None),
};
let id = Id::of(&cast);
match crate::federation::held::write(&state, Some(user), cast).await {
Ok(()) => Json(json!({"id": id.to_string()})).into_response(),
Err(error) => store_status(error, "Failed to put a vote").into_response(),
}
}
/// The events an operator names.
#[derive(Deserialize)]
struct Named {
ids: Vec<String>,
}
impl Named {
fn ids(&self) -> Result<Vec<Id>, ApiError> {
read_ids(&self.ids)
}
}
/// `ids`, each an event's ID in hex.
fn read_ids(ids: &[String]) -> Result<Vec<Id>, ApiError> {
ids.iter()
.map(|id| {
Id::from_hex(id).ok_or_else(|| {
ApiError(
StatusCode::BAD_REQUEST,
Some(format!("{id:?} isn't an event's ID")),
)
})
})
.collect()
}
/// A fork to make: the heads it forks at, and its version.
#[derive(Deserialize)]
struct Forking {
heads: Vec<String>,
version: JsonValue,
}
/// `POST /admin/events/fork`: the root of the fork at `heads` by `version`, as this node's
/// store builds it, with the events the root keeps: the file its founders start its swarm
/// from (`--store-root`), the root on its first line, each event it keeps on a line of
/// its own.
async fn make_fork(State(state): State<AppState>, Json(forking): Json<Forking>) -> Response {
let heads = match read_ids(&forking.heads) {
Ok(heads) => heads,
Err(error) => return error.into_response(),
};
let version = match crate::federation::client::json(&forking.version) {
Ok(version) => version,
Err(why) => return error_response(StatusCode::BAD_REQUEST, why, None),
};
match state
.holding
.with(|store| fork::make(store, &heads, &version))
{
None => no_store(),
Some(Err(why)) => error_response(StatusCode::UNPROCESSABLE_ENTITY, why, None),
Some(Ok(file)) => ([(CONTENT_TYPE, "application/octet-stream")], file).into_response(),
}
}
/// `POST /events/fork`: what this node finds of the fork whose root is the body's first
/// line, as the file its founders start from holds it: whether it builds that root at
/// its heads, and why not; what it holds that those heads lack; and the parties whose keys
/// the fork's version gives otherwise than they had there, each with its keys there and in
/// the fork.
async fn check_fork(State(state): State<AppState>, body: Bytes) -> Response {
let (root, _) = fork::read_root_file(&body);
match state.holding.with(|store| fork::check(store, &root)) {
None => no_store(),
Some(Err(why)) => error_response(StatusCode::UNPROCESSABLE_ENTITY, why, None),
Some(Ok(check)) => {
let keys: serde_json::Map<String, JsonValue> = check
.keys
.into_iter()
.map(|(party, there, forked)| (party, json!({"there": there, "fork": forked})))
.collect();
Json(json!({
"fork": Id::of(&root).to_string(),
"builds": check.builds,
"why": check.why,
"lacking": ids(check.lacking),
"keys": keys,
}))
.into_response()
}
}
}
/// `POST /admin/events/drop`: drops events the store took after its checkpoint, with
/// everything built on them, as the operator has the node do: it refuses them from then
/// on, from whoever brings them, and keeps so across restarts (`--store-file`). What it
/// dropped, in the order taken.
async fn drop_taken(State(state): State<AppState>, Json(named): Json<Named>) -> Response {
let named = match named.ids() {
Ok(ids) => ids,
Err(error) => return error.into_response(),
};
match state.holding.drop_taken(&named) {
None => no_store(),
Some(Err(why)) => error_response(StatusCode::UNPROCESSABLE_ENTITY, why.0, None),
Some(Ok(dropped)) => Json(json!({"dropped": ids(dropped)})).into_response(),
}
}
/// `POST /admin/events/allow`: takes back what the node refused of its own, or dropped,
/// among the events named, and what was refused for building on them: taken again where
/// the store takes them, as it reads its document again.
async fn allow(State(state): State<AppState>, Json(named): Json<Named>) -> Response {
let named = match named.ids() {
Ok(ids) => ids,
Err(error) => return error.into_response(),
};
if state.holding.allow(&named) {
StatusCode::NO_CONTENT.into_response()
} else {
no_store()
}
}
|