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
use sha2::{Digest, Sha256};
pub trait Commitment {
type Seed;
type Output;
fn new(seed: Self::Seed) -> Self;
fn input(&mut self, input: &[u8]);
fn finish(self) -> Self::Output;
fn check(comm1: &Self::Output, comm2: &Self::Output) -> bool;
}
pub struct ShaCommitment {
pub seed: [u8; 32],
commit: Sha256,
}
impl Commitment for ShaCommitment {
type Seed = [u8; 32];
type Output = [u8; 32];
fn new(seed: Self::Seed) -> Self {
let commit = Sha256::new();
Self { seed, commit }
}
fn input(&mut self, input: &[u8]) {
self.commit.update(input);
}
fn finish(mut self) -> [u8; 32] {
self.commit.update(&self.seed);
let mut a = [0u8; 32];
a.copy_from_slice(&self.commit.finalize());
a
}
fn check(comm1: &Self::Output, comm2: &Self::Output) -> bool {
comm1 == comm2
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::Rng;
#[test]
fn commit_hello_world() {
let mut commit = ShaCommitment::new([0u8; 32]);
commit.input(b"Hello ");
commit.input(b"world!");
let result = commit.finish();
assert_eq!(
hex::encode(result),
"9652d7ad97478403f26e4a9e64eaee024b9c75fe9e699a6a2e3f1b85d40d1c0d"
);
}
#[test]
fn commit_check() {
let seed: _ = rand::thread_rng().gen::<[u8; 32]>();
let mut seed_ = [0u8; 32];
seed_.copy_from_slice(&seed);
let mut commit = ShaCommitment::new(seed);
commit.input(b"hello ");
commit.input(b"world");
let commitment = commit.finish();
let msg = b"hello world";
let mut commit_ = ShaCommitment::new(seed_);
commit_.input(msg);
let commitment_ = commit_.finish();
assert!(ShaCommitment::check(&commitment, &commitment_));
}
}