forked from dojoengine/origami
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommitment.cairo
64 lines (52 loc) · 1.69 KB
/
commitment.cairo
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
use poseidon::poseidon_hash_span;
#[derive(Copy, Drop, Default, Serde, dojo::Introspect)]
struct Commitment {
hash: felt252
}
/// Errors module.
mod errors {
const COMMITMENT_INVALID_HASH: felt252 = 'Commitment: can not commit zero';
}
trait CommitmentTrait {
fn new() -> Commitment;
fn commit(ref self: Commitment, hash: felt252);
fn reveal<T, impl TSerde: Serde<T>, impl TDrop: Drop<T>>(self: @Commitment, reveal: T) -> bool;
}
impl CommitmentImpl of CommitmentTrait {
fn new() -> Commitment {
Commitment { hash: 0 }
}
fn commit(ref self: Commitment, hash: felt252) {
assert(hash.is_non_zero(), errors::COMMITMENT_INVALID_HASH);
self.hash = hash;
}
fn reveal<T, impl TSerde: Serde<T>, impl TDrop: Drop<T>>(self: @Commitment, reveal: T) -> bool {
let mut serialized = array![];
reveal.serialize(ref serialized);
let hash = poseidon_hash_span(serialized.span());
return hash == *self.hash;
}
}
#[cfg(test)]
mod tests {
// Core imports
use debug::PrintTrait;
use poseidon::poseidon_hash_span;
// Local imports
use super::{Commitment, CommitmentTrait};
#[test]
fn test_security_commit_reveal() {
let mut commitment = CommitmentTrait::new();
let value = array!['ohayo'].span();
let hash = poseidon_hash_span(value);
commitment.commit(hash);
let valid = commitment.reveal('ohayo');
assert(valid, 'invalid reveal for commitment')
}
#[test]
#[should_panic(expected: ('Commitment: can not commit zero',))]
fn test_security_commit_revert_zero() {
let mut commitment = CommitmentTrait::new();
commitment.commit(0);
}
}