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
|
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: &Vec<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[pos..=1]
.iter()
.enumerate()
.all(|(prev_hash, (pred_prev_hash, _))| {
let prev_hash = Self::hash_o_item(&self.data[prev_hash - 1]);
prev_hash == *pred_prev_hash
})
}
pub fn rehash(&mut self, from_hash: &[u8]) {
let pos = self
.data
.iter()
.position(|x| x.0 == *from_hash)
.unwrap();
let prev_hashes: Vec<_> = (pos..self
.data
.len())
.map(|i| Self::hash_o_item(&self.data[i - 1]))
.collect();
self.data[pos..]
.iter_mut()
.enumerate()
.map(|(idx, item)| (item, prev_hashes[idx].clone()))
.for_each(|((pred_prev_hash, _), prev_hash)| {
if prev_hash != *pred_prev_hash {
*pred_prev_hash = prev_hash;
}
});
}
pub fn hash_item(data: (&Vec<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
}
}
|