libblockchain/chain.rs
1// The MIT License (MIT)
2//
3// Copyright (c) 2017 Doublify Technologies
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21// THE SOFTWARE.
22
23//! A `Chain` implementation.
24
25use std::hash::Hash;
26
27use block::Block;
28
29/// A `Chain` representation.
30#[derive(Debug)]
31pub struct Chain<T: Clone + Hash> {
32 inner: Vec<Block<T>>,
33}
34
35impl<T: Clone + Hash> Chain<T> {
36 /// Creates a new `Chain`.
37 pub fn new(inner: Vec<Block<T>>) -> Chain<T> {
38 Chain { inner }
39 }
40
41 /// Appends a block to the `Chain`.
42 ///
43 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
44 ///
45 /// # Examples
46 ///
47 /// ```rust
48 /// use libblockchain::{Block, Chain};
49 ///
50 /// let mut chain = Chain::new(vec![]);
51 ///
52 /// let block0 = Block::new(0, vec![0; 256], 0);
53 ///
54 /// let resp = chain.push(block0);
55 ///
56 /// assert_eq!(resp.is_some(), true)
57 /// ```
58 pub fn push(&mut self, v: Block<T>) -> Option<()> {
59 Some(self.inner.push(v))
60 }
61
62 /// Returns `true` if the given `Chain` is trusty.
63 pub fn is_trusty_chain(&self) -> bool {
64 let mut iter = self.inner.clone().into_iter();
65
66 while let Some(previous) = iter.next() {
67 if let Some(current) = iter.next() {
68 if !current.is_trusty_for(&previous) {
69 return false;
70 }
71 }
72 }
73
74 true
75 }
76}