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
//  Copyright (C) 2017-2019  The AXIOM TEAM Association.
//
// 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/>.

//! Wrappers around Identity documents V10.

use durs_common_tools::fatal_error;

use crate::documents::*;
use crate::text_document_traits::*;
use crate::Blockstamp;

/// Wrap an Identity document.
///
/// Must be created by parsing a text document or using a builder.
#[derive(Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
pub struct IdentityDocumentV10 {
    /// Document as text.
    ///
    /// Is used to check signatures, and other values
    /// must be extracted from it.
    text: Option<String>,

    /// Currency.
    currency: String,
    /// Unique ID
    username: String,
    /// Blockstamp
    blockstamp: Blockstamp,
    /// Document issuer (there should be only one).
    issuers: Vec<PubKey>,
    /// Document signature (there should be only one).
    signatures: Vec<Sig>,
}

#[derive(Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
/// identity document for jsonification
pub struct IdentityDocumentV10Stringified {
    /// Currency.
    pub currency: String,
    /// Unique ID
    pub username: String,
    /// Blockstamp
    pub blockstamp: String,
    /// Document issuer
    pub issuer: String,
    /// Document signature
    pub signature: String,
}

impl ToStringObject for IdentityDocumentV10 {
    type StringObject = IdentityDocumentV10Stringified;
    /// Transforms an object into a json object
    fn to_string_object(&self) -> IdentityDocumentV10Stringified {
        IdentityDocumentV10Stringified {
            currency: self.currency.clone(),
            username: self.username.clone(),
            blockstamp: format!("{}", self.blockstamp),
            issuer: format!("{}", self.issuers[0]),
            signature: format!("{}", self.signatures[0]),
        }
    }
}

impl IdentityDocumentV10 {
    /// Unique ID
    pub fn username(&self) -> &str {
        &self.username
    }

    /// Lightens the membership (for example to store it while minimizing the space required)
    pub fn reduce(&mut self) {
        self.text = None;
    }
    /// From pest parser pair
    pub fn from_pest_pair(pair: Pair<Rule>) -> Result<IdentityDocumentV10, TextDocumentParseError> {
        let doc = pair.as_str();
        let mut currency = "";
        let mut pubkey_str = "";
        let mut uid = "";
        let mut blockstamp = Blockstamp::default();
        let mut sig_str = "";
        for field in pair.into_inner() {
            match field.as_rule() {
                Rule::currency => currency = field.as_str(),
                Rule::pubkey => pubkey_str = field.as_str(),
                Rule::uid => uid = field.as_str(),
                Rule::blockstamp => {
                    let mut inner_rules = field.into_inner(); // { integer ~ "-" ~ hash }

                    let block_id: &str = inner_rules.next().unwrap().as_str();
                    let block_hash: &str = inner_rules.next().unwrap().as_str();
                    blockstamp = Blockstamp {
                        id: BlockNumber(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::ed25519_sig => sig_str = field.as_str(),
                Rule::EOI => (),
                _ => fatal_error!("unexpected rule"), // Grammar ensures that we never reach this line
            }
        }

        Ok(IdentityDocumentV10 {
            text: Some(doc.to_owned()),
            currency: currency.to_owned(),
            username: uid.to_owned(),
            blockstamp,
            issuers: vec![PubKey::Ed25519(
                ed25519::PublicKey::from_base58(pubkey_str).unwrap(),
            )], // Grammar ensures that we have a base58 string.
            signatures: vec![Sig::Ed25519(
                ed25519::Signature::from_base64(sig_str).unwrap(),
            )], // Grammar ensures that we have a base64 string.
        })
    }
}

impl Document for IdentityDocumentV10 {
    type PublicKey = PubKey;

    fn version(&self) -> u16 {
        10
    }

    fn currency(&self) -> &str {
        &self.currency
    }

    fn blockstamp(&self) -> Blockstamp {
        self.blockstamp
    }

    fn issuers(&self) -> &Vec<PubKey> {
        &self.issuers
    }

    fn signatures(&self) -> &Vec<Sig> {
        &self.signatures
    }

    fn as_bytes(&self) -> &[u8] {
        self.as_text_without_signature().as_bytes()
    }
}

/// CompactIdentityDocumentV10
#[derive(Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
pub struct CompactIdentityDocumentV10 {
    /// Unique ID
    username: String,
    /// Blockstamp
    blockstamp: Blockstamp,
    /// Document issuer
    pubkey: PubKey,
    /// Document signature
    signature: Sig,
}

impl CompactTextDocument for CompactIdentityDocumentV10 {
    fn as_compact_text(&self) -> String {
        format!(
            "{issuer}:{signature}:{blockstamp}:{username}",
            issuer = self.pubkey,
            signature = self.signature,
            blockstamp = self.blockstamp,
            username = self.username,
        )
    }
}

impl TextDocument for IdentityDocumentV10 {
    type CompactTextDocument_ = CompactIdentityDocumentV10;

    fn as_text(&self) -> &str {
        if let Some(ref text) = self.text {
            text
        } else {
            fatal_error!("Try to get text of reduce identity !")
        }
    }

    fn to_compact_document(&self) -> Self::CompactTextDocument_ {
        CompactIdentityDocumentV10 {
            username: self.username.clone(),
            blockstamp: self.blockstamp,
            pubkey: self.issuers[0],
            signature: self.signatures[0],
        }
    }
}

/// Identity document builder.
#[derive(Debug, Copy, Clone)]
pub struct IdentityDocumentV10Builder<'a> {
    /// Document currency.
    pub currency: &'a str,
    /// Identity unique id.
    pub username: &'a str,
    /// Reference blockstamp.
    pub blockstamp: &'a Blockstamp,
    /// Document/identity issuer.
    pub issuer: &'a PubKey,
}

impl<'a> IdentityDocumentV10Builder<'a> {
    fn build_with_text_and_sigs(self, text: String, signatures: Vec<Sig>) -> IdentityDocumentV10 {
        IdentityDocumentV10 {
            text: Some(text),
            currency: self.currency.to_string(),
            username: self.username.to_string(),
            blockstamp: *self.blockstamp,
            issuers: vec![*self.issuer],
            signatures,
        }
    }
}

impl<'a> DocumentBuilder for IdentityDocumentV10Builder<'a> {
    type Document = IdentityDocumentV10;
    type PrivateKey = PrivKey;

    fn build_with_signature(&self, signatures: Vec<Sig>) -> IdentityDocumentV10 {
        self.build_with_text_and_sigs(self.generate_text(), signatures)
    }

    fn build_and_sign(&self, private_keys: Vec<PrivKey>) -> IdentityDocumentV10 {
        let (text, signatures) = self.build_signed_text(private_keys);
        self.build_with_text_and_sigs(text, signatures)
    }
}

impl<'a> TextDocumentBuilder for IdentityDocumentV10Builder<'a> {
    fn generate_text(&self) -> String {
        format!(
            "Version: 10
Type: Identity
Currency: {currency}
Issuer: {issuer}
UniqueID: {username}
Timestamp: {blockstamp}
",
            currency = self.currency,
            issuer = self.issuer,
            username = self.username,
            blockstamp = self.blockstamp
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Document;
    use dup_crypto::keys::{PrivateKey, PublicKey, Signature};

    #[test]
    fn generate_real_document() {
        let pubkey = PubKey::Ed25519(
            ed25519::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV")
                .unwrap(),
        );

        let prikey = PrivKey::Ed25519(
            ed25519::PrivateKey::from_base58(
                "468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5G\
                 iERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7",
            )
            .unwrap(),
        );

        let sig = Sig::Ed25519(
            ed25519::Signature::from_base64(
                "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FGM\
                 MmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg==",
            )
            .unwrap(),
        );

        let block = Blockstamp::from_string(
            "0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855",
        )
        .unwrap();

        let builder = IdentityDocumentV10Builder {
            currency: "duniter_unit_test_currency",
            username: "tic",
            blockstamp: &block,
            issuer: &pubkey,
        };

        assert!(builder
            .build_with_signature(vec![sig])
            .verify_signatures()
            .is_ok());
        assert!(builder
            .build_and_sign(vec![prikey])
            .verify_signatures()
            .is_ok());
    }

    #[test]
    fn parse_identity_document() {
        let doc = "Version: 10
Type: Identity
Currency: duniter_unit_test_currency
Issuer: DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV
UniqueID: tic
Timestamp: 0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855
1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FGMMmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg==";

        let doc = IdentityDocumentParser::parse(doc).expect("Fail to parse idty doc !");
        println!("Doc : {:?}", doc);
        assert!(doc.verify_signatures().is_ok())
    }
}