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
#![cfg_attr(feature = "strict", deny(warnings))]
#![deny(
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces
)]
#[macro_use]
extern crate failure;
#[macro_use]
extern crate pest_derive;
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
#[macro_use]
extern crate serde_derive;
pub mod blockstamp;
mod currencies_codes;
pub mod documents;
pub mod parsers;
pub mod text_document_traits;
use crate::currencies_codes::*;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use dup_crypto::hashs::Hash;
use dup_crypto::keys::*;
use pest::iterators::Pair;
use pest::RuleType;
use serde::Serialize;
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Error, Formatter};
use std::io::Cursor;
use std::mem;
pub use crate::blockstamp::{Blockstamp, PreviousBlockstamp};
#[derive(Parser)]
#[grammar = "documents_grammar.pest"]
struct DocumentsParser;
pub trait TextDocumentParser<R: RuleType> {
type DocumentType;
fn parse(doc: &str) -> Result<Self::DocumentType, TextDocumentParseError>;
fn from_pest_pair(pairs: Pair<R>) -> Self::DocumentType;
}
#[derive(Debug, Clone, Fail)]
pub enum TextDocumentParseError {
#[fail(display = "TextDocumentParseError: Invalid inner format.")]
InvalidInnerFormat(&'static str),
#[fail(display = "TextDocumentParseError: PestError.")]
PestError(String),
#[fail(display = "TextDocumentParseError: UnexpectedVersion.")]
UnexpectedVersion(String),
#[fail(display = "TextDocumentParseError: UnknownType.")]
UnknownType,
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, Hash)]
pub struct CurrencyName(pub String);
impl Default for CurrencyName {
fn default() -> CurrencyName {
CurrencyName(String::from("default_currency"))
}
}
impl Display for CurrencyName {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{}", self.0)
}
}
#[derive(Debug)]
pub enum CurrencyCodeError {
UnknowCurrencyCode(),
IoError(::std::io::Error),
UnknowCurrencyName(),
}
impl From<::std::io::Error> for CurrencyCodeError {
fn from(error: ::std::io::Error) -> Self {
CurrencyCodeError::IoError(error)
}
}
impl CurrencyName {
pub fn from(currency_code: [u8; 2]) -> Result<Self, CurrencyCodeError> {
let mut currency_code_bytes = Cursor::new(currency_code.to_vec());
let currency_code = currency_code_bytes.read_u16::<BigEndian>()?;
Self::from_u16(currency_code)
}
pub fn from_u16(currency_code: u16) -> Result<Self, CurrencyCodeError> {
match currency_code {
tmp if tmp == *CURRENCY_NULL => Ok(CurrencyName(String::from(""))),
tmp if tmp == *CURRENCY_G1 => Ok(CurrencyName(String::from("g1"))),
tmp if tmp == *CURRENCY_G1_TEST => Ok(CurrencyName(String::from("g1-test"))),
_ => Err(CurrencyCodeError::UnknowCurrencyCode()),
}
}
pub fn to_bytes(&self) -> Result<[u8; 2], CurrencyCodeError> {
let currency_code = match self.0.as_str() {
"g1" => *CURRENCY_G1,
"g1-test" => *CURRENCY_G1_TEST,
_ => return Err(CurrencyCodeError::UnknowCurrencyName()),
};
let mut buffer = [0u8; mem::size_of::<u16>()];
buffer
.as_mut()
.write_u16::<BigEndian>(currency_code)
.expect("Unable to write");
Ok(buffer)
}
}
#[derive(Copy, Clone, Debug, Deserialize, Ord, PartialEq, PartialOrd, Eq, Hash, Serialize)]
pub struct BlockId(pub u32);
impl Display for BlockId {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{}", self.0)
}
}
#[derive(Copy, Clone, Default, Deserialize, Eq, Ord, PartialEq, PartialOrd, Hash, Serialize)]
pub struct BlockHash(pub Hash);
impl Display for BlockHash {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{}", self.0.to_hex())
}
}
impl Debug for BlockHash {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "BlockHash({})", self)
}
}
pub trait Document: Debug + Clone + PartialEq + Eq {
type PublicKey: PublicKey;
type CurrencyType: ?Sized;
fn version(&self) -> u16;
fn currency(&self) -> &Self::CurrencyType;
fn blockstamp(&self) -> Blockstamp;
fn issuers(&self) -> &Vec<Self::PublicKey>;
fn signatures(&self) -> &Vec<<Self::PublicKey as PublicKey>::Signature>;
fn as_bytes(&self) -> &[u8];
fn verify_signatures(&self) -> VerificationResult {
let issuers_count = self.issuers().len();
let signatures_count = self.signatures().len();
if issuers_count != signatures_count {
VerificationResult::IncompletePairs(issuers_count, signatures_count)
} else {
let issuers = self.issuers();
let signatures = self.signatures();
let mismatches: Vec<_> = issuers
.iter()
.zip(signatures)
.enumerate()
.filter(|&(_, (key, signature))| !key.verify(self.as_bytes(), signature))
.map(|(i, _)| i)
.collect();
if mismatches.is_empty() {
VerificationResult::Valid()
} else {
VerificationResult::Invalid(mismatches)
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerificationResult {
Valid(),
IncompletePairs(usize, usize),
Invalid(Vec<usize>),
}
pub trait IntoSpecializedDocument<P> {
fn into_specialized(self) -> P;
}
pub trait DocumentBuilder {
type Document: Document;
type PrivateKey: PrivateKey<
Signature = <<Self::Document as Document>::PublicKey as PublicKey>::Signature,
>;
fn build_with_signature(
&self,
signatures: Vec<<<Self::Document as Document>::PublicKey as PublicKey>::Signature>,
) -> Self::Document;
fn build_and_sign(&self, private_keys: Vec<Self::PrivateKey>) -> Self::Document;
}
pub trait DocumentParser<S, D, E> {
fn parse(source: S) -> Result<D, E>;
}
pub trait ToStringObject {
type StringObject: Serialize;
fn to_string_object(&self) -> Self::StringObject;
}
pub trait ToJsonObject: ToStringObject {
fn to_json_string(&self) -> Result<String, serde_json::Error> {
Ok(serde_json::to_string(&self.to_string_object())?)
}
fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
Ok(serde_json::to_string_pretty(&self.to_string_object())?)
}
}
impl<T: ToStringObject> ToJsonObject for T {}
#[cfg(test)]
mod tests {
use super::*;
use crate::documents::DUBPDocument;
#[test]
fn parse_dubp_document() {
let text = "Version: 10
Type: Identity
Currency: g1
Issuer: D9D2zaJoWYWveii1JRYLVK3J4Z7ZH3QczoKrnQeiM6mx
UniqueID: elois
Timestamp: 0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855
Ydnclvw76/JHcKSmU9kl9Ie0ne5/X8NYOqPqbGnufIK3eEPRYYdEYaQh+zffuFhbtIRjv6m/DkVLH5cLy/IyAg==";
let doc = DUBPDocument::parse(text).expect("Fail to parse DUBPDocument !");
println!("Doc : {:?}", doc);
}
}