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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use crate::header::WireDelete;
use crate::header::WireHeaderStatus;
use crate::header::WireNewEntryHeader;
use crate::header::WireUpdateRelationship;
use crate::prelude::*;
use error::ElementGroupError;
use error::ElementGroupResult;
use holochain_keystore::KeystoreError;
use holochain_keystore::LairResult;
use holochain_keystore::MetaLairClient;
use holochain_serialized_bytes::prelude::*;
use holochain_zome_types::entry::EntryHashed;
use std::borrow::Cow;
use std::collections::BTreeSet;
#[allow(missing_docs)]
pub mod error;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, SerializedBytes, Default)]
pub struct WireElementOps {
pub header: Option<Judged<SignedHeader>>,
pub deletes: Vec<Judged<WireDelete>>,
pub updates: Vec<Judged<WireUpdateRelationship>>,
pub entry: Option<Entry>,
}
impl WireElementOps {
pub fn new() -> Self {
Self::default()
}
pub fn render(self) -> DhtOpResult<RenderedOps> {
let Self {
header,
deletes,
updates,
entry,
} = self;
let mut ops = Vec::with_capacity(1 + deletes.len() + updates.len());
if let Some(header) = header {
let status = header.validation_status();
let SignedHeader(header, signature) = header.data;
let entry_hash = header.entry_hash().cloned();
ops.push(RenderedOp::new(
header,
signature,
status,
DhtOpType::StoreElement,
)?);
if let Some(entry_hash) = entry_hash {
for op in deletes {
let status = op.validation_status();
let op = op.data;
let signature = op.signature;
let header = Header::Delete(op.delete);
ops.push(RenderedOp::new(
header,
signature,
status,
DhtOpType::RegisterDeletedBy,
)?);
}
for op in updates {
let status = op.validation_status();
let SignedHeader(header, signature) =
op.data.into_signed_header(entry_hash.clone());
ops.push(RenderedOp::new(
header,
signature,
status,
DhtOpType::RegisterUpdatedElement,
)?);
}
}
}
Ok(RenderedOps {
entry: entry.map(EntryHashed::from_content_sync),
ops,
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
pub struct WireElement {
signed_header: SignedHeader,
maybe_entry: Option<Entry>,
validation_status: ValidationStatus,
deletes: Vec<WireHeaderStatus<WireDelete>>,
updates: Vec<WireHeaderStatus<WireUpdateRelationship>>,
}
#[derive(Debug, Clone)]
pub struct ElementGroup<'a> {
headers: Vec<Cow<'a, SignedHeaderHashed>>,
rejected: Vec<Cow<'a, SignedHeaderHashed>>,
entry: Cow<'a, EntryHashed>,
}
#[derive(Debug, Clone, derive_more::Constructor)]
pub struct ElementStatus {
pub element: Element,
pub status: ValidationStatus,
}
impl<'a> ElementGroup<'a> {
pub fn headers_and_hashes(&self) -> impl Iterator<Item = (&HeaderHash, &Header)> {
self.headers
.iter()
.map(|shh| shh.header_address())
.zip(self.headers.iter().map(|shh| shh.header()))
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.headers.len()
}
pub fn visibility(&self) -> ElementGroupResult<&EntryVisibility> {
self.headers
.first()
.ok_or(ElementGroupError::Empty)?
.header()
.entry_data()
.map(|(_, et)| et.visibility())
.ok_or(ElementGroupError::MissingEntryData)
}
pub fn entry_hash(&self) -> &EntryHash {
self.entry.as_hash()
}
pub fn entry_hashed(&self) -> EntryHashed {
self.entry.clone().into_owned()
}
pub fn owned_signed_headers(&self) -> impl Iterator<Item = SignedHeaderHashed> + 'a {
self.headers
.clone()
.into_iter()
.chain(self.rejected.clone().into_iter())
.map(|shh| shh.into_owned())
}
pub fn valid_hashes(&self) -> impl Iterator<Item = &HeaderHash> {
self.headers.iter().map(|shh| shh.header_address())
}
pub fn rejected_hashes(&self) -> impl Iterator<Item = &HeaderHash> {
self.rejected.iter().map(|shh| shh.header_address())
}
pub fn from_wire_elements<I: IntoIterator<Item = WireHeaderStatus<WireNewEntryHeader>>>(
headers_iter: I,
entry_type: EntryType,
entry: Entry,
) -> ElementGroupResult<ElementGroup<'a>> {
let iter = headers_iter.into_iter();
let mut valid = Vec::with_capacity(iter.size_hint().0);
let mut rejected = Vec::with_capacity(iter.size_hint().0);
let entry = entry.into_hashed();
let entry_hash = entry.as_hash().clone();
let entry = Cow::Owned(entry);
for wire in iter {
match wire.validation_status {
ValidationStatus::Valid => valid.push(Cow::Owned(
wire.header
.into_header(entry_type.clone(), entry_hash.clone()),
)),
ValidationStatus::Rejected => rejected.push(Cow::Owned(
wire.header
.into_header(entry_type.clone(), entry_hash.clone()),
)),
ValidationStatus::Abandoned => todo!(),
}
}
Ok(Self {
headers: valid,
rejected,
entry,
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
pub enum GetElementResponse {
GetEntryFull(Option<Box<RawGetEntryResponse>>),
GetEntryPartial,
GetEntryCollapsed,
GetHeader(Option<Box<WireElement>>),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
pub struct RawGetEntryResponse {
pub live_headers: BTreeSet<WireHeaderStatus<WireNewEntryHeader>>,
pub deletes: Vec<WireHeaderStatus<WireDelete>>,
pub updates: Vec<WireHeaderStatus<WireUpdateRelationship>>,
pub entry: Entry,
pub entry_type: EntryType,
}
impl RawGetEntryResponse {
pub fn from_elements<E>(
elements: E,
deletes: Vec<WireHeaderStatus<WireDelete>>,
updates: Vec<WireHeaderStatus<WireUpdateRelationship>>,
) -> Option<Self>
where
E: IntoIterator<Item = ElementStatus>,
{
let mut elements = elements.into_iter();
elements.next().map(|ElementStatus { element, status }| {
let mut live_headers = BTreeSet::new();
let (new_entry_header, entry_type, entry) = Self::from_element(element);
live_headers.insert(WireHeaderStatus::new(new_entry_header, status));
let r = Self {
live_headers,
deletes,
updates,
entry,
entry_type,
};
elements.fold(r, |mut response, ElementStatus { element, status }| {
let (new_entry_header, entry_type, entry) = Self::from_element(element);
debug_assert_eq!(response.entry, entry);
debug_assert_eq!(response.entry_type, entry_type);
response
.live_headers
.insert(WireHeaderStatus::new(new_entry_header, status));
response
})
})
}
fn from_element(element: Element) -> (WireNewEntryHeader, EntryType, Entry) {
let (shh, entry) = element.into_inner();
let entry = entry
.into_option()
.expect("Get entry responses cannot be created without entries");
let (header, signature) = shh.into_inner();
let (new_entry_header, entry_type) = match header.into_content() {
Header::Create(ec) => {
let et = ec.entry_type.clone();
(WireNewEntryHeader::Create((ec, signature).into()), et)
}
Header::Update(eu) => {
let et = eu.entry_type.clone();
(WireNewEntryHeader::Update((eu, signature).into()), et)
}
h => panic!(
"Get entry responses cannot be created from headers
other then Create or Update.
Tried to with: {:?}",
h
),
};
(new_entry_header, entry_type, entry)
}
}
#[async_trait::async_trait]
pub trait ElementExt {
async fn validate(&self) -> Result<(), KeystoreError>;
}
#[async_trait::async_trait]
impl ElementExt for Element {
async fn validate(&self) -> Result<(), KeystoreError> {
self.signed_header().validate().await?;
Ok(())
}
}
#[async_trait::async_trait]
pub trait SignedHeaderHashedExt {
fn from_content_sync(signed_header: SignedHeader) -> SignedHeaderHashed;
#[allow(clippy::new_ret_no_self)]
async fn sign(
keystore: &MetaLairClient,
header: HeaderHashed,
) -> LairResult<SignedHeaderHashed>;
async fn validate(&self) -> Result<(), KeystoreError>;
}
#[allow(missing_docs)]
#[async_trait::async_trait]
impl SignedHeaderHashedExt for SignedHeaderHashed {
fn from_content_sync(signed_header: SignedHeader) -> Self
where
Self: Sized,
{
let (header, signature) = signed_header.into();
Self::with_presigned(header.into_hashed(), signature)
}
async fn sign(keystore: &MetaLairClient, header: HeaderHashed) -> LairResult<Self> {
let signature = header.author().sign(keystore, &*header).await?;
Ok(Self::with_presigned(header, signature))
}
async fn validate(&self) -> Result<(), KeystoreError> {
if !self
.header()
.author()
.verify_signature(self.signature(), self.header())
.await
{
return Err(KeystoreError::InvalidSignature(
self.signature().clone(),
format!("header {:?}", self.header_address()),
));
}
Ok(())
}
}
impl WireElement {
pub fn into_parts(self) -> (ElementStatus, Vec<ElementStatus>, Vec<ElementStatus>) {
let entry_hash = self.signed_header.header().entry_hash().cloned();
let header = Element::new(
SignedHeaderHashed::from_content_sync(self.signed_header),
self.maybe_entry,
);
let deletes = self
.deletes
.into_iter()
.map(WireHeaderStatus::<WireDelete>::into_element_status)
.collect();
let updates = self
.updates
.into_iter()
.map(|u| {
let entry_hash = entry_hash
.clone()
.expect("Updates cannot be on headers that do not have entries");
u.into_element_status(entry_hash)
})
.collect();
(
ElementStatus::new(header, self.validation_status),
deletes,
updates,
)
}
pub fn from_element(
e: ElementStatus,
deletes: Vec<WireHeaderStatus<WireDelete>>,
updates: Vec<WireHeaderStatus<WireUpdateRelationship>>,
) -> Self {
let ElementStatus { element, status } = e;
let (signed_header, maybe_entry) = element.into_inner();
Self {
signed_header: signed_header.into(),
maybe_entry: maybe_entry.into_option(),
validation_status: status,
deletes,
updates,
}
}
pub fn entry_hash(&self) -> Option<&EntryHash> {
self.signed_header
.header()
.entry_data()
.map(|(hash, _)| hash)
}
}
#[cfg(test)]
mod tests {
use super::SignedHeader;
use super::SignedHeaderHashed;
use crate::prelude::*;
use ::fixt::prelude::*;
use holo_hash::HasHash;
use holo_hash::HoloHashed;
#[tokio::test(flavor = "multi_thread")]
async fn test_signed_header_roundtrip() {
let signature = SignatureFixturator::new(Unpredictable).next().unwrap();
let header = HeaderFixturator::new(Unpredictable).next().unwrap();
let signed_header = SignedHeader(header, signature);
let hashed: HoloHashed<SignedHeader> = HoloHashed::from_content_sync(signed_header);
let HoloHashed {
content: SignedHeader(header, signature),
hash,
} = hashed.clone();
let shh = SignedHeaderHashed {
hashed: HeaderHashed::with_pre_hashed(header, hash),
signature,
};
assert_eq!(shh.header_address(), hashed.as_hash());
let round = HoloHashed {
content: SignedHeader(shh.header().clone(), shh.signature().clone()),
hash: shh.header_address().clone(),
};
assert_eq!(hashed, round);
}
}