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
#![warn(missing_docs)]
use std::str::FromStr;
use num_bigint::BigUint;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;
use crate::dht::subring::SubRing;
use crate::dht::Did;
use crate::ecc::HashStr;
use crate::err::Error;
use crate::err::Result;
use crate::message::Encoded;
use crate::message::Encoder;
use crate::message::MessagePayload;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum VNodeType {
Data,
SubRing,
RelayMessage,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VirtualNode {
pub did: Did,
pub data: Vec<Encoded>,
pub kind: VNodeType,
}
impl<T> TryFrom<MessagePayload<T>> for VirtualNode
where T: Serialize + DeserializeOwned
{
type Error = Error;
fn try_from(msg: MessagePayload<T>) -> Result<Self> {
let did = BigUint::from(msg.addr) + BigUint::from(1u16);
let data = msg.encode()?;
Ok(Self {
did: did.into(),
data: vec![data],
kind: VNodeType::RelayMessage,
})
}
}
impl TryFrom<Encoded> for VirtualNode {
type Error = Error;
fn try_from(e: Encoded) -> Result<Self> {
let did: HashStr = e.value().into();
Ok(Self {
did: Did::from_str(&did.inner())?,
data: vec![e],
kind: VNodeType::Data,
})
}
}
impl TryFrom<String> for VirtualNode {
type Error = Error;
fn try_from(s: String) -> Result<Self> {
let encoded_message = s.encode()?;
encoded_message.try_into()
}
}
impl VirtualNode {
pub fn concat(a: &Self, b: &Self) -> Result<Self> {
match &a.kind {
VNodeType::RelayMessage => {
if a.did != b.did {
Err(Error::DidNotEqual)
} else {
Ok(Self {
did: a.did,
data: [&a.data[..], &b.data[..]].concat(),
kind: a.kind.clone(),
})
}
}
VNodeType::Data => Ok(a.clone()),
VNodeType::SubRing => {
let decoded_a: String = a.data[0].decode()?;
let decoded_b: String = a.data[0].decode()?;
let mut subring_a: SubRing =
serde_json::from_str(&decoded_a).map_err(Error::Deserialize)?;
let subring_b: SubRing =
serde_json::from_str(&decoded_b).map_err(Error::Deserialize)?;
subring_a.finger.join(subring_b.creator);
subring_a.try_into()
}
}
}
}