1use std::collections::{BTreeMap, BTreeSet};
5
6pub use nibkeep_base::ChangeId;
7use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value as Cbor};
8use nibkeep_base::small::SmallSet;
9use nibkeep_base::{Hash, SpaceId, StatementId};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_crypto::{Envelope, Key, Signature, SigningKey, VerifyingKey, key_hash};
12use nibkeep_time::Timestamp;
13
14use crate::keys::{associated_data, change_keys_key};
15use crate::{LogError, Payload, SpaceKeys};
16
17const SUITE: u8 = 1;
19
20const SIGNATURE_CONTEXT: &str = "nibkeep change";
22
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub enum Kind {
27 #[default]
29 Ordinary,
30 Governing,
33}
34
35impl ToCbor for Kind {
36 fn to_cbor(&self) -> Cbor {
37 match self {
38 Self::Ordinary => 0u8.to_cbor(),
39 Self::Governing => 1u8.to_cbor(),
40 }
41 }
42}
43
44impl FromCbor for Kind {
45 fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
46 match u8::from_cbor(value) {
47 Ok(0) => Ok(Self::Ordinary),
48 Ok(1) => Ok(Self::Governing),
49 _ => Err(cbor::Error::Expected("a kind of change: 0 or 1")),
50 }
51 }
52}
53
54#[derive(Clone, Debug, Default, PartialEq, Eq)]
61pub struct Purges {
62 pub changes: BTreeSet<ChangeId>,
64 pub statements: BTreeSet<StatementId>,
66 pub blobs: BTreeSet<Hash>,
68}
69
70impl Purges {
71 #[must_use]
73 pub fn is_empty(&self) -> bool {
74 self.changes.is_empty() && self.statements.is_empty() && self.blobs.is_empty()
75 }
76}
77
78impl ToCbor for Purges {
79 fn to_cbor(&self) -> Cbor {
80 Cbor::Array(vec![
83 Cbor::Array(self.changes.iter().map(ToCbor::to_cbor).collect()),
84 Cbor::Array(self.statements.iter().map(ToCbor::to_cbor).collect()),
85 Cbor::Array(self.blobs.iter().map(ToCbor::to_cbor).collect()),
86 ])
87 }
88}
89
90impl FromCbor for Purges {
91 fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
92 const EXPECTED: &str =
93 "purges: [changes, statements, blobs], each in ascending order without duplicates";
94 let Cbor::Array(items) = value else {
95 return Err(cbor::Error::Expected(EXPECTED));
96 };
97 let [changes, statements, blobs] = items.as_slice() else {
98 return Err(cbor::Error::Expected(EXPECTED));
99 };
100 Ok(Self {
101 changes: ascending(changes, EXPECTED)?,
102 statements: ascending(statements, EXPECTED)?,
103 blobs: ascending(blobs, EXPECTED)?,
104 })
105 }
106}
107
108pub type Restores = Purges;
113
114pub(crate) fn ascending<T: FromCbor + Ord>(
116 value: &Cbor,
117 expected: &'static str,
118) -> Result<BTreeSet<T>, cbor::Error> {
119 let items: Vec<T> = Vec::from_cbor(value)?;
120 if items.windows(2).any(|pair| pair[0] >= pair[1]) {
121 return Err(cbor::Error::Expected(expected));
122 }
123 Ok(items.into_iter().collect())
124}
125
126#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct SealedPayload(Envelope);
134
135impl SealedPayload {
136 #[must_use]
138 pub fn hash(&self) -> Hash {
139 Hash::of(&cbor::to_vec(self))
140 }
141
142 #[must_use]
144 pub fn byte_len(&self) -> usize {
145 self.0.byte_len()
146 }
147}
148
149impl ToCbor for SealedPayload {
150 fn to_cbor(&self) -> Cbor {
151 self.0.to_cbor()
152 }
153}
154
155impl FromCbor for SealedPayload {
156 fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
157 Envelope::from_cbor(value).map(Self)
158 }
159}
160
161#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct WrappedChangeKey(Envelope);
168
169impl WrappedChangeKey {
170 fn wrap(
172 space: SpaceId,
173 change: ChangeId,
174 change_key: &Key,
175 space_key: &Key,
176 rng: &mut impl CryptoRng,
177 ) -> Self {
178 Self(Envelope::seal_key(
179 &change_keys_key(space_key),
180 change_key,
181 &associated_data(space, &change),
182 rng,
183 ))
184 }
185
186 pub(crate) fn unwrap(&self, change: &Change, keys: &SpaceKeys) -> Option<Key> {
189 let space_key = keys.get(change.epoch())?;
190 let key = self
191 .0
192 .open_key(
193 &change_keys_key(space_key),
194 &associated_data(change.space(), &change.id()),
195 )
196 .ok()?;
197 (key_hash(&key) == change.header.key_hash).then_some(key)
198 }
199}
200
201impl ToCbor for WrappedChangeKey {
202 fn to_cbor(&self) -> Cbor {
203 self.0.to_cbor()
204 }
205}
206
207impl FromCbor for WrappedChangeKey {
208 fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
209 Envelope::from_cbor(value).map(Self)
210 }
211}
212
213#[derive(Clone, Debug, PartialEq, Eq)]
217pub struct Parcel {
218 pub change: Change,
220 pub payload: Option<SealedPayload>,
222 pub keys: Vec<WrappedChangeKey>,
224}
225
226impl Parcel {
227 #[must_use]
229 pub const fn id(&self) -> ChangeId {
230 self.change.id()
231 }
232}
233
234#[derive(Clone, Debug)]
236pub struct Draft {
237 pub parents: BTreeSet<ChangeId>,
239 pub timestamp: Timestamp,
241 pub kind: Kind,
243 pub purges: Purges,
245 pub restores: Restores,
247 pub record_keys: BTreeMap<StatementId, Hash>,
249 pub payload: Payload,
251}
252
253impl Draft {
254 #[must_use]
256 pub fn new(
257 parents: impl IntoIterator<Item = ChangeId>,
258 timestamp: Timestamp,
259 payload: Payload,
260 ) -> Self {
261 Self {
262 parents: parents.into_iter().collect(),
263 timestamp,
264 kind: Kind::Ordinary,
265 purges: Purges::default(),
266 restores: Restores::default(),
267 record_keys: BTreeMap::new(),
268 payload,
269 }
270 }
271}
272
273#[derive(Clone, Debug, PartialEq, Eq)]
280pub struct Change {
281 header: Header,
282 signature: Signature,
283 id: ChangeId,
284}
285
286#[derive(Clone, Debug, PartialEq, Eq)]
287struct Header {
288 space: SpaceId,
289 epoch: u64,
290 author: VerifyingKey,
291 parents: SmallSet<ChangeId>,
293 timestamp: Timestamp,
294 kind: Kind,
295 payload_hash: Hash,
296 key_hash: Hash,
297 sealed: BTreeMap<StatementId, Hash>,
299 purges: Purges,
300 restores: Restores,
302}
303
304impl Change {
305 #[must_use]
308 pub fn create(
309 space: SpaceId,
310 keys: &SpaceKeys,
311 author: &SigningKey,
312 draft: &Draft,
313 rng: &mut impl CryptoRng,
314 ) -> Parcel {
315 let (epoch, space_key) = keys.newest();
316 let change_key = Key::generate(rng);
317 let key_hash = key_hash(&change_key);
318 let payload = SealedPayload(Envelope::seal(
319 &change_key,
320 &cbor::to_vec(&draft.payload),
321 &associated_data(space, &key_hash),
322 rng,
323 ));
324 let header = Header {
325 space,
326 epoch,
327 author: author.verifying_key(),
328 parents: draft.parents.iter().copied().collect(),
329 timestamp: draft.timestamp,
330 kind: draft.kind,
331 payload_hash: payload.hash(),
332 key_hash,
333 sealed: draft.record_keys.clone(),
334 purges: draft.purges.clone(),
335 restores: draft.restores.clone(),
336 };
337 let signature = author.sign(SIGNATURE_CONTEXT, &cbor::to_vec(&header));
338 let change = Self::from_parts(header, signature);
339 let key = WrappedChangeKey::wrap(space, change.id(), &change_key, space_key, rng);
340 Parcel {
341 change,
342 payload: Some(payload),
343 keys: vec![key],
344 }
345 }
346
347 fn from_parts(header: Header, signature: Signature) -> Self {
349 let mut change = Self {
350 header,
351 signature,
352 id: ChangeId::from_hash(Hash::of(&[])),
353 };
354 change.id = ChangeId::from_hash(Hash::of(&cbor::to_vec(&change)));
355 change
356 }
357
358 #[must_use]
360 pub const fn id(&self) -> ChangeId {
361 self.id
362 }
363
364 #[must_use]
366 pub const fn space(&self) -> SpaceId {
367 self.header.space
368 }
369
370 #[must_use]
372 pub const fn epoch(&self) -> u64 {
373 self.header.epoch
374 }
375
376 #[must_use]
378 pub const fn author(&self) -> &VerifyingKey {
379 &self.header.author
380 }
381
382 #[must_use]
384 pub const fn parents(&self) -> &SmallSet<ChangeId> {
385 &self.header.parents
386 }
387
388 #[must_use]
390 pub const fn timestamp(&self) -> Timestamp {
391 self.header.timestamp
392 }
393
394 #[must_use]
396 pub const fn kind(&self) -> Kind {
397 self.header.kind
398 }
399
400 #[must_use]
402 pub const fn payload_hash(&self) -> &Hash {
403 &self.header.payload_hash
404 }
405
406 #[must_use]
409 pub const fn sealed(&self) -> &BTreeMap<StatementId, Hash> {
410 &self.header.sealed
411 }
412
413 #[must_use]
415 pub const fn purges(&self) -> &Purges {
416 &self.header.purges
417 }
418
419 #[must_use]
421 pub const fn restores(&self) -> &Restores {
422 &self.header.restores
423 }
424
425 #[must_use]
427 pub fn purges_or_restores(&self) -> bool {
428 !self.header.purges.is_empty() || !self.header.restores.is_empty()
429 }
430
431 pub fn verify(&self) -> Result<(), LogError> {
437 self.header
438 .author
439 .verify(
440 SIGNATURE_CONTEXT,
441 &cbor::to_vec(&self.header),
442 &self.signature,
443 )
444 .map_err(|_| LogError::InvalidSignature)
445 }
446
447 pub fn open(
456 &self,
457 payload: &SealedPayload,
458 key: &WrappedChangeKey,
459 keys: &SpaceKeys,
460 ) -> Result<Payload, LogError> {
461 if payload.hash() != self.header.payload_hash {
462 return Err(LogError::OtherPayload);
463 }
464 self.open_checked(payload, key, keys)
465 }
466
467 pub(crate) fn open_checked(
470 &self,
471 payload: &SealedPayload,
472 key: &WrappedChangeKey,
473 keys: &SpaceKeys,
474 ) -> Result<Payload, LogError> {
475 if keys.get(self.header.epoch).is_none() {
476 return Err(LogError::UnknownEpoch(self.header.epoch));
477 }
478 let change_key = key.unwrap(self, keys).ok_or(LogError::OtherKey)?;
479 let plaintext = payload
480 .0
481 .open(
482 &change_key,
483 &associated_data(self.header.space, &self.header.key_hash),
484 )
485 .map_err(|_| LogError::Decryption)?;
486 let opened: Payload = cbor::from_slice(&plaintext).map_err(LogError::Operations)?;
487 let mut sealed: Vec<StatementId> = opened.all_sealed().map(|(&id, _)| id).collect();
488 sealed.sort_unstable();
489 if !sealed.iter().eq(self.header.sealed.keys()) {
490 return Err(LogError::Operations(cbor::Error::Expected(
491 "the statements that the change's header says are sealed",
492 )));
493 }
494 Ok(opened)
495 }
496}
497
498fn parents_cbor(parents: &SmallSet<ChangeId>) -> Cbor {
500 let mut parents: Vec<Vec<u8>> = parents
501 .iter()
502 .map(|parent| parent.hash().to_multihash())
503 .collect();
504 parents.sort();
505 Cbor::Array(parents.into_iter().map(Cbor::Bytes).collect())
506}
507
508impl ToCbor for Header {
509 fn to_cbor(&self) -> Cbor {
510 let mut items = vec![
511 self.space.to_cbor(),
512 self.epoch.to_cbor(),
513 self.author.to_cbor(),
514 parents_cbor(&self.parents),
515 self.timestamp.to_cbor(),
516 self.kind.to_cbor(),
517 self.payload_hash.to_cbor(),
518 self.key_hash.to_cbor(),
519 write_by_statement(&self.sealed),
520 self.purges.to_cbor(),
521 ];
522 if !self.restores.is_empty() {
523 items.push(self.restores.to_cbor());
524 }
525 Cbor::Array(items)
526 }
527}
528
529impl FromCbor for Header {
530 fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
531 const EXPECTED: &str = "a change header: [space, epoch, author, parents, timestamp, kind, payload hash, key hash, sealed, purges], and restores if it restores anything";
532 let Cbor::Array(items) = value else {
533 return Err(cbor::Error::Expected(EXPECTED));
534 };
535 let (items, restores) = match items.as_slice() {
538 [header @ .., restores] if header.len() == 10 => {
539 let restores = Restores::from_cbor(restores)?;
540 if restores.is_empty() {
541 return Err(cbor::Error::Expected(EXPECTED));
542 }
543 (header, restores)
544 }
545 items => (items, Restores::default()),
546 };
547 let [
548 space,
549 epoch,
550 author,
551 parents,
552 timestamp,
553 kind,
554 payload_hash,
555 key_hash,
556 sealed,
557 purges,
558 ] = items
559 else {
560 return Err(cbor::Error::Expected(EXPECTED));
561 };
562 Ok(Self {
563 space: SpaceId::from_cbor(space)?,
564 epoch: u64::from_cbor(epoch)?,
565 author: VerifyingKey::from_cbor(author)?,
566 parents: read_parents(parents)?,
567 timestamp: Timestamp::from_cbor(timestamp)?,
568 kind: Kind::from_cbor(kind)?,
569 payload_hash: Hash::from_cbor(payload_hash)?,
570 key_hash: Hash::from_cbor(key_hash)?,
571 sealed: read_by_statement(
572 sealed,
573 "sealed statements: [id, record key hash] in ascending order of their IDs",
574 )?,
575 purges: Purges::from_cbor(purges)?,
576 restores,
577 })
578 }
579}
580
581pub(crate) fn read_by_statement<T: FromCbor>(
584 value: &Cbor,
585 expected: &'static str,
586) -> Result<BTreeMap<StatementId, T>, cbor::Error> {
587 let Cbor::Array(items) = value else {
588 return Err(cbor::Error::Expected(expected));
589 };
590 let mut read = BTreeMap::new();
591 for item in items {
592 let Cbor::Array(pair) = item else {
593 return Err(cbor::Error::Expected(expected));
594 };
595 let [statement, value] = pair.as_slice() else {
596 return Err(cbor::Error::Expected(expected));
597 };
598 let statement = StatementId::from_cbor(statement)?;
599 if read
600 .last_key_value()
601 .is_some_and(|(&last, _)| last >= statement)
602 {
603 return Err(cbor::Error::Expected(expected));
604 }
605 read.insert(statement, T::from_cbor(value)?);
606 }
607 Ok(read)
608}
609
610pub(crate) fn write_by_statement<T: ToCbor>(pairs: &BTreeMap<StatementId, T>) -> Cbor {
612 Cbor::Array(
613 pairs
614 .iter()
615 .map(|(statement, value)| Cbor::Array(vec![statement.to_cbor(), value.to_cbor()]))
616 .collect(),
617 )
618}
619
620fn read_parents(value: &Cbor) -> Result<SmallSet<ChangeId>, cbor::Error> {
622 const EXPECTED: &str = "parents: change IDs sorted by their bytes, without duplicates";
623 let Cbor::Array(items) = value else {
624 return Err(cbor::Error::Expected(EXPECTED));
625 };
626 let mut previous: Option<&[u8]> = None;
627 let mut parents = SmallSet::new();
628 for item in items {
629 let Cbor::Bytes(bytes) = item else {
630 return Err(cbor::Error::Expected(EXPECTED));
631 };
632 if previous.is_some_and(|previous| previous >= bytes.as_slice()) {
633 return Err(cbor::Error::Expected(EXPECTED));
634 }
635 previous = Some(bytes);
636 parents.insert(ChangeId::from_cbor(item)?);
637 }
638 Ok(parents)
639}
640
641impl ToCbor for Change {
642 fn to_cbor(&self) -> Cbor {
643 Cbor::Array(vec![
644 SUITE.to_cbor(),
645 self.header.to_cbor(),
646 self.signature.to_cbor(),
647 ])
648 }
649}
650
651impl FromCbor for Change {
652 fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
653 const EXPECTED: &str = "a change: [1, header, signature]";
654 let Cbor::Array(items) = value else {
655 return Err(cbor::Error::Expected(EXPECTED));
656 };
657 let [suite, header, signature] = items.as_slice() else {
658 return Err(cbor::Error::Expected(EXPECTED));
659 };
660 if u8::from_cbor(suite) != Ok(SUITE) {
661 return Err(cbor::Error::Expected(EXPECTED));
662 }
663 Ok(Self::from_parts(
664 Header::from_cbor(header)?,
665 Signature::from_cbor(signature)?,
666 ))
667 }
668}