mitrid_core 0.9.4

Core library of the Mitrid framework
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! # Wallet
//!
//! `wallet` is the module providing the type used for wallets (accounts) in the distributed ledger.

use std::mem;

use base::Result;
use base::Checkable;
use base::Datable;
use base::Serializable;
use base::{Sizable, ConstantSize};
use base::{Eval, EvalMut};
use base::Numerical;
use base::Meta;
use crypto::Hash;
use io::{Store, Storable};
use model::Coin;

/// Code of the `Wallet` type.
pub const WALLET_CODE: u64 = 7;

/// Type used to represent a wallet (account) in the distributed ledger.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash, Serialize, Deserialize)]
pub struct Wallet<D, A, P>
    where   D: Ord + Datable + ConstantSize,
            A: Numerical,
            P: Datable
{
    /// Wallet id. It is the digest of the same wallet, but with a default `D` id.
    pub id: D,
    /// Wallet metadata.
    pub meta: Meta,
    /// Wallet spent coins length.
    pub spent_coins_len: u64,
    /// Wallet spent coins.
    pub spent_coins: Vec<Coin<D, A>>,
    /// Wallet unspent coins length.
    pub unspent_coins_len: u64,
    /// Wallet unspent coins.
    pub unspent_coins: Vec<Coin<D, A>>,
    /// Custom payload.
    pub payload: P,
}

impl<D, A, P> Wallet<D, A, P>
    where   D: Ord + Datable + ConstantSize,
            P: Datable,
            A: Numerical,
            Self: Serializable
{
    /// Creates a new `Wallet`.
    pub fn new() -> Self {
        let mut wallet = Wallet::default();
        wallet.update_size();
        wallet
    }

    /// Updates the `Wallet` size.
    pub fn update_size(&mut self) {
        let size = self.size();

        self.meta.set_size(size);
    }

    /// Sets the `Wallet`'s metadata.
    pub fn meta(mut self, meta: &Meta) -> Result<Self> {
        meta.check()?;
        self.meta = meta.clone();

        self.update_size();

        Ok(self)
    }

    /// Sets the `Wallet`s set of spent `Coin`s and its lenght.
    pub fn spent_coins(mut self, spent_coins: &Vec<Coin<D, A>>) -> Result<Self> {
        spent_coins.check()?;

        let mut unique_spent_coins = spent_coins.clone();
        unique_spent_coins.dedup_by(|a, b| { a == b });

        if unique_spent_coins.len() != spent_coins.len() {
            return Err(format!("duplicates found"));
        }

        for ref coin in spent_coins {
            if self.unspent_coins.contains(&coin) {
                return Err(format!("spent and unpent not disjunct"))
            }
        }

        self.spent_coins_len = spent_coins.len() as u64;
        self.spent_coins = spent_coins.clone();

        self.update_size();

        Ok(self)
    }

    /// Adds a spent `Coin` to the `Wallet` set of spent `Coin`s.
    pub fn add_spent_coin(&mut self, spent_coin: &Coin<D, A>) -> Result<()> {
        spent_coin.check()?;
        
        if self.spent_coins.contains(spent_coin) {
            return Err(format!("already found"));
        }

        if self.unspent_coins.contains(spent_coin) {
            return Err(format!("already found"));
        }

        self.spent_coins.push(spent_coin.to_owned());
        self.spent_coins_len += 1;

        Ok(())
    }

    /// Removes a spent `Coin` from the `Wallet` set of spent `Coin`s.
    pub fn del_spent_coin(&mut self, spent_coin: &Coin<D, A>) -> Result<()> {
        spent_coin.check()?;
        
        if !self.spent_coins.contains(spent_coin) {
            return Err(format!("not found"));
        }

        if self.unspent_coins.contains(spent_coin) {
            return Err(format!("already found"));
        }

        let idx = self.spent_coins.binary_search(spent_coin)
                    .map_err(|e| format!("{:?}", e))?;

        self.spent_coins.remove(idx);
        self.spent_coins_len -= 1;

        Ok(())
    }

    /// Sets the `Wallet`s set of unspent `Coin`s and its lenght.
    pub fn unspent_coins(mut self, unspent_coins: &Vec<Coin<D, A>>) -> Result<Self> {
        unspent_coins.check()?;

        let mut unique_unspent_coins = unspent_coins.clone();
        unique_unspent_coins.dedup_by(|a, b| { a == b });

        if unique_unspent_coins.len() != unspent_coins.len() {
            return Err(format!("duplicates found"));
        }

        for ref coin in unspent_coins {
            if self.spent_coins.contains(&coin) {
                return Err(format!("spent and unpent not disjunct"))
            }
        }

        self.unspent_coins_len = unspent_coins.len() as u64;
        self.unspent_coins = unspent_coins.clone();

        self.update_size();

        Ok(self)
    }

    /// Adds an unspent `Coin` to the `Wallet` set of unspent `Coin`s.
    pub fn add_unspent_coin(&mut self, unspent_coin: &Coin<D, A>) -> Result<()> {
        unspent_coin.check()?;
        
        if self.unspent_coins.contains(unspent_coin) {
            return Err(format!("already found"));
        }

        if self.spent_coins.contains(unspent_coin) {
            return Err(format!("already found"));
        }

        self.unspent_coins.push(unspent_coin.to_owned());
        self.unspent_coins_len += 1;

        Ok(())
    }

    /// Removes a unspent `Coin` from the `Wallet` set of unspent `Coin`s.
    pub fn del_unspent_coin(&mut self, unspent_coin: &Coin<D, A>) -> Result<()> {
        unspent_coin.check()?;
        
        if !self.unspent_coins.contains(unspent_coin) {
            return Err(format!("not found"));
        }

        if self.spent_coins.contains(unspent_coin) {
            return Err(format!("already found"));
        }

        let idx = self.unspent_coins.binary_search(unspent_coin)
                    .map_err(|e| format!("{:?}", e))?;

        self.unspent_coins.remove(idx);
        self.unspent_coins_len -= 1;

        Ok(())
    }

    /// Sets an unspent `Coin` as spent, removing it from the set of unspent `Coin`s
    /// and adding it to the set of spent `Coin`s.
    pub fn spend_coin(&mut self, unspent_coin: &Coin<D, A>) -> Result<()> {
        self.del_unspent_coin(unspent_coin)?;
        self.add_spent_coin(unspent_coin)?;

        Ok(())
    }

    /// Sets the `Wallet`'s custom payload.
    pub fn payload(mut self, payload: &P) -> Result<Self> {
        payload.check()?;

        self.payload = payload.clone();

        self.update_size();

        Ok(self)
    }

    /// Finalizes the `Wallet`, building its id and returning it's complete form.
    pub fn finalize<H: Hash<D>>(mut self, hasher: &mut H) -> Result<Self> {
        let msg = self.to_bytes()?;
        self.id = hasher.digest(&msg)?;

        self.update_size();

        self.check()?;

        Ok(self)
    }

    /// Hashes cryptographically the `Wallet`.
    pub fn digest<H: Hash<D>>(&self, hasher: &mut H) -> Result<D> {
        let mut wallet = self.clone();
        wallet.id = D::default();
        wallet.update_size();

        let msg = wallet.to_bytes()?;
        hasher.digest(&msg)
    }

    /// Verifies the cryptographic digest against the `Wallet`'s digest.
    pub fn verify_digest<H: Hash<D>>(&self, hasher: &mut H) -> Result<bool> {
        let digest = self.id.clone();
        digest.check()?;

        let mut wallet = self.clone();
        wallet.id = D::default();
        wallet.update_size();

        let msg = wallet.to_bytes()?;
        hasher.verify(&msg, &digest)
    }

    /// Checks the cryptographic digest against the `Wallet`'s digest.
    pub fn check_digest<H: Hash<D>>(&self, hasher: &mut H) -> Result<()> {
        let digest = self.id.clone();
        digest.check()?;

        let mut wallet = self.clone();
        wallet.id = D::default();
        wallet.update_size();

        let msg = wallet.to_bytes()?;
        hasher.check(&msg, &digest)
    }

    /// Evals the `Wallet`.
    pub fn eval<Ev, EP, ER>(&self, params: &EP, evaluator: &Ev)
        -> Result<ER>
        where   Ev: Eval<Self, EP, ER>,
                EP: Datable,
                ER: Datable
    {
        self.check()?;
        params.check()?;

        evaluator.eval(self, params)
    }

    /// Evals mutably the `Wallet`.
    pub fn eval_mut<EvM, EP, ER>(&mut self, params: &EP, evaluator: &mut EvM)
        -> Result<ER>
        where   EvM: EvalMut<Self, EP, ER>,
                EP: Datable,
                ER: Datable
    {
        self.check()?;
        params.check()?;

        let result = evaluator.eval_mut(self, params)?;
        self.update_size();

        self.check()?;

        Ok(result)
    }
}

impl<D, A, P> Sizable for Wallet<D, A, P>
    where   D: Ord + Datable + ConstantSize,
            A: Numerical,
            P: Datable
{
    fn size(&self) -> u64 {
        self.id.size() +
            self.meta.size() +
            self.payload.size()
    }
}

impl<D, A, P> Checkable for Wallet<D, A, P>
    where   D: Ord + Datable + ConstantSize,
            A: Numerical,
            P: Datable
{
    fn check(&self) -> Result<()> {
        self.id.check()?;
        self.id.check_size()?;
        self.meta.check()?;
        
        if self.meta.get_size() != self.size() {
            return Err(String::from("invalid meta size"));
        }

        self.spent_coins_len.check()?;
        self.spent_coins.check()?;

        if self.spent_coins.len() != self.spent_coins_len as usize {
            return Err(String::from("invalid spent coins length"));
        }

        let mut unique_spent_coins = self.spent_coins.clone();
        unique_spent_coins.dedup_by(|a, b| { a == b });

        if unique_spent_coins.len() != self.spent_coins.len() {
            return Err(format!("duplicates found"));
        }

        self.unspent_coins_len.check()?;
        self.unspent_coins.check()?;

        if self.unspent_coins.len() != self.unspent_coins_len as usize {
            return Err(String::from("invalid unspent coins length"));
        }

        let mut unique_unspent_coins = self.unspent_coins.clone();
        unique_unspent_coins.dedup_by(|a, b| { a == b });

        if unique_unspent_coins.len() != self.unspent_coins.len() {
            return Err(format!("duplicates found"));
        }

        for ref coin in self.spent_coins.iter() {
            if self.unspent_coins.contains(&coin) {
                return Err(format!("spent and unpent not disjunct"))
            }
        }

        for ref coin in self.unspent_coins.iter() {
            if self.spent_coins.contains(&coin) {
                return Err(format!("spent and unpent not disjunct"))
            }
        }

        self.payload.check()?;

        Ok(())
    }
}

impl<D, A, P> Serializable for Wallet<D, A, P>
    where   D: Ord + Datable + ConstantSize + Serializable,
            A: Numerical + Serializable,
            P: Datable + Serializable
{}

impl<D, A, P> Datable for Wallet<D, A, P>
    where   D: Ord + Datable + ConstantSize,
            A: Numerical,
            P: Datable
{}

impl<St, S, D, A, P>
    Storable<St, S, D, Wallet<D, A, P>>
    for Wallet<D, A, P>
    where   St: Store<S>,
            S: Datable + Serializable,
            D: Ord + Datable + ConstantSize + Serializable,
            A: Numerical + Serializable,
            P: Datable + Serializable
{
    fn store_prefix() -> Vec<u8> {
        let mut prefix = Vec::new();

        let _prefix: [u8; 8] = unsafe { mem::transmute(WALLET_CODE) };
        prefix.extend_from_slice(&_prefix[..]);

        prefix
    }

    fn store_key(&self) -> Result<D> {
        self.id.check()?;

        Ok(self.id.clone())
    }

    fn store_value(&self) -> Result<Self> {
        self.check()?;

        Ok(self.clone())
    }
}