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
use super::wire_msg_header::WireMsgHeader;
use crate::messaging::{
data::{ServiceError, ServiceMsg},
system::SystemMsg,
AuthorityProof, DstLocation, Error, MessageId, MessageType, MsgKind, NodeMsgAuthority, Result,
ServiceAuth,
};
use bls::PublicKey as BlsPublicKey;
use bytes::Bytes;
use custom_debug::Debug;
use serde::Serialize;
use std::io::Write;
use xor_name::XorName;
#[derive(Clone, Debug)]
pub struct WireMsg {
pub header: WireMsgHeader,
#[debug(skip)]
pub payload: Bytes,
#[cfg(feature = "unstable-wiremsg-debuginfo")]
pub(crate) payload_debug: Option<std::sync::Arc<dyn std::fmt::Debug + Send + Sync>>,
}
impl PartialEq for WireMsg {
fn eq(&self, other: &Self) -> bool {
self.header == other.header && self.payload == other.payload
}
}
impl WireMsg {
pub fn serialize_msg_payload<T: Serialize>(msg: &T) -> Result<Bytes> {
let payload_vec = rmp_serde::to_vec_named(&msg).map_err(|err| {
Error::Serialisation(format!(
"could not serialize message payload with Msgpack: {}",
err
))
})?;
Ok(Bytes::from(payload_vec))
}
pub fn new_msg(
msg_id: MessageId,
payload: Bytes,
msg_kind: MsgKind,
dst_location: DstLocation,
) -> Result<Self> {
Ok(Self {
header: WireMsgHeader::new(msg_id, msg_kind, dst_location),
payload,
#[cfg(feature = "unstable-wiremsg-debuginfo")]
payload_debug: None,
})
}
pub fn from(bytes: Bytes) -> Result<Self> {
let (header, payload) = WireMsgHeader::from(bytes)?;
Ok(Self {
header,
payload,
#[cfg(feature = "unstable-wiremsg-debuginfo")]
payload_debug: None,
})
}
pub fn serialize(&self) -> Result<Bytes> {
let max_length = 10 * (WireMsgHeader::max_size() as usize + self.payload.len());
let mut buffer = vec![0u8; max_length];
let (mut buf_at_payload, bytes_written) = self.header.write(&mut buffer)?;
buf_at_payload.write_all(&self.payload).map_err(|err| {
Error::Serialisation(format!(
"message payload (size {}) couldn't be serialized: {}",
self.payload.len(),
err
))
})?;
buffer.truncate(bytes_written as usize + self.payload.len());
Ok(Bytes::from(buffer))
}
pub fn into_message(&self) -> Result<MessageType> {
match self.header.msg_envelope.msg_kind.clone() {
MsgKind::ServiceMsg(auth) => {
let msg: ServiceMsg = rmp_serde::from_slice(&self.payload).map_err(|err| {
Error::FailedToParse(format!("Data message payload as Msgpack: {}", err))
})?;
let auth = if let ServiceMsg::ServiceError(ServiceError {
source_message: Some(payload),
..
}) = &msg
{
AuthorityProof::verify(auth, payload)?
} else {
AuthorityProof::verify(auth, &self.payload)?
};
Ok(MessageType::Service {
msg_id: self.header.msg_envelope.msg_id,
auth,
dst_location: self.header.msg_envelope.dst_location,
msg,
})
}
MsgKind::NodeAuthMsg(node_signed) => {
let msg: SystemMsg = rmp_serde::from_slice(&self.payload).map_err(|err| {
Error::FailedToParse(format!("Node signed message payload as Msgpack: {}", err))
})?;
Ok(MessageType::System {
msg_id: self.header.msg_envelope.msg_id,
msg_authority: NodeMsgAuthority::Node(AuthorityProof::verify(
node_signed,
&self.payload,
)?),
dst_location: self.header.msg_envelope.dst_location,
msg,
})
}
MsgKind::NodeBlsShareAuthMsg(bls_share_signed) => {
let msg: SystemMsg = rmp_serde::from_slice(&self.payload).map_err(|err| {
Error::FailedToParse(format!(
"Node message payload (BLS share signed) as Msgpack: {}",
err
))
})?;
Ok(MessageType::System {
msg_id: self.header.msg_envelope.msg_id,
msg_authority: NodeMsgAuthority::BlsShare(AuthorityProof::verify(
bls_share_signed,
&self.payload,
)?),
dst_location: self.header.msg_envelope.dst_location,
msg,
})
}
}
}
pub fn msg_id(&self) -> MessageId {
self.header.msg_envelope.msg_id
}
pub fn set_msg_id(&mut self, msg_id: MessageId) {
self.header.msg_envelope.msg_id = msg_id;
}
pub fn msg_kind(&self) -> &MsgKind {
&self.header.msg_envelope.msg_kind
}
pub fn dst_section_pk(&self) -> Option<BlsPublicKey> {
self.header.msg_envelope.dst_location.section_pk()
}
pub fn set_dst_section_pk(&mut self, pk: BlsPublicKey) {
self.header.msg_envelope.dst_location.set_section_pk(pk)
}
pub fn set_dst_xorname(&mut self, name: XorName) {
self.header.msg_envelope.dst_location.set_name(name)
}
pub fn dst_location(&self) -> &DstLocation {
&self.header.msg_envelope.dst_location
}
pub fn src_section_pk(&self) -> Option<BlsPublicKey> {
match &self.header.msg_envelope.msg_kind {
MsgKind::NodeAuthMsg(node_signed) => Some(node_signed.section_pk),
MsgKind::NodeBlsShareAuthMsg(bls_share_signed) => Some(bls_share_signed.section_pk),
_ => None,
}
}
pub fn deserialize(bytes: Bytes) -> Result<MessageType> {
Self::from(bytes)?.into_message()
}
pub fn verify_sig(auth: ServiceAuth, msg: ServiceMsg) -> Result<AuthorityProof<ServiceAuth>> {
Self::serialize_msg_payload(&msg).and_then(|payload| AuthorityProof::verify(auth, &payload))
}
#[cfg(feature = "unstable-wiremsg-debuginfo")]
pub(crate) fn set_payload_debug(
mut self,
payload_debug: impl std::fmt::Debug + Send + Sync + 'static,
) -> Self {
self.payload_debug = Some(std::sync::Arc::new(payload_debug));
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
messaging::{
data::{DataQuery, ServiceMsg, StorageLevel},
system::{NodeCmd, SystemMsg},
AuthorityProof, MessageId, NodeAuth, ServiceAuth,
},
types::{ChunkAddress, Keypair},
};
use bls::SecretKey;
use eyre::Result;
use rand::rngs::OsRng;
use xor_name::XorName;
#[test]
fn serialisation_node_msg() -> Result<()> {
let src_section_pk = SecretKey::random().public_key();
let mut rng = OsRng;
let src_node_keypair = ed25519_dalek::Keypair::generate(&mut rng);
let dst_name = XorName::random();
let dst_section_pk = SecretKey::random().public_key();
let dst_location = DstLocation::Node {
name: dst_name,
section_pk: dst_section_pk,
};
let msg_id = MessageId::new();
let pk = crate::types::PublicKey::Bls(dst_section_pk);
let node_msg = SystemMsg::NodeCmd(NodeCmd::RecordStorageLevel {
node_id: pk,
section: pk.into(),
level: StorageLevel::zero(),
});
let payload = WireMsg::serialize_msg_payload(&node_msg)?;
let node_auth = NodeAuth::authorize(src_section_pk, &src_node_keypair, &payload);
let msg_kind = MsgKind::NodeAuthMsg(node_auth.clone().into_inner());
let wire_msg = WireMsg::new_msg(msg_id, payload, msg_kind, dst_location)?;
let serialized = wire_msg.serialize()?;
let deserialized = WireMsg::from(serialized)?;
assert_eq!(deserialized, wire_msg);
assert_eq!(deserialized.msg_id(), wire_msg.msg_id());
assert_eq!(deserialized.dst_location(), &dst_location);
assert_eq!(deserialized.dst_section_pk(), Some(dst_section_pk));
assert_eq!(deserialized.src_section_pk(), Some(src_section_pk));
assert_eq!(
deserialized.into_message()?,
MessageType::System {
msg_id: wire_msg.msg_id(),
msg_authority: NodeMsgAuthority::Node(node_auth),
dst_location,
msg: node_msg,
}
);
Ok(())
}
#[test]
fn serialisation_client_msg() -> Result<()> {
let mut rng = OsRng;
let src_client_keypair = Keypair::new_ed25519(&mut rng);
let dst_name = XorName::random();
let dst_section_pk = SecretKey::random().public_key();
let dst_location = DstLocation::Node {
name: dst_name,
section_pk: dst_section_pk,
};
let msg_id = MessageId::new();
let client_msg = ServiceMsg::Query(DataQuery::GetChunk(ChunkAddress(XorName::random())));
let payload = WireMsg::serialize_msg_payload(&client_msg)?;
let auth = ServiceAuth {
public_key: src_client_keypair.public_key(),
signature: src_client_keypair.sign(&payload),
};
let auth_proof = AuthorityProof::verify(auth.clone(), &payload).unwrap();
let msg_kind = MsgKind::ServiceMsg(auth);
let wire_msg = WireMsg::new_msg(msg_id, payload, msg_kind, dst_location)?;
let serialized = wire_msg.serialize()?;
let deserialized = WireMsg::from(serialized)?;
assert_eq!(deserialized, wire_msg);
assert_eq!(deserialized.msg_id(), wire_msg.msg_id());
assert_eq!(deserialized.dst_location(), &dst_location);
assert_eq!(deserialized.dst_section_pk(), Some(dst_section_pk));
assert_eq!(deserialized.src_section_pk(), None);
assert_eq!(
deserialized.into_message()?,
MessageType::Service {
msg_id: wire_msg.msg_id(),
auth: auth_proof,
dst_location,
msg: client_msg,
}
);
Ok(())
}
}