summaryrefslogtreecommitdiff
path: root/src/hash_chain.rs
blob: db3e4e2e04974a14e07e3ab207e6356657a00b05 (plain)
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
use std::ops::Deref;

use bincode::Encode;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct HashChain<T: Encode> {
    data: Vec<(Vec<u8>, T)>, // Vector of (hash, value) pairs
}

impl<T: Encode> Default for HashChain<T> {
    fn default() -> Self {
        Self {
            data: Default::default(),
        }
    }
}

impl<T: Encode> HashChain<T> {
    pub fn new(data: Vec<T>) -> Self {
        let mut this = Self::default();
        for i in data {
            this.push(i);
        }
        this
    }

    pub fn push(&mut self, data: T) {
        let prev_hash = self
            .data
            .last()
            .map(|p| {
                p.0.clone()
            })
            .unwrap_or_default();
        self.data
            .push((Self::hash_item((&prev_hash, &data)), data));
    }

    // TODO: make try_last that does same as this but returns Err() if it's not the
    // last one and/or refuse to insert
    pub fn insert(&mut self, data: T, base_hash: &[u8]) {
        let pos = self
            .data
            .iter()
            .position(|x| x.0 == *base_hash)
            .unwrap();
        self.data
            .insert(pos + 1, (Self::hash_item((base_hash, &data)), data));

        // everything after that hash is invalidated
        self.rehash(&base_hash);
    }

    pub fn verify(&self, until_hash: &[u8]) -> bool {
        let pos = self
            .data
            .iter()
            .position(|x| x.0 == until_hash)
            .unwrap();

        self.data
            .iter()
            .take(pos + 1)
            .try_fold(Vec::<u8>::new(), |prev, (hash, val)| {
                let expected = Self::hash_item((&prev, val));
                if *hash == expected {
                    Ok(expected)
                } else {
                    Err(())
                }
            })
            .is_ok()
    }

    pub fn rehash(&mut self, from_hash: &[u8]) {
        let pos = self
            .data
            .iter()
            .position(|x| x.0 == *from_hash)
            .unwrap();

        let mut prev = self.data[pos]
            .0
            .clone();
        self.data
            .iter_mut()
            .skip(pos + 1)
            .for_each(|(hash, val)| {
                let expected = Self::hash_item((&prev, val));
                if *hash != expected {
                    *hash = expected.clone();
                }
                prev = expected;
            });
    }

    pub fn hash_item(data: (&[u8], &T)) -> Vec<u8> {
        let mut hasher = Sha256::new();
        hasher.update(bincode::encode_to_vec(data, bincode::config::standard()).unwrap());
        hasher
            .finalize()
            .to_vec()
    }

    pub fn hash_o_item(data: &(Vec<u8>, T)) -> Vec<u8> {
        Self::hash_item((&data.0, &data.1))
    }
}

impl<T: Encode> Deref for HashChain<T> {
    type Target = Vec<(Vec<u8>, T)>;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}