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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
mod blob;
mod cmd;
mod data;
mod data_exchange;
mod duty;
mod errors;
mod map;
mod query;
mod register;
mod sequence;
mod transfer;
pub use self::{
blob::{BlobRead, BlobWrite},
cmd::Cmd,
data::{DataCmd, DataQuery},
data_exchange::{
BlobDataExchange, ChunkMetadata, DataExchange, HolderMetadata, MapDataExchange,
SequenceDataExchange,
},
duty::{AdultDuties, Duty, ElderDuties, NodeDuties},
errors::{Error, Result},
map::{MapRead, MapWrite},
query::Query,
register::{RegisterRead, RegisterWrite},
sequence::{SequenceRead, SequenceWrite},
transfer::{TransferCmd, TransferQuery},
};
use crate::{MessageId, MessageType, WireMsg};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use sn_data_types::{
register::{Entry, EntryHash, Permissions, Policy, Register},
ActorHistory, Blob, Map, MapEntries, MapPermissionSet, MapValue, MapValues, PublicKey,
Sequence, SequenceEntries, SequenceEntry, SequencePermissions, SequencePrivatePolicy,
SequencePublicPolicy, Signature, Token, TransferAgreementProof, TransferValidated,
};
use std::{
collections::{BTreeMap, BTreeSet},
convert::TryFrom,
};
use threshold_crypto::PublicKey as BlsPublicKey;
use xor_name::XorName;
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct ClientSigned {
pub public_key: PublicKey,
pub signature: Signature,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum ClientMsg {
Process(ProcessMsg),
ProcessingError(ProcessingError),
SupportingInfo(SupportingInfo),
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct SupportingInfo {
pub info: SupportingInfoFor,
pub source_message: ProcessMsg,
pub id: MessageId,
pub correlation_id: MessageId,
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum SupportingInfoFor {}
impl SupportingInfo {
pub fn new(
info: SupportingInfoFor,
source_message: ProcessMsg,
correlation_id: MessageId,
id: MessageId,
) -> Self {
Self {
info,
source_message,
id,
correlation_id,
}
}
pub fn id(&self) -> MessageId {
self.id
}
pub fn source_message(&self) -> &ProcessMsg {
&self.source_message
}
pub fn info(&self) -> &SupportingInfoFor {
&self.info
}
pub fn correlation_id(&self) -> MessageId {
self.correlation_id
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct ProcessingError {
reason: Option<Error>,
source_message: Option<ProcessMsg>,
id: MessageId,
}
impl ProcessingError {
pub fn new(reason: Option<Error>, source_message: Option<ProcessMsg>, id: MessageId) -> Self {
Self {
reason,
source_message,
id,
}
}
pub fn id(&self) -> MessageId {
self.id
}
pub fn source_message(&self) -> &Option<ProcessMsg> {
&self.source_message
}
pub fn reason(&self) -> &Option<Error> {
&self.reason
}
}
impl ClientMsg {
pub fn from(bytes: Bytes) -> crate::Result<Self> {
let deserialized = WireMsg::deserialize(bytes)?;
if let MessageType::Client { msg, .. } = deserialized {
Ok(msg)
} else {
Err(crate::Error::FailedToParse(
"bytes as a client message".to_string(),
))
}
}
pub fn serialize(&self, dest: XorName, dest_section_pk: BlsPublicKey) -> crate::Result<Bytes> {
WireMsg::serialize_client_msg(self, dest, dest_section_pk)
}
pub fn id(&self) -> MessageId {
match self {
Self::Process(ProcessMsg::Cmd { id, .. })
| Self::Process(ProcessMsg::Query { id, .. })
| Self::Process(ProcessMsg::Event { id, .. })
| Self::Process(ProcessMsg::QueryResponse { id, .. })
| Self::Process(ProcessMsg::CmdError { id, .. })
| Self::ProcessingError(ProcessingError { id, .. }) => *id,
Self::SupportingInfo(SupportingInfo { id, .. }) => *id,
}
}
pub fn get_process(&self) -> Option<&ProcessMsg> {
match self {
Self::Process(msg) => Some(msg),
Self::ProcessingError(_) => None,
Self::SupportingInfo(msg) => Some(&msg.source_message()),
}
}
pub fn get_processing_error(&self) -> Option<&ProcessingError> {
match self {
Self::Process(_) => None,
Self::SupportingInfo(_) => None,
Self::ProcessingError(error) => Some(error),
}
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum ProcessMsg {
Cmd {
id: MessageId,
cmd: Cmd,
client_signed: ClientSigned,
},
Query {
id: MessageId,
query: Query,
client_signed: ClientSigned,
},
Event {
id: MessageId,
event: Event,
correlation_id: MessageId,
},
QueryResponse {
id: MessageId,
response: QueryResponse,
correlation_id: MessageId,
},
CmdError {
id: MessageId,
error: CmdError,
correlation_id: MessageId,
},
}
impl ProcessMsg {
pub fn create_processing_error(&self, reason: Option<Error>) -> ProcessingError {
ProcessingError {
source_message: Some(self.clone()),
id: MessageId::new(),
reason,
}
}
pub fn id(&self) -> MessageId {
match self {
Self::Cmd { id, .. }
| Self::Query { id, .. }
| Self::Event { id, .. }
| Self::QueryResponse { id, .. }
| Self::CmdError { id, .. } => *id,
}
}
}
#[derive(Debug, Hash, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum CmdError {
Data(Error),
Transfer(TransferError),
}
#[derive(Debug, Hash, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum TransferError {
TransferValidation(Error),
TransferRegistration(Error),
}
#[allow(clippy::large_enum_variant, clippy::type_complexity)]
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum Event {
TransferValidated {
event: TransferValidated,
},
TransferAgreementReached {
proof: TransferAgreementProof,
},
}
#[allow(clippy::large_enum_variant, clippy::type_complexity)]
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize, Debug)]
pub enum QueryResponse {
GetBlob(Result<Blob>),
GetMap(Result<Map>),
GetMapShell(Result<Map>),
GetMapVersion(Result<u64>),
ListMapEntries(Result<MapEntries>),
ListMapKeys(Result<BTreeSet<Vec<u8>>>),
ListMapValues(Result<MapValues>),
ListMapUserPermissions(Result<MapPermissionSet>),
ListMapPermissions(Result<BTreeMap<PublicKey, MapPermissionSet>>),
GetMapValue(Result<MapValue>),
GetSequence(Result<Sequence>),
GetSequenceRange(Result<SequenceEntries>),
GetSequenceLastEntry(Result<(u64, SequenceEntry)>),
GetSequencePublicPolicy(Result<SequencePublicPolicy>),
GetSequencePrivatePolicy(Result<SequencePrivatePolicy>),
GetSequenceUserPermissions(Result<SequencePermissions>),
GetRegister(Result<Register>),
GetRegisterOwner(Result<PublicKey>),
ReadRegister(Result<BTreeSet<(EntryHash, Entry)>>),
GetRegisterPolicy(Result<Policy>),
GetRegisterUserPermissions(Result<Permissions>),
GetBalance(Result<Token>),
GetHistory(Result<ActorHistory>),
GetStoreCost(Result<(u64, Token, PublicKey)>),
}
impl QueryResponse {
pub fn is_success(&self) -> bool {
use QueryResponse::*;
match self {
GetBlob(result) => result.is_ok(),
GetMap(result) => result.is_ok(),
GetMapShell(result) => result.is_ok(),
GetMapVersion(result) => result.is_ok(),
ListMapEntries(result) => result.is_ok(),
ListMapKeys(result) => result.is_ok(),
ListMapValues(result) => result.is_ok(),
ListMapUserPermissions(result) => result.is_ok(),
ListMapPermissions(result) => result.is_ok(),
GetMapValue(result) => result.is_ok(),
GetSequence(result) => result.is_ok(),
GetSequenceRange(result) => result.is_ok(),
GetSequenceLastEntry(result) => result.is_ok(),
GetSequencePublicPolicy(result) => result.is_ok(),
GetSequencePrivatePolicy(result) => result.is_ok(),
GetSequenceUserPermissions(result) => result.is_ok(),
GetRegister(result) => result.is_ok(),
GetRegisterOwner(result) => result.is_ok(),
ReadRegister(result) => result.is_ok(),
GetRegisterPolicy(result) => result.is_ok(),
GetRegisterUserPermissions(result) => result.is_ok(),
GetBalance(result) => result.is_ok(),
GetHistory(result) => result.is_ok(),
GetStoreCost(result) => result.is_ok(),
}
}
}
#[derive(Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum TryFromError {
WrongType,
Response(Error),
}
macro_rules! try_from {
($ok_type:ty, $($variant:ident),*) => {
impl TryFrom<QueryResponse> for $ok_type {
type Error = TryFromError;
fn try_from(response: QueryResponse) -> std::result::Result<Self, Self::Error> {
match response {
$(
QueryResponse::$variant(Ok(data)) => Ok(data),
QueryResponse::$variant(Err(error)) => Err(TryFromError::Response(error)),
)*
_ => Err(TryFromError::WrongType),
}
}
}
};
}
try_from!(Blob, GetBlob);
try_from!(Map, GetMap, GetMapShell);
try_from!(u64, GetMapVersion);
try_from!(MapEntries, ListMapEntries);
try_from!(BTreeSet<Vec<u8>>, ListMapKeys);
try_from!(MapValues, ListMapValues);
try_from!(MapPermissionSet, ListMapUserPermissions);
try_from!(BTreeMap<PublicKey, MapPermissionSet>, ListMapPermissions);
try_from!(MapValue, GetMapValue);
try_from!(Sequence, GetSequence);
try_from!(SequenceEntries, GetSequenceRange);
try_from!((u64, SequenceEntry), GetSequenceLastEntry);
try_from!(SequencePublicPolicy, GetSequencePublicPolicy);
try_from!(SequencePrivatePolicy, GetSequencePrivatePolicy);
try_from!(SequencePermissions, GetSequenceUserPermissions);
try_from!(Register, GetRegister);
try_from!(PublicKey, GetRegisterOwner);
try_from!(BTreeSet<(EntryHash, Entry)>, ReadRegister);
try_from!(Policy, GetRegisterPolicy);
try_from!(Permissions, GetRegisterUserPermissions);
try_from!(Token, GetBalance);
try_from!(ActorHistory, GetHistory);
#[cfg(test)]
mod tests {
use super::*;
use anyhow::{anyhow, Result};
use sn_data_types::{BlobAddress, DataAddress, Keypair, PublicBlob, UnseqMap};
use std::convert::{TryFrom, TryInto};
fn gen_keypairs() -> Vec<Keypair> {
let mut rng = rand::thread_rng();
let bls_secret_key = threshold_crypto::SecretKeySet::random(1, &mut rng);
vec![
Keypair::new_ed25519(&mut rng),
Keypair::new_bls_share(
0,
bls_secret_key.secret_key_share(0),
bls_secret_key.public_keys(),
),
]
}
pub fn gen_keys() -> Vec<PublicKey> {
gen_keypairs().iter().map(PublicKey::from).collect()
}
#[test]
fn debug_format_functional() -> Result<()> {
if let Some(key) = gen_keys().first() {
let errored_response = QueryResponse::GetSequence(Err(Error::AccessDenied(*key)));
assert!(format!("{:?}", errored_response)
.contains("GetSequence(Err(AccessDenied(PublicKey::"));
Ok(())
} else {
Err(anyhow!("Could not generate public key"))
}
}
#[test]
fn generate_processing_error() -> Result<()> {
if let Some(keypair) = gen_keypairs().first() {
let public_key = keypair.public_key();
let signature = keypair.sign(b"the query");
let msg = ProcessMsg::Query {
id: MessageId::new(),
query: Query::Transfer(TransferQuery::GetBalance(public_key)),
client_signed: ClientSigned {
public_key,
signature,
},
};
let random_addr = DataAddress::Blob(BlobAddress::Public(XorName::random()));
let lazy_error =
msg.create_processing_error(Some(Error::DataNotFound(random_addr.clone())));
assert!(format!("{:?}", lazy_error).contains("TransferQuery::GetBalance"));
assert!(format!("{:?}", lazy_error).contains("ProcessingError"));
assert!(
format!("{:?}", lazy_error).contains(&format!("DataNotFound({:?})", random_addr))
);
Ok(())
} else {
Err(anyhow!("Could not generate public key"))
}
}
#[test]
fn debug_format_processing_error() -> Result<()> {
if let Some(keypair) = gen_keypairs().first() {
let public_key = keypair.public_key();
let signature = keypair.sign(b"the query");
let random_addr = DataAddress::Blob(BlobAddress::Public(XorName::random()));
let errored_response = ProcessingError {
reason: Some(Error::DataNotFound(random_addr.clone())),
source_message: Some(ProcessMsg::Query {
id: MessageId::new(),
query: Query::Transfer(TransferQuery::GetBalance(public_key)),
client_signed: ClientSigned {
public_key,
signature,
},
}),
id: MessageId::new(),
};
assert!(format!("{:?}", errored_response).contains("TransferQuery::GetBalance"));
assert!(format!("{:?}", errored_response).contains("ProcessingError"));
assert!(format!("{:?}", errored_response)
.contains(&format!("DataNotFound({:?})", random_addr)));
Ok(())
} else {
Err(anyhow!("Could not generate public key"))
}
}
#[test]
fn try_from() -> Result<()> {
use QueryResponse::*;
let key = match gen_keys().first() {
Some(key) => *key,
None => return Err(anyhow!("Could not generate public key")),
};
let i_data = Blob::Public(PublicBlob::new(vec![1, 3, 1, 4]));
let e = Error::AccessDenied(key);
assert_eq!(
i_data,
GetBlob(Ok(i_data.clone()))
.try_into()
.map_err(|_| anyhow!("Mismatched types".to_string()))?
);
assert_eq!(
Err(TryFromError::Response(e.clone())),
Blob::try_from(GetBlob(Err(e.clone())))
);
let mut data = BTreeMap::new();
let _ = data.insert(vec![1], vec![10]);
let owners = PublicKey::Bls(threshold_crypto::SecretKey::random().public_key());
let m_data = Map::Unseq(UnseqMap::new_with_data(
*i_data.name(),
1,
data,
BTreeMap::new(),
owners,
));
assert_eq!(
m_data,
GetMap(Ok(m_data.clone()))
.try_into()
.map_err(|_| anyhow!("Mismatched types".to_string()))?
);
assert_eq!(
Err(TryFromError::Response(e.clone())),
Map::try_from(GetMap(Err(e)))
);
Ok(())
}
#[test]
fn serialization() -> Result<()> {
let keypair = &gen_keypairs()[0];
let public_key = keypair.public_key();
let signature = keypair.sign(b"the query");
let id = MessageId::new();
let message = ClientMsg::Process(ProcessMsg::Query {
id,
query: Query::Transfer(TransferQuery::GetBalance(public_key)),
client_signed: ClientSigned {
public_key,
signature,
},
});
let dest = XorName::random();
let dest_section_pk = threshold_crypto::SecretKey::random().public_key();
let serialized = message.serialize(dest, dest_section_pk)?;
let deserialized = ClientMsg::from(serialized)?;
assert_eq!(deserialized, message);
Ok(())
}
}