1use std::collections::BTreeMap;
5
6use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value as Cbor};
7use nibkeep_base::{SpaceId, StatementId};
8use nibkeep_crypto::rand_core::CryptoRng;
9use nibkeep_crypto::{Envelope, Key};
10use nibkeep_model::{Operation, Statement};
11
12use crate::ChangeId;
13use crate::change::{read_by_statement, write_by_statement};
14use crate::keys::associated_data;
15
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
22pub struct Payload {
23 pub operations: Vec<Operation>,
25 pub sealed: BTreeMap<StatementId, Envelope>,
28 pub restated: BTreeMap<ChangeId, Restated>,
31}
32
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
37pub struct Restated {
38 pub operations: Vec<Operation>,
40 pub sealed: BTreeMap<StatementId, Envelope>,
42}
43
44impl Restated {
45 #[must_use]
47 pub fn is_empty(&self) -> bool {
48 self.operations.is_empty() && self.sealed.is_empty()
49 }
50}
51
52impl Payload {
53 pub fn all_operations(&self) -> impl Iterator<Item = &Operation> {
55 self.operations.iter().chain(
56 self.restated
57 .values()
58 .flat_map(|restated| restated.operations.iter()),
59 )
60 }
61
62 pub fn all_sealed(&self) -> impl Iterator<Item = (&StatementId, &Envelope)> {
64 self.sealed.iter().chain(
65 self.restated
66 .values()
67 .flat_map(|restated| restated.sealed.iter()),
68 )
69 }
70}
71
72impl From<Vec<Operation>> for Payload {
73 fn from(operations: Vec<Operation>) -> Self {
74 Self {
75 operations,
76 ..Self::default()
77 }
78 }
79}
80
81pub(crate) fn seal(
83 space: SpaceId,
84 statement: &Statement,
85 record_key: &Key,
86 rng: &mut impl CryptoRng,
87) -> Envelope {
88 Envelope::seal(
89 record_key,
90 &cbor::to_vec(statement),
91 &associated_data(space, &statement.id),
92 rng,
93 )
94}
95
96pub(crate) fn open_sealed(
99 space: SpaceId,
100 id: StatementId,
101 envelope: &Envelope,
102 record_key: &Key,
103) -> Option<Statement> {
104 let plaintext = envelope
105 .open(record_key, &associated_data(space, &id))
106 .ok()?;
107 let statement: Statement = cbor::from_slice(&plaintext).ok()?;
108 (statement.id == id).then_some(statement)
109}
110
111impl ToCbor for Payload {
112 fn to_cbor(&self) -> Cbor {
113 Cbor::Array(vec![
114 Cbor::Array(self.operations.iter().map(ToCbor::to_cbor).collect()),
115 write_by_statement(&self.sealed),
116 Cbor::Array(
117 self.restated
118 .iter()
119 .map(|(change, restated)| {
120 Cbor::Array(vec![
121 change.to_cbor(),
122 Cbor::Array(restated.operations.iter().map(ToCbor::to_cbor).collect()),
123 write_by_statement(&restated.sealed),
124 ])
125 })
126 .collect(),
127 ),
128 ])
129 }
130}
131
132impl FromCbor for Payload {
133 fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
134 const EXPECTED: &str = "a payload: [operations, sealed, restated], with sealed statements and restated changes in ascending order of their IDs";
135 let error = || cbor::Error::Expected(EXPECTED);
136 let Cbor::Array(items) = value else {
137 return Err(error());
138 };
139 let [operations, sealed, restated] = items.as_slice() else {
140 return Err(error());
141 };
142 let Cbor::Array(restated) = restated else {
143 return Err(error());
144 };
145 let mut restated_by_change: BTreeMap<ChangeId, Restated> = BTreeMap::new();
146 for entry in restated {
147 let Cbor::Array(entry) = entry else {
148 return Err(error());
149 };
150 let [change, operations, sealed] = entry.as_slice() else {
151 return Err(error());
152 };
153 let change = ChangeId::from_cbor(change)?;
154 if restated_by_change
156 .last_key_value()
157 .is_some_and(|(&last, _)| last >= change)
158 {
159 return Err(error());
160 }
161 restated_by_change.insert(
162 change,
163 Restated {
164 operations: Vec::from_cbor(operations)?,
165 sealed: read_by_statement(sealed, EXPECTED)?,
166 },
167 );
168 }
169 Ok(Self {
170 operations: Vec::from_cbor(operations)?,
171 sealed: read_by_statement(sealed, EXPECTED)?,
172 restated: restated_by_change,
173 })
174 }
175}