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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// Copyright 2017 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// spell-checker:ignore lhash, rhash, lkey, rkey, bpath, repr

use serde::{Serialize, Serializer};
use serde::ser::SerializeMap;

use std::fmt;

use crypto::{Hash, HashStream};
use super::super::{Error, StorageValue};
use super::key::{BitsRange, ChildKind, ProofMapKey, ProofPath, KEY_SIZE};

impl Serialize for ProofPath {
    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut repr = String::with_capacity(KEY_SIZE * 8);
        let bpath = self;
        for ind in 0..self.len() {
            match bpath.bit(ind) {
                ChildKind::Left => {
                    repr.push('0');
                }
                ChildKind::Right => {
                    repr.push('1');
                }
            }
        }
        ser.serialize_str(&repr)
    }
}

/// An enum that represents a proof of existence or non-existence for a proof map key.
pub enum MapProof<V> {
    /// A boundary case with a single element tree and a matching key.
    LeafRootInclusive(ProofPath, V),
    /// A boundary case with a single element tree and a non-matching key
    LeafRootExclusive(ProofPath, Hash),
    /// A boundary case with empty tree.
    Empty,
    /// A root branch of the tree.
    Branch(BranchProofNode<V>),
}

/// An enum that represents a node of the map proof.
pub enum ProofNode<V> {
    /// A branch of map proof.
    Branch(BranchProofNode<V>),
    /// A leaf of map proof with the value of the requested key.
    Leaf(V),
}

/// An enum that represents a branch node of the map proof.
pub enum BranchProofNode<V> {
    /// A branch of proof in which both children do not contain the requested key.
    BranchKeyNotFound {
        /// A hash of the left child.
        left_hash: Hash,
        /// A hash of the right child.
        right_hash: Hash,
        /// A key of the left child.
        left_key: ProofPath,
        /// A key of the right child.
        right_key: ProofPath,
    },
    /// A branch of proof in which left child may contain the requested key.
    LeftBranch {
        /// A left child node.
        left_node: Box<ProofNode<V>>,
        /// A hash of the right child.
        right_hash: Hash,
        /// A key of the left child.
        left_key: ProofPath,
        /// A key of the right child.
        right_key: ProofPath,
    },
    /// A branch of proof in which right child may contain the requested key.
    RightBranch {
        /// A hash of the left child.
        left_hash: Hash,
        /// A right child node.
        right_node: Box<ProofNode<V>>,
        /// A key of the left child.
        left_key: ProofPath,
        /// A key of the right child.
        right_key: ProofPath,
    },
}

impl<V: StorageValue> MapProof<V> {
    /// Returns root hash of the map proof.
    pub fn root_hash(&self) -> Hash {
        use self::MapProof::*;
        match *self {
            Empty => Hash::zero(),
            LeafRootInclusive(ref root_key, ref root_val) => {
                HashStream::new()
                    .update(root_key.as_bytes())
                    .update(root_val.hash().as_ref())
                    .hash()
            }
            LeafRootExclusive(ref root_key, ref root_val_hash) => {
                HashStream::new()
                    .update(root_key.as_bytes())
                    .update(root_val_hash.as_ref())
                    .hash()
            }
            Branch(ref branch) => branch.root_hash(),
        }
    }
}
impl<V: StorageValue> ProofNode<V> {
    fn root_hash(&self) -> Hash {
        use self::ProofNode::*;
        match *self {
            Leaf(ref val) => val.hash(),
            Branch(ref branch) => branch.root_hash(),
        }
    }
}

impl<V: StorageValue> BranchProofNode<V> {
    fn root_hash(&self) -> Hash {
        use self::BranchProofNode::*;
        match *self {
            BranchKeyNotFound {
                ref left_hash,
                ref right_hash,
                ref left_key,
                ref right_key,
            } => {
                HashStream::new()
                    .update(left_hash.as_ref())
                    .update(right_hash.as_ref())
                    .update(left_key.as_bytes())
                    .update(right_key.as_bytes())
                    .hash()
            }
            LeftBranch {
                ref left_node,
                ref right_hash,
                ref left_key,
                ref right_key,
            } => {
                HashStream::new()
                    .update(left_node.root_hash().as_ref())
                    .update(right_hash.as_ref())
                    .update(left_key.as_bytes())
                    .update(right_key.as_bytes())
                    .hash()
            }
            RightBranch {
                ref left_hash,
                ref right_node,
                ref left_key,
                ref right_key,
            } => {
                HashStream::new()
                    .update(left_hash.as_ref())
                    .update(right_node.root_hash().as_ref())
                    .update(left_key.as_bytes())
                    .update(right_key.as_bytes())
                    .hash()
            }
        }
    }
}

impl<V: Serialize> Serialize for MapProof<V> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use self::MapProof::*;

        match *self {
            Empty => {
                let state = serializer.serialize_map(Some(0))?;
                state.end()
            }
            LeafRootInclusive(ref key, ref value) => {
                #[derive(Serialize)]
                struct SerializeHelper<'a, V: Serialize + 'a> {
                    val: &'a V,
                }
                let helper = SerializeHelper { val: value };
                let mut state = serializer.serialize_map(Some(1))?;
                state.serialize_entry(key, &helper)?;
                state.end()
            }
            LeafRootExclusive(ref key, ref hash) => {
                let mut state = serializer.serialize_map(Some(1))?;
                state.serialize_entry(key, hash)?;
                state.end()
            }
            Branch(ref branch) => branch.serialize(serializer),
        }
    }
}
impl<V: Serialize> Serialize for BranchProofNode<V> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use self::BranchProofNode::*;
        let mut state = serializer.serialize_map(Some(2))?;
        match *self {
            BranchKeyNotFound {
                left_hash: ref lhash,
                right_hash: ref rhash,
                left_key: ref lkey,
                right_key: ref rkey,
            } => {
                state.serialize_entry(lkey, lhash)?;
                state.serialize_entry(rkey, rhash)?;
            }
            LeftBranch {
                left_node: ref proof,
                right_hash: ref rhash,
                left_key: ref lkey,
                right_key: ref rkey,
            } => {
                state.serialize_entry(lkey, proof)?;
                state.serialize_entry(rkey, rhash)?;
            }
            RightBranch {
                left_hash: ref lhash,
                right_node: ref proof,
                left_key: ref lkey,
                right_key: ref rkey,
            } => {
                state.serialize_entry(lkey, lhash)?;
                state.serialize_entry(rkey, proof)?;
            }
        }
        state.end()
    }
}
impl<V: Serialize> Serialize for ProofNode<V> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use self::ProofNode::*;
        match *self {
            Leaf(ref value) => {
                #[derive(Serialize)]
                struct SerializeHelper<'a, V: Serialize + 'a> {
                    val: &'a V,
                }
                let helper = SerializeHelper { val: value };
                helper.serialize(serializer)
            }
            Branch(ref branch) => branch.serialize(serializer),
        }
    }
}

impl<V: fmt::Debug + StorageValue> MapProof<V> {
    /// Verifies the correctness of the proof by the trusted root hash and the requested key.
    ///
    /// If the proof is valid and the requested key exists, `Ok(Some(&V))` is returned.
    /// If the proof is valid and the requested key does not exists, `Ok(None)` is returned.
    /// If the proof is invalid, `Err` is returned.
    pub fn validate<K: ProofMapKey>(&self, key: &K, root_hash: Hash) -> Result<Option<&V>, Error> {
        let searched_key = ProofPath::new(key);
        use self::MapProof::*;

        // if we inspect the topmost level of a proof
        let res: Option<&V> = match *self {
            Empty => None,
            LeafRootInclusive(ref root_path, ref val) => {
                let root_key = root_path;
                if root_key != &searched_key {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched key: \
                         {:?}. Proof: {:?}. ",
                        searched_key,
                        self
                    )));
                }
                Some(val)
            }
            LeafRootExclusive(ref root_path, _) => {
                let root_key = root_path;
                if root_key == &searched_key {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched key: \
                         {:?}. Proof: {:?} ",
                        searched_key,
                        self
                    )));
                }
                None
            }
            Branch(ref branch) => branch.validate(&searched_key)?,
        };
        let proof_hash = self.root_hash();
        if proof_hash != root_hash {
            return Err(Error::new(format!(
                "The proof doesn't match the expected hash! \
                 Expected: {:?} , from proof: {:?}",
                root_hash,
                proof_hash
            )));
        }
        Ok(res)
    }
}

impl<V: fmt::Debug> BranchProofNode<V> {
    fn validate(&self, searched_key: &ProofPath) -> Result<Option<&V>, Error> {
        use self::BranchProofNode::*;

        // if we inspect the topmost level of a proof
        let res: Option<&V> = match *self {
            LeftBranch {
                left_node: ref proof,
                left_key: ref left_path_key,
                ..
            } => {
                let left_path = left_path_key;
                if !searched_key.starts_with(left_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched_key: \
                         {:?}. Proof: {:?}",
                        searched_key,
                        self
                    )));
                }
                proof.validate_consistency(left_path, searched_key)?
            }
            RightBranch {
                right_node: ref proof,
                right_key: ref right_path_key,
                ..
            } => {
                let right_path = right_path_key;
                if !searched_key.starts_with(right_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched_key: \
                         {:?}. Proof: {:?}",
                        searched_key,
                        self
                    )));
                }
                proof.validate_consistency(right_path, searched_key)?
            }
            BranchKeyNotFound {
                left_key: ref left_path_key,
                right_key: ref right_path_key,
                ..
            } => {
                let left_path = left_path_key;
                let right_path = right_path_key;
                if searched_key.starts_with(left_path) || searched_key.starts_with(right_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched_key: \
                         {:?}. Proof: {:?}",
                        searched_key,
                        self
                    )));
                }
                None
            }
        };
        Ok(res)
    }

    fn validate_consistency<'a>(
        &'a self,
        parent_path: &ProofPath,
        searched_key: &ProofPath,
    ) -> Result<Option<&'a V>, Error> {
        use self::BranchProofNode::*;

        // if we inspect sub-proofs of a proof
        let res: Option<&V> = match *self {
            LeftBranch {
                left_node: ref proof,
                left_key: ref left_path_key,
                right_key: ref right_path_key,
                ..
            } => {
                let left_path = left_path_key.start_from(0);
                let right_path = right_path_key.start_from(0);
                if !left_path.starts_with(parent_path) || !right_path.starts_with(parent_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with itself: Proof: \
                         {:?} . Parent path: {:?}",
                        self,
                        parent_path
                    )));
                }
                if !searched_key.starts_with(&left_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched_key: \
                         {:?}. Proof: {:?}",
                        searched_key,
                        self
                    )));
                }
                proof.validate_consistency(&left_path, searched_key)?
            }
            RightBranch {
                right_node: ref proof,
                left_key: ref left_path_key,
                right_key: ref right_path_key,
                ..
            } => {
                let left_path = left_path_key.start_from(0);
                let right_path = right_path_key.start_from(0);
                if !left_path.starts_with(parent_path) || !right_path.starts_with(parent_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with itself: Proof: \
                         {:?} . Parent path: {:?}",
                        self,
                        parent_path
                    )));
                }
                if !searched_key.starts_with(&right_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched_key: \
                         {:?}. Proof: {:?}",
                        searched_key,
                        self
                    )));
                }
                proof.validate_consistency(&right_path, searched_key)?
            }
            BranchKeyNotFound {
                left_key: ref left_path_key,
                right_key: ref right_path_key,
                ..
            } => {
                let left_path = left_path_key.start_from(0);
                let right_path = right_path_key.start_from(0);
                if !left_path.starts_with(parent_path) || !right_path.starts_with(parent_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with itself: Proof: \
                         {:?} . Parent path: {:?}",
                        self,
                        parent_path
                    )));
                }
                if searched_key.starts_with(&left_path) || searched_key.starts_with(&right_path) {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched_key: \
                         {:?}. Proof: {:?}",
                        searched_key,
                        self
                    )));
                }
                None
            }
        };
        Ok(res)
    }
}
impl<V: fmt::Debug> ProofNode<V> {
    fn validate_consistency<'a>(
        &'a self,
        parent_key: &ProofPath,
        searched_key: &ProofPath,
    ) -> Result<Option<&'a V>, Error> {
        use self::ProofNode::*;

        // if we inspect sub-proofs of a proof
        let res: Option<&V> = match *self {
            Leaf(ref val) => {
                if searched_key != parent_key {
                    return Err(Error::new(format!(
                        "Proof is inconsistent with searched_key: \
                         {:?}. Parent path: {:?} ",
                        searched_key,
                        parent_key
                    )));
                }
                Some(val)
            }
            Branch(ref branch) => branch.validate_consistency(parent_key, searched_key)?,
        };
        Ok(res)
    }
}

impl<V: fmt::Debug> fmt::Debug for MapProof<V> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::MapProof::*;
        match *self {
            LeafRootInclusive(ref db_key, ref val) => {
                write!(f, "{{\"path\":{:?},{:?}}}", db_key, val)
            }
            LeafRootExclusive(ref db_key, ref val_hash) => {
                write!(f, "{{\"path\":{:?},\"val_hash\":{:?}}}", db_key, val_hash)
            }
            Empty => write!(f, "{{}}"),
            Branch(ref branch) => write!(f, "{:?}", branch),
        }
    }
}
impl<V: fmt::Debug> fmt::Debug for ProofNode<V> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::ProofNode::*;
        match *self {
            Branch(ref branch) => write!(f, "{:?}", branch),
            Leaf(ref val) => write!(f, "{{\"val\":{:?}}}", val),
        }
    }
}

impl<V: fmt::Debug> fmt::Debug for BranchProofNode<V> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::BranchProofNode::*;
        match *self {
            LeftBranch {
                ref left_node,
                ref right_hash,
                ref left_key,
                ref right_key,
            } => {
                write!(
                    f,
                    "{{\"left\":{:?},\"right\":{:?},\"left_path\":{:?},\"right_path\":{:?}}}",
                    left_node,
                    right_hash,
                    left_key,
                    right_key
                )
            }
            RightBranch {
                ref left_hash,
                ref right_node,
                ref left_key,
                ref right_key,
            } => {
                write!(
                    f,
                    "{{\"left\":{:?},\"right\":{:?},\"left_path\":{:?},\"right_path\":{:?}}}",
                    left_hash,
                    right_node,
                    left_key,
                    right_key
                )
            }
            BranchKeyNotFound {
                ref left_hash,
                ref right_hash,
                ref left_key,
                ref right_key,
            } => {
                write!(
                    f,
                    "{{\"left\":{:?},\"right\":{:?},\"left_path\":{:?},\"right_path\":{:?}}}",
                    left_hash,
                    right_hash,
                    left_key,
                    right_key
                )
            }
        }
    }
}