indy-vdr 0.3.0

A library for interacting with Hyperledger Indy Node, a distributed ledger for self-sovereign identity (https://www.hyperledger.org/use/hyperledger-indy).
Documentation
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
use std::collections::HashMap;

use rlp::{DecoderError as RlpDecoderError, Prototype as RlpPrototype, RlpStream, UntrustedRlp};
use ursa::hash::sha3;

use crate::common::error::prelude::*;

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum Node {
    Leaf(Leaf),
    Extension(Extension),
    Full(FullNode),
    Hash(Vec<u8>),
    Blank,
}

impl Node {
    const RADIX: usize = 16;
    const FULL_SIZE: usize = Node::RADIX + 1;
    const PAIR_SIZE: usize = 2;
    const HASH_SIZE: usize = 32;
    const EMPTY_SIZE: usize = 0;
    const IS_LEAF_MASK: u8 = 0x20;
    const IS_PATH_ODD_MASK: u8 = 0x10;
}

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct FullNode {
    nodes: [Option<Box<Node>>; Node::RADIX],
    value: Option<Vec<u8>>,
}

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct Leaf {
    path: Vec<u8>,
    value: Vec<u8>,
}

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct Extension {
    path: Vec<u8>,
    next: Box<Node>,
}

impl rlp::Encodable for Node {
    fn rlp_append(&self, s: &mut RlpStream) {
        match *self {
            Node::Hash(ref hash) => {
                s.append_internal(&hash.as_slice());
            }
            Node::Leaf(ref pair) => {
                s.begin_list(Node::PAIR_SIZE);
                s.append(&pair.path);
                s.append(&pair.value);
            }
            Node::Extension(ref ext) => {
                s.begin_list(Node::PAIR_SIZE);
                s.append(&ext.path);
                s.append(ext.next.as_ref());
            }
            Node::Full(ref node) => {
                s.begin_list(Node::FULL_SIZE);
                for node in &node.nodes {
                    if let Some(ref node) = *node {
                        s.append(node.as_ref());
                    } else {
                        s.append_empty_data();
                    }
                }
                if let Some(ref value) = node.value {
                    s.append(value);
                } else {
                    s.append_empty_data();
                }
            }
            Node::Blank => {
                s.append_empty_data();
            }
        }
    }
}

impl rlp::Decodable for Node {
    fn decode(rlp: &UntrustedRlp) -> Result<Self, RlpDecoderError> {
        match rlp.prototype()? {
            RlpPrototype::List(Node::PAIR_SIZE) => {
                let path: Vec<u8> = rlp.at(0)?.as_val()?;
                if path[0] & Node::IS_LEAF_MASK == Node::IS_LEAF_MASK {
                    Ok(Node::Leaf(Leaf {
                        path: rlp.at(0)?.as_val()?,
                        value: rlp.at(1)?.as_val()?,
                    }))
                } else if path[0] & Node::IS_LEAF_MASK == 0x00 {
                    Ok(Node::Extension(Extension {
                        path: rlp.at(0)?.as_val()?,
                        next: Box::new(rlp.at(1)?.as_val()?),
                    }))
                } else {
                    debug!(
                        "RLP for path in Patricia Merkle Trie contains incorrect flags byte {}",
                        path[0]
                    );
                    Err(RlpDecoderError::Custom(
                        "Path contains incorrect flags byte",
                    ))
                }
            }
            RlpPrototype::List(Node::FULL_SIZE) => {
                let mut nodes: [Option<Box<Node>>; Node::RADIX] = [
                    None, None, None, None, None, None, None, None, None, None, None, None, None,
                    None, None, None,
                ];
                for i in 0..Node::RADIX {
                    let cur = rlp.at(i)?;
                    match cur.prototype()? {
                        RlpPrototype::Data(0) => continue,
                        _ => {
                            nodes[i] = Some(Box::new(cur.as_val()?));
                        }
                    }
                }
                let value: Option<Vec<u8>> = if !rlp.at(Node::RADIX)?.is_empty() {
                    Some(rlp.at(Node::RADIX)?.as_val()?)
                } else {
                    None
                };
                Ok(Node::Full(FullNode { nodes, value }))
            }
            RlpPrototype::Data(Node::HASH_SIZE) => Ok(Node::Hash(rlp.as_val()?)),
            RlpPrototype::Data(Node::EMPTY_SIZE) => Ok(Node::Blank),
            _ => {
                debug!(
                    "Unexpected data while parsing Patricia Merkle Trie: {:?}: {:?}",
                    rlp.prototype(),
                    rlp
                );
                Err(RlpDecoderError::Custom("Unexpected data"))
            }
        }
    }
}

type NodeHash = sha3::digest::generic_array::GenericArray<
    u8,
    <sha3::Sha3_256 as sha3::digest::FixedOutput>::OutputSize,
>;
pub type TrieDB<'a> = HashMap<NodeHash, &'a Node>;

impl Node {
    pub fn get_hash(&self) -> NodeHash {
        use rlp::encode as rlp_encode;
        use sha3::digest::FixedOutput;
        use sha3::Digest;
        let encoded = rlp_encode(self);
        let mut hasher = sha3::Sha3_256::default();
        hasher.input(encoded.to_vec().as_slice());
        hasher.fixed_result()
    }
    pub fn get_str_value<'a, 'b>(
        &'a self,
        db: &'a TrieDB,
        path: &'b [u8],
    ) -> VdrResult<Option<String>> {
        let value = self.get_value(db, path)?;
        if let Some(vec) = value {
            let str = String::from_utf8(vec)
                .with_input_err("Patricia Merkle Trie contains malformed utf8 string")?;

            trace!("Str value from Patricia Merkle Trie {}", str);
            Ok(Some(str))
        } else {
            Ok(None)
        }
    }

    pub fn get_all_values<'a>(
        &'a self,
        db: &'a TrieDB,
        prefix: Option<&[u8]>,
    ) -> VdrResult<Vec<(String, String)>> {
        let node_and_prefix = prefix
            .map(|prf| self.get_node(db, &prf))
            .unwrap_or_else(|| Ok(Some((self, vec![]))))?;
        if let Some((node, prf)) = node_and_prefix {
            let vals = node._get_all_values(db, prf)?;
            let mut res: Vec<(String, String)> = Vec::with_capacity(vals.len());
            for (key, val) in vals {
                res.push((Node::_nibbles_to_str(&key)?, val))
            }
            Ok(res)
        } else {
            Ok(vec![])
        }
    }

    pub fn get_node<'a, 'b>(
        &'a self,
        db: &'a TrieDB,
        path: &'b [u8],
    ) -> VdrResult<Option<(&Node, Vec<u8>)>> {
        trace!("Node::get_node >> path: {:?}", path);
        let nibble_path = Node::path_to_nibbles(path);
        trace!(
            "Node::get_node >> made some nibbles >> nibbles: {:?}",
            nibble_path
        );
        self._get_node(db, nibble_path.as_slice(), vec![].as_slice())
    }

    fn _get_node<'a, 'b>(
        &'a self,
        db: &'a TrieDB,
        path: &'b [u8],
        seen_path: &'b [u8],
    ) -> VdrResult<Option<(&Node, Vec<u8>)>> {
        trace!(
            "Getting node for prefix, cur node: {:?}, prefix: {:?}",
            self,
            path
        );
        match *self {
            Node::Full(ref node) => {
                if path.is_empty() {
                    return Ok(Some((self, seen_path.to_vec())));
                }
                if let Some(ref next) = node.nodes[path[0] as usize] {
                    let mut new_seen_path = Vec::with_capacity(seen_path.len() + path[..1].len());
                    new_seen_path.extend_from_slice(seen_path);
                    new_seen_path.extend_from_slice(&path[..1]);
                    return next._get_node(db, &path[1..], new_seen_path.as_slice());
                }
                Ok(None)
            }
            Node::Hash(ref hash) => {
                let hash = NodeHash::from_slice(hash.as_slice());
                if let Some(ref next) = db.get(hash) {
                    next._get_node(db, path, seen_path)
                } else {
                    Err(input_err(
                        "Incomplete key-value DB for Patricia Merkle Trie to get value by the key",
                    ))
                }
            }
            Node::Leaf(ref pair) => {
                let (is_leaf, pair_path) = Node::parse_path(pair.path.as_slice());

                if !is_leaf {
                    return Err(input_err("Incorrect Patricia Merkle Trie: node marked as leaf but path contains extension flag"));
                }

                trace!(
                    "Node::_get_value in Leaf searched path {:?}, stored path {:?}",
                    String::from_utf8(path.to_vec()),
                    String::from_utf8(pair_path.clone())
                );

                if pair_path.starts_with(&path) {
                    Ok(Some((self, seen_path.to_vec())))
                } else {
                    Ok(None)
                }
            }
            Node::Extension(ref pair) => {
                let (is_leaf, pair_path) = Node::parse_path(pair.path.as_slice());

                if is_leaf {
                    return Err(input_err("Incorrect Patricia Merkle Trie: node marked as extension but path contains leaf flag"));
                }

                trace!("current extension node path: {:?}", pair_path);

                if path.starts_with(&pair_path) {
                    let mut new_seen_path = Vec::with_capacity(seen_path.len() + pair_path.len());
                    new_seen_path.extend_from_slice(seen_path);
                    new_seen_path.extend_from_slice(pair_path.as_slice());
                    pair.next
                        ._get_node(db, &path[pair_path.len()..], new_seen_path.as_slice())
                } else if pair_path.starts_with(&path) {
                    Ok(Some((self, seen_path.to_vec())))
                } else {
                    Ok(None)
                }
            }
            Node::Blank => Ok(None),
        }
    }

    fn _get_all_values<'a>(
        &'a self,
        db: &'a TrieDB,
        prefix: Vec<u8>,
    ) -> VdrResult<Vec<(Vec<u8>, String)>> {
        trace!("Getting all values, cur node: {:?}", self);
        match *self {
            Node::Full(ref node) => {
                let mut res = vec![];
                for nibble in 0..16 {
                    let next = &node.nodes[nibble];
                    if let Some(next) = next {
                        trace!("Checking nibble {}", nibble);
                        let mut prefix_nibble = prefix.clone();
                        prefix_nibble.push(nibble as u8);
                        let mut sub_res: Vec<(Vec<u8>, String)> =
                            next._get_all_values(db, prefix_nibble)?;
                        trace!("Got some values: {:?}", sub_res);
                        res.append(&mut sub_res);
                        trace!("Intermediate result: {:?}", res);
                    }
                }
                if let Some(ref value) = node.value.as_ref() {
                    let mut vec: Vec<Vec<u8>> =
                        UntrustedRlp::new(value).as_list().unwrap_or_default(); //default will cause error below

                    if let Some(val) = vec.pop() {
                        if vec.is_empty() {
                            res.push((
                                prefix.clone(),
                                String::from_utf8(val.clone()).with_input_err(
                                    "Patricia Merkle Trie contains malformed utf8 string",
                                )?,
                            ));
                        }
                    }
                }
                Ok(res)
            }
            Node::Hash(ref hash) => {
                trace!("Node::_get_all_values in Hash");
                let hash = NodeHash::from_slice(hash.as_slice());
                if let Some(ref next) = db.get(hash) {
                    trace!("found value in db");
                    next._get_all_values(db, prefix)
                } else {
                    Err(input_err("Incorrect Patricia Merkle Trie: empty hash node when it should not be empty"))
                }
            }
            Node::Leaf(ref pair) => {
                let (is_leaf, pair_path) = Node::parse_path(pair.path.as_slice());

                if !is_leaf {
                    return Err(input_err("Incorrect Patricia Merkle Trie: node marked as leaf but path contains extension flag"));
                }

                trace!(
                    "Node::_get_all_values in Leaf stored path {:?}",
                    String::from_utf8(pair_path.clone())
                );

                let mut vec: Vec<Vec<u8>> = UntrustedRlp::new(pair.value.as_slice())
                    .as_list()
                    .unwrap_or_default(); //default will cause error below

                let mut full_path = prefix.clone();
                let mut path_left = pair_path.clone();
                full_path.append(&mut path_left);

                if let Some(val) = vec.pop() {
                    if vec.is_empty() {
                        return Ok(vec![(
                            full_path,
                            String::from_utf8(val.clone()).with_input_err(
                                "Patricia Merkle Trie contains malformed utf8 string",
                            )?,
                        )]);
                    }
                }
                Err(input_err(
                    "Unexpected data format of value in Patricia Merkle Trie",
                ))
            }
            Node::Extension(ref pair) => {
                let (is_leaf, pair_path) = Node::parse_path(pair.path.as_slice());

                if is_leaf {
                    return Err(input_err("Incorrect Patricia Merkle Trie: node marked as extension but path contains leaf flag"));
                }

                let mut full_path = prefix.clone();
                let mut path_left = pair_path.clone();
                full_path.append(&mut path_left);

                let values = pair.next._get_all_values(db, full_path)?;

                Ok(values)
            }
            Node::Blank => Ok(vec![]),
        }
    }

    fn get_value<'a, 'b>(&'a self, db: &'a TrieDB, path: &'b [u8]) -> VdrResult<Option<Vec<u8>>> {
        let nibble_path = Node::path_to_nibbles(path);
        match self._get_value(db, nibble_path.as_slice())? {
            Some(v) => {
                let mut vec: Vec<Vec<u8>> = UntrustedRlp::new(v.as_slice())
                    .as_list()
                    .unwrap_or_default(); //default will cause error below

                if let Some(val) = vec.pop() {
                    if vec.is_empty() {
                        return Ok(Some(val));
                    }
                }

                Err(input_err(
                    "Unexpected data format of value in Patricia Merkle Trie",
                ))
            }
            None => Ok(None),
        }
    }
    fn _get_value<'a, 'b>(
        &'a self,
        db: &'a TrieDB,
        path: &'b [u8],
    ) -> VdrResult<Option<&'a Vec<u8>>> {
        trace!("Check proof, cur node: {:?}", self);
        match self._get_node(db, path, vec![].as_slice())? {
            Some((Node::Full(ref node), _)) => Ok(node.value.as_ref()),
            Some((Node::Hash(_), _)) => Ok(None),
            Some((Node::Leaf(ref pair), _)) => {
                let (is_leaf, _) = Node::parse_path(pair.path.as_slice());

                if !is_leaf {
                    return Err(input_err("Incorrect Patricia Merkle Trie: node marked as leaf but path contains extension flag"));
                }

                Ok(Some(&pair.value))
            }
            Some((Node::Extension(_), _)) => Ok(None),
            Some((Node::Blank, _)) => Ok(None),
            None => Ok(None),
        }
    }

    fn path_to_nibbles(path: &[u8]) -> Vec<u8> {
        let mut nibble_path: Vec<u8> = Vec::with_capacity(2 * path.len());

        for s in path {
            nibble_path.push(s >> 4);
            nibble_path.push(s & 0x0F);
        }

        nibble_path
    }

    fn _nibbles_to_str(nibbles: &[u8]) -> VdrResult<String> {
        trace!("Node::_nibbles_to_str >> nibbles: {:?}", nibbles);
        let mut res: Vec<u8> = Vec::with_capacity(nibbles.len() / 2);
        for x in (0..nibbles.len()).step_by(2) {
            let h: u8 = (nibbles[x] << 4) + nibbles[x + 1];
            res.push(h)
        }
        String::from_utf8(res).with_input_err("Patricia Merkle Trie contains malformed utf8 string")
    }

    fn parse_path(path: &[u8]) -> (bool, Vec<u8>) {
        let is_leaf: bool = path[0] & Node::IS_LEAF_MASK == Node::IS_LEAF_MASK;
        let is_odd: bool = path[0] & Node::IS_PATH_ODD_MASK == Node::IS_PATH_ODD_MASK;
        let mut nibbles: Vec<u8> = Node::path_to_nibbles(&path[1..]); //TODO avoid copy
        if is_odd {
            nibbles.insert(0, path[0] & 0x0F);
        }
        (is_leaf, nibbles)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::base64;

    #[test]
    fn node_deserialize_works_for_emtpy() {
        assert_eq!(
            UntrustedRlp::new(&base64::decode("wYA=").unwrap())
                .as_list::<Node>()
                .unwrap(),
            vec![Node::Blank]
        );
    }

    #[test]
    fn node_serialize_works_for_emtpy() {
        assert_eq!(
            base64::encode(&rlp::encode_list(&vec![Node::Blank])),
            "wYA="
        );
    }
}