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
//  Copyright (C) 2017  The Durs Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Module defining the format of network heads v3 and how to handle them.

use crate::*;
use base58::ToBase58;
use dubp_documents::blockstamp::Blockstamp;
use dubp_documents::{BlockHash, BlockId, CurrencyName, ToStringObject};
use dup_crypto::keys::text_signable::TextSignable;
use dup_crypto::keys::*;
use pest::iterators::Pair;
use pest::Parser;
use std::cmp::Ordering;

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Head V3
pub struct NetworkHeadV3 {
    /// Currency name
    pub currency_name: CurrencyName,
    /// WS2P Private configuration
    pub api_outgoing_conf: u8,
    /// WS2P Public configuration
    pub api_incoming_conf: u8,
    /// Issuer node free member rooms
    pub free_member_rooms: u8,
    /// Issuer node free mirror rooms
    pub free_mirror_rooms: u8,
    /// Issuer node id
    pub node_id: NodeId,
    /// Issuer pubkey
    pub pubkey: PubKey,
    /// Head blockstamp
    pub blockstamp: Blockstamp,
    /// Issuer node software
    pub software: String,
    /// Issuer node soft version
    pub soft_version: String,
    /// Issuer signature
    pub signature: Option<Sig>,
    /// Head step
    pub step: u8,
}

impl PartialOrd for NetworkHeadV3 {
    fn partial_cmp(&self, other: &NetworkHeadV3) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for NetworkHeadV3 {
    fn cmp(&self, other: &NetworkHeadV3) -> Ordering {
        self.blockstamp.cmp(&other.blockstamp)
    }
}

/*impl<'de> BinSignable<'de> for NetworkHeadV3 {
    fn issuer_pubkey(&self) -> PubKey {
        self.pubkey
    }
    fn signature(&self) -> Option<Sig> {
        self.signature
    }
    fn set_signature(&mut self, signature: Sig) {
        self.signature = Some(signature);
    }
}*/

impl TextSignable for NetworkHeadV3 {
    fn as_signable_text(&self) -> String {
        format!(
"3:{currency}:{api_outgoing_conf}:{api_incoming_conf}:{free_member_rooms}:{free_mirror_rooms}:{node_id}:{pubkey}:{blockstamp}:{software}:{soft_version}\n",
            currency = self.currency_name,
            api_outgoing_conf = self.api_outgoing_conf,
            api_incoming_conf = self.api_incoming_conf,
            free_member_rooms = self.free_member_rooms,
            free_mirror_rooms = self.free_mirror_rooms,
            node_id = format!("{}", self.node_id),
            pubkey = self.pubkey.to_base58(),
            blockstamp = self.blockstamp.to_string(),
            software = self.software,
            soft_version = self.soft_version,
        )
    }
    fn issuer_pubkey(&self) -> PubKey {
        self.pubkey
    }
    fn signature(&self) -> Option<Sig> {
        self.signature
    }
    fn set_signature(&mut self, signature: Sig) {
        self.signature = Some(signature);
    }
}

impl TextDocumentParser<Rule> for NetworkHeadV3 {
    /// Type of document generated by the parser
    type DocumentType = NetworkHeadV3;

    fn parse(doc: &str) -> Result<NetworkHeadV3, TextDocumentParseError> {
        match NetworkDocsParser::parse(Rule::head_v3, doc) {
            Ok(mut head_v3_pairs) => {
                Ok(NetworkHeadV3::from_pest_pair(head_v3_pairs.next().unwrap()))
            }
            Err(pest_error) => Err(TextDocumentParseError::PestError(format!("{}", pest_error))),
        }
    }

    fn from_pest_pair(pair: Pair<Rule>) -> NetworkHeadV3 {
        let mut currency_str = "";
        let mut api_outgoing_conf = 0;
        let mut api_incoming_conf = 0;
        let mut free_member_rooms = 0;
        let mut free_mirror_rooms = 0;
        let mut node_id = NodeId(0);
        let mut pubkey = None;
        let mut blockstamp = None;
        let mut software = "";
        let mut soft_version = "";
        let mut signature = None;
        let mut step = 0;
        for field in pair.into_inner() {
            match field.as_rule() {
                Rule::currency => currency_str = field.as_str(),
                Rule::api_outgoing_conf => api_outgoing_conf = field.as_str().parse().unwrap(),
                Rule::api_incoming_conf => api_incoming_conf = field.as_str().parse().unwrap(),
                Rule::free_member_rooms => free_member_rooms = field.as_str().parse().unwrap(),
                Rule::free_mirror_rooms => free_mirror_rooms = field.as_str().parse().unwrap(),
                Rule::node_id => node_id = NodeId(field.as_str().parse().unwrap()),
                Rule::pubkey => {
                    pubkey = Some(PubKey::Ed25519(
                        ed25519::PublicKey::from_base58(field.as_str()).unwrap(),
                    ))
                }
                Rule::blockstamp => {
                    let mut inner_rules = field.into_inner(); // { block_id ~ "-" ~ hash }

                    let block_id: &str = inner_rules.next().unwrap().as_str();
                    let block_hash: &str = inner_rules.next().unwrap().as_str();
                    blockstamp = Some(Blockstamp {
                        id: BlockId(block_id.parse().unwrap()), // Grammar ensures that we have a digits string.
                        hash: BlockHash(Hash::from_hex(block_hash).unwrap()), // Grammar ensures that we have an hexadecimal string.
                    });
                }
                Rule::software => software = field.as_str(),
                Rule::soft_version => soft_version = field.as_str(),
                Rule::ed25519_sig => {
                    signature = Some(Sig::Ed25519(
                        ed25519::Signature::from_base64(field.as_str()).unwrap(),
                    ))
                }
                Rule::step => step = field.as_str().parse().unwrap(),
                _ => panic!("unexpected rule: {:?}", field.as_rule()), // Grammar ensures that we never reach this line
            }
        }
        NetworkHeadV3 {
            currency_name: CurrencyName(currency_str.to_owned()),
            api_outgoing_conf,
            api_incoming_conf,
            free_member_rooms,
            free_mirror_rooms,
            node_id,
            pubkey: pubkey.expect("Grammar must ensure that head v3 have valid issuer pubkey !"),
            blockstamp: blockstamp
                .expect("Grammar must ensure that head v3 have valid blockstamp!"),
            software: software.to_owned(),
            soft_version: soft_version.to_owned(),
            signature,
            step,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Head V3 for json serializer
pub struct HeadV3Stringified {
    /// Head body
    pub body: String,
    /// Issuer signature
    pub signature: Option<String>,
    /// Head step
    pub step: u8,
}

impl<'a> ToStringObject for NetworkHeadV3 {
    type StringObject = HeadV3Stringified;

    fn to_string_object(&self) -> Self::StringObject {
        let body = self.as_signable_text();
        let body_len = body.len();
        HeadV3Stringified {
            body: body.chars().take(body_len - 1).collect(),
            signature: if let Some(sig) = self.signature {
                Some(sig.to_base64())
            } else {
                None
            },
            step: self.step,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::keypair1;

    #[test]
    fn head_v3_sign_and_verify() {
        let keypair = keypair1();
        let mut head_v3 = NetworkHeadV3 {
            currency_name: CurrencyName("g1".to_owned()),
            api_outgoing_conf: 0u8,
            api_incoming_conf: 0u8,
            free_mirror_rooms: 0u8,
            free_member_rooms: 0u8,
            node_id: NodeId(0),
            pubkey: PubKey::Ed25519(keypair.public_key()),
            blockstamp: Blockstamp::from_string(
                "50-000005B1CEB4EC5245EF7E33101A330A1C9A358EC45A25FC13F78BB58C9E7370",
            )
            .unwrap(),
            software: String::from("durs"),
            soft_version: String::from("0.1.0-a0.1"),
            signature: None,
            step: 0,
        };
        // Sign
        let sign_result = head_v3.sign(PrivKey::Ed25519(keypair.private_key()));
        if let Ok(head_v3_raw) = sign_result {
            println!("{}", head_v3_raw);
            assert_eq!(
                head_v3,
                NetworkHeadV3::parse(&head_v3_raw).expect("Fail to parse head v3 !")
            )
        } else {
            panic!("fail to sign head v3 : {:?}", sign_result.err().unwrap())
        }
        // Verify signature
        head_v3.verify().expect("HEADv3 : Invalid signature !");
    }
}