This repository has been archived by the owner on Jun 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 80
/
mod.rs
429 lines (381 loc) · 13.8 KB
/
mod.rs
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
// Copyright 2020 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
mod hash;
mod plain_message;
mod src_authority;
mod variant;
pub use self::{hash::MessageHash, src_authority::SrcAuthority};
pub(crate) use self::{
plain_message::PlainMessage,
variant::{JoinRequest, ResourceProofResponse, Variant},
};
use crate::{
crypto::{self, Verifier},
error::{Error, Result},
node::Node,
section::{SectionChainError, SectionKeyShare},
};
use bls_signature_aggregator::{Proof, ProofShare};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use sn_messaging::{Aggregation, DstLocation};
use std::fmt::{self, Debug, Formatter};
use thiserror::Error;
use xor_name::XorName;
/// Message sent over the network.
#[derive(Clone, Eq, Serialize, Deserialize)]
pub(crate) struct Message {
/// Source authority.
/// Messages do not need to sign this field as it is all verifiable (i.e. if the sig validates
/// agains the public key and we know the pub key then we are good. If the proof is not recognised we
/// ask for a longer chain that can be recognised). Therefore we don't need to sign this field.
src: SrcAuthority,
/// Destination location.
dst: DstLocation,
/// The aggregation scheme to be used.
aggregation: Aggregation,
/// The body of the message.
variant: Variant,
/// PublicKey of the Section from which the Sender hails from.
section_pk: bls::PublicKey,
/// Serialised message, this is a signed and fully serialised message ready to send.
#[serde(skip)]
serialized: Bytes,
#[serde(skip)]
hash: MessageHash,
}
impl Message {
/// Deserialize the message. Only called on message receipt.
pub(crate) fn from_bytes(msg_bytes: Bytes) -> Result<Self> {
let mut msg: Message =
bincode::deserialize(&msg_bytes).map_err(|_| Error::InvalidMessage)?;
let signed_bytes = bincode::serialize(&SignableView {
dst: &msg.dst,
variant: &msg.variant,
})
.map_err(|_| Error::InvalidMessage)?;
match &msg.src {
SrcAuthority::Node {
public_key,
signature,
..
} => {
if public_key.verify(&signed_bytes, signature).is_err() {
error!("Failed signature: {:?}", msg);
return Err(Error::CreateError(CreateError::FailedSignature));
}
}
SrcAuthority::BlsShare { proof_share, .. } => {
if !proof_share.verify(&signed_bytes) {
error!("Failed signature: {:?}", msg);
return Err(Error::CreateError(CreateError::FailedSignature));
}
if proof_share.public_key_set.public_key() != msg.section_pk() {
error!(
"Proof share public key doesn't match proof chain last key: {:?}",
msg
);
return Err(Error::CreateError(CreateError::FailedSignature));
}
}
SrcAuthority::Section { proof, .. } => {
if !msg.section_pk.verify(&proof.signature, &signed_bytes) {
error!(
"Failed signature: {:?} (Section PK: {:?})",
msg, msg.section_pk
);
return Err(Error::CreateError(CreateError::FailedSignature));
}
}
}
msg.serialized = msg_bytes.clone();
msg.hash = MessageHash::from_bytes(&msg_bytes);
Ok(msg)
}
/// send across wire
pub(crate) fn to_bytes(&self) -> Bytes {
self.serialized.clone()
}
/// Creates a signed message where signature is assumed valid.
fn new_signed(
src: SrcAuthority,
dst: DstLocation,
variant: Variant,
section_pk: bls::PublicKey,
) -> Result<Message, Error> {
let mut msg = Message {
dst,
src,
aggregation: Aggregation::None,
section_pk,
variant,
serialized: Default::default(),
hash: Default::default(),
};
msg.serialized = bincode::serialize(&msg)
.map_err(|_| Error::InvalidMessage)?
.into();
msg.hash = MessageHash::from_bytes(&msg.serialized);
Ok(msg)
}
/// Creates a message signed using a BLS KeyShare for destination accumulation
pub(crate) fn for_dst_accumulation(
key_share: &SectionKeyShare,
src_name: XorName,
dst: DstLocation,
variant: Variant,
section_pk: bls::PublicKey,
) -> Result<Self, Error> {
let serialized = bincode::serialize(&SignableView {
dst: &dst,
variant: &variant,
})
.map_err(|_| Error::InvalidMessage)?;
let signature_share = key_share.secret_key_share.sign(&serialized);
let proof_share = ProofShare {
public_key_set: key_share.public_key_set.clone(),
index: key_share.index,
signature_share,
};
let src = SrcAuthority::BlsShare {
src_name,
proof_share,
};
Self::new_signed(src, dst, variant, section_pk)
}
/// Converts the message src authority from `BlsShare` to `Section` on successful accumulation.
/// Returns errors if src is not `BlsShare` or if the proof is invalid.
pub(crate) fn into_dst_accumulated(mut self, proof: Proof) -> Result<Self> {
let (proof_share, src_name) = if let SrcAuthority::BlsShare {
proof_share,
src_name,
} = &self.src
{
(proof_share.clone(), *src_name)
} else {
error!("not a message for dst accumulation");
return Err(Error::InvalidMessage);
};
if proof_share.public_key_set.public_key() != proof.public_key {
error!("proof public key doesn't match proof share public key");
return Err(Error::InvalidMessage);
}
if proof.public_key != self.section_pk {
error!("proof public key doesn't match the attached section PK");
return Err(Error::InvalidMessage);
}
let bytes = bincode::serialize(&self.signable_view()).map_err(|_| Error::InvalidMessage)?;
if !proof.verify(&bytes) {
return Err(Error::FailedSignature);
}
self.src = SrcAuthority::Section { proof, src_name };
Ok(self)
}
pub(crate) fn signable_view(&self) -> SignableView {
SignableView {
dst: &self.dst,
variant: &self.variant,
}
}
/// Creates a signed message from single node.
pub(crate) fn single_src(
node: &Node,
dst: DstLocation,
variant: Variant,
section_pk: bls::PublicKey,
) -> Result<Self> {
let serialized = bincode::serialize(&SignableView {
dst: &dst,
variant: &variant,
})
.map_err(|_| Error::InvalidMessage)?;
let signature = crypto::sign(&serialized, &node.keypair);
let src = SrcAuthority::Node {
public_key: node.keypair.public,
signature,
};
Self::new_signed(src, dst, variant, section_pk)
}
/// Creates a signed message from a section.
/// Note: `proof` isn't verified and is assumed valid.
pub(crate) fn section_src(
plain: PlainMessage,
proof: Proof,
section_pk: bls::PublicKey,
) -> Result<Self> {
Self::new_signed(
SrcAuthority::Section {
src_name: plain.src,
proof,
},
plain.dst,
plain.variant,
section_pk,
)
}
/// Verify this message is properly signed and trusted.
pub(crate) fn verify<'a, I>(&self, trusted_keys: I) -> Result<VerifyStatus>
where
I: IntoIterator<Item = &'a bls::PublicKey>,
{
let bytes = bincode::serialize(&SignableView {
dst: &self.dst,
variant: &self.variant,
})
.map_err(|_| Error::InvalidMessage)?;
match &self.src {
SrcAuthority::Node {
public_key,
signature,
..
} => {
if public_key.verify(&bytes, signature).is_err() {
return Err(Error::FailedSignature);
}
// Variant-specific verification.
self.variant.verify(None, trusted_keys)
}
SrcAuthority::BlsShare { proof_share, .. } => {
// TODO: Add SectionChain as a part of SrcAuthority::BlsShare
// Proof chain is required for accumulation at destination.
// let proof_chain: SectionChain = if let Some(proof_chain) = self.proof_chain.as_ref() {
// proof_chain
// } else {
// return Err(Error::InvalidMessage);
// };
if proof_share.public_key_set.public_key() != self.section_pk {
return Err(Error::InvalidMessage);
}
if !proof_share.verify(&bytes) {
return Err(Error::FailedSignature);
}
// TODO: Add SectionChain as a part of SrcAuthority::BlsShare
// if proof_chain.check_trust(trusted_keys) {
// Ok(VerifyStatus::Full)
// } else {
// Ok(VerifyStatus::Unknown)
// }
Ok(VerifyStatus::Full)
}
SrcAuthority::Section { proof, .. } => {
// TODO: Add SectionChain as a part of SrcAuthority::Section
// Proof chain is required for section-src messages.
// let proof_chain = if let Some(proof_chain) = self.proof_chain.as_ref() {
// proof_chain
// } else {
// return Err(Error::InvalidMessage);
// };
if !self.section_pk.verify(&proof.signature, &bytes) {
return Err(Error::FailedSignature);
}
// TODO: Add SectionChain as a part of SrcAuthority::Section
// if proof_chain.check_trust(trusted_keys) {
// Ok(VerifyStatus::Full)
// } else {
// Ok(VerifyStatus::Unknown)
// }
Ok(VerifyStatus::Full)
}
}
}
/// Getter
pub fn proof(&self) -> Option<Proof> {
if let SrcAuthority::Section { proof, .. } = &self.src {
Some(proof.clone())
} else {
None
}
}
/// Getter
pub fn dst(&self) -> &DstLocation {
&self.dst
}
/// Getter
pub fn variant(&self) -> &Variant {
&self.variant
}
/// Getter
pub fn src(&self) -> &SrcAuthority {
&self.src
}
/// Getter
pub fn hash(&self) -> &MessageHash {
&self.hash
}
/// Returns the attached proof chain, if any.
pub(crate) fn section_pk(&self) -> bls::PublicKey {
self.section_pk
}
/// Returns message signed with the provided Section key i.e. known to be latest.
pub(crate) fn updated_with_latest_key(self, section_pk: bls::PublicKey) -> Result<Self, Error> {
Self::new_signed(self.src, self.dst, self.variant, section_pk)
}
}
// Ignore `serialized` and `hash` fields because they are only computed from the other fields and
// in some cases might be even absent.
impl PartialEq for Message {
fn eq(&self, other: &Self) -> bool {
self.src == other.src
&& self.dst == other.dst
&& self.variant == other.variant
&& self.section_pk == other.section_pk
}
}
impl Debug for Message {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
formatter
.debug_struct("Message")
.field("src", &self.src.src_location())
.field("dst", &self.dst)
.field("variant", &self.variant)
.finish()
}
}
#[derive(Eq, PartialEq, Debug)]
pub enum VerifyStatus {
// The message has been fully verified.
Full,
// The message trust and integrity cannot be verified because it's proof is not trusted by us,
// even though it is valid. The message should be relayed to other nodes who might be able to
// verify it.
Unknown,
}
/// Status of an incomming message.
#[derive(Eq, PartialEq)]
pub enum MessageStatus {
/// Message is useful and should be handled.
Useful,
/// Message is useless and should be discarded.
Useless,
/// Message trust can't be established.
Untrusted,
}
#[derive(Debug, Error)]
pub enum CreateError {
#[error("signature check failed")]
FailedSignature,
#[error("public key mismatch")]
PublicKeyMismatch,
}
/// Error returned from `Message::extend_proof_chain`.
#[derive(Debug, Error)]
pub enum ExtendProofChainError {
#[error("message has no proof chain")]
NoProofChain,
#[error("failed to extend proof chain: {}", .0)]
Extend(#[from] SectionChainError),
#[error("failed to re-create message: {}", .0)]
Create(#[from] CreateError),
}
// View of a message that can be serialized for the purpose of signing.
#[derive(Serialize)]
pub(crate) struct SignableView<'a> {
// TODO: why don't we include also `src`?
pub dst: &'a DstLocation,
pub variant: &'a Variant,
}