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
//! # BlockGraph
//!
//! `blockgraph` is the module providing the type used to represent a graph of authenticated `Block`s.
//! Nodes are `Blocknode`s and edges the links between them, which are specified in the `Block`s
//! referenced by the graph `BlockNode`s.
//! An authenticated graph allows to represent different authenticated data structures
//! (linked lists, trees, sets, etc), so it is a natural choice to keep the framework generic.

use base::Result;
use base::Checkable;
use base::Datable;
use base::Serializable;
use base::{Sizable, FixedSize};
use base::Evaluable;
use crypto::Hashable;
use models::Meta;
use models::BlockNode;

/// Type representing a graph of `BlockNodes`. It just expose the graph frontier, from which
/// one can span the entire graph after following the `BlockNode`s' `Block`s `prev_block_id` links.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash, Serialize, Deserialize)]
pub struct BlockGraph<D, P>
    where   D: Datable + FixedSize,
            P: Datable
{
    /// BlockGraph id. It is the digest of the same blockgraph, but with a default `D` id.
    pub id: D,
    /// BlockGraph metadata.
    pub meta: Meta,
    /// Blockgraph tip's or frontier's height.
    pub height: u64,
    /// BlockGraph's frontier tip idx, if any.
    pub tip_idx: Option<u64>,
    /// BlockGraph's frontier length.
    pub frontier_len: u64,
    /// BlockGraph's frontier.
    pub frontier: Vec<BlockNode<D>>,
    /// Custom payload.
    pub payload: P,
}

impl<D, P> BlockGraph<D, P>
    where   D: Datable + FixedSize,
            P: Datable
{
    /// Creates a new `BlockGraph`.
    pub fn new() -> BlockGraph<D, P> {
        let mut bg = BlockGraph::default();
        bg.update_size();
        bg
    }

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

        self.meta.set_size(size);
    }

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

        self.update_size();

        Ok(self)
    }

    /// Sets the `BlockGraph`s frontier and its height and lenght.
    pub fn frontier(mut self, tip_idx: Option<u64>, frontier: &Vec<BlockNode<D>>)
        -> Result<BlockGraph<D, P>>
    {
        frontier.check()?;

        let mut height = 0;

        for node in frontier.clone() {
            if node.block_height > height {
                height = node.block_height;
            }
        }

        if let Some(idx) = tip_idx {
            if idx > (frontier.len() -1) as u64 {
                return Err(String::from("invalid tip index"));
            }
        }

        self.height = height;
        self.tip_idx = tip_idx;
        self.frontier_len = frontier.len() as u64;
        self.frontier = frontier.clone();

        self.update_size();

        Ok(self)
    }

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

        self.payload = payload.clone();

        self.update_size();

        Ok(self)
    }

    /// Finalizes the `BlockGraph`, building its id and returning it's complete form.
    pub fn finalize<HP: Datable>(mut self, params: &HP, cb: &Fn(&Self, &HP) -> Result<D>)
        -> Result<BlockGraph<D, P>>
    {
        params.check()?;

        self.update_size();

        self.id = self.digest(params, cb)?;

        self.check()?;

        Ok(self)
    }

    /// Hashes cryptographically the `BlockGraph`.
    pub fn digest<HP: Datable>(&self, params: &HP, cb: &Fn(&Self, &HP) -> Result<D>)
        -> Result<D>
    {
        params.check()?;

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

        bg.digest_cb(params, cb)
    }

    /// Verifies the cryptographic digest against the `BlockGraph`'s digest.
    pub fn verify_digest<HP: Datable>(&self,
                                      params: &HP,
                                      cb: &Fn(&Self, &HP, &D) -> Result<bool>)
        -> Result<bool>
    {
        params.check()?;

        let digest = self.id.clone();
        digest.check()?;

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

        bg.verify_digest_cb(params, &digest, cb)
    }

    /// Checks the cryptographic digest against the `BlockGraph`'s digest.
    pub fn check_digest<HP: Datable>(&self,
                                     params: &HP,
                                     cb: &Fn(&Self, &HP, &D) -> Result<()>)
        -> Result<()>
    {
        params.check()?;

        let digest = self.id.clone();
        digest.check()?;

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

        bg.check_digest_cb(params, &digest, cb)
    }

    /// Evals the `BlockGraph`.
    pub fn eval<EP, R>(&self, params: &EP, cb: &Fn(&Self, &EP) -> Result<R>)
        -> Result<R>
        where   EP: Datable,
                R: Datable
    {
        params.check()?;

        self.eval_cb(params, cb)
    }
}

impl<HP, D, P> Hashable<HP, D> for BlockGraph<D, P>
    where   HP: Datable,
            D: Datable + FixedSize,
            P: Datable
{}

impl<D, P> Sizable for BlockGraph<D, P>
    where   D: Datable + FixedSize,
            P: Datable
{
    fn size(&self) -> u64 {
        self.id.size() +
            self.meta.size() +
            self.height.size() +
            self.tip_idx.size() +
            self.frontier_len.size() +
            self.frontier.size() +
            self.payload.size()
    }
}

impl<D, P> Checkable for BlockGraph<D, P>
    where   D: Datable + FixedSize,
            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.height.check()?;
        self.tip_idx.check()?;
        self.frontier_len.check()?;

        if self.frontier.len() != self.frontier_len as usize {
            return Err(String::from("invalid frontier length"));
        }
        
        for node in self.frontier.clone() {
            node.check()?;
        }

        if let Some(idx) = self.tip_idx {
            if idx > self.frontier_len -1 {
                return Err(String::from("invalid frontier tip idx"));
            }
        }

        self.payload.check()?;

        Ok(())
    }
}

impl<D, P> Serializable for BlockGraph<D, P>
    where   D: Datable + FixedSize + Serializable,
            P: Datable + Serializable
{}

impl<D, P> Datable for BlockGraph<D, P>
    where   D: Datable + FixedSize,
            P: Datable
{}

impl<D, P> Evaluable for BlockGraph<D, P>
    where   D: Datable + FixedSize,
            P: Datable
{}