dkls23_core/utilities/
commits.rs1use crate::utilities::hashes::{point_to_bytes, tagged_hash, HashOutput};
8use crate::utilities::oracle_tags::TAG_COMMITMENT;
9use crate::utilities::rng;
10use elliptic_curve::CurveArithmetic;
11use rand::RngExt;
12use rustcrypto_group::GroupEncoding;
13use subtle::ConstantTimeEq;
14
15use crate::SECURITY;
17
18#[must_use]
26pub fn commit(msg: &[u8]) -> (HashOutput, Vec<u8>) {
27 let mut salt = [0u8; 2 * SECURITY as usize];
29 rng::get_rng().fill(&mut salt[..]);
30
31 let commitment = tagged_hash(TAG_COMMITMENT, &[&salt, msg]);
32
33 (commitment, salt.to_vec())
34}
35
36#[must_use]
41pub fn verify_commitment(msg: &[u8], commitment: &HashOutput, salt: &[u8]) -> bool {
42 let expected_commitment = tagged_hash(TAG_COMMITMENT, &[salt, msg]);
43 commitment.ct_eq(&expected_commitment).into()
44}
45
46#[must_use]
50pub fn commit_point<C: CurveArithmetic>(point: &C::AffinePoint) -> (HashOutput, Vec<u8>)
51where
52 C::AffinePoint: GroupEncoding,
53{
54 let point_as_bytes = point_to_bytes::<C>(point);
55 commit(&point_as_bytes)
56}
57
58#[must_use]
62pub fn verify_commitment_point<C: CurveArithmetic>(
63 point: &C::AffinePoint,
64 commitment: &HashOutput,
65 salt: &[u8],
66) -> bool
67where
68 C::AffinePoint: GroupEncoding,
69{
70 let point_as_bytes = point_to_bytes::<C>(point);
71 verify_commitment(&point_as_bytes, commitment, salt)
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
80 fn test_commit_decommit() {
81 let msg = rng::get_rng().random::<[u8; 32]>();
82 let (commitment, salt) = commit(&msg);
83 assert!(verify_commitment(&msg, &commitment, &salt));
84 }
85
86 #[test]
89 fn test_commit_decommit_fail_msg() {
90 let msg = rng::get_rng().random::<[u8; 32]>();
91 let (commitment, salt) = commit(&msg);
92 let msg = rng::get_rng().random::<[u8; 32]>(); assert!(!(verify_commitment(&msg, &commitment, &salt))); }
95
96 #[test]
99 fn test_commit_decommit_fail_commitment() {
100 let msg = rng::get_rng().random::<[u8; 32]>();
101 let (_, salt) = commit(&msg);
102 let commitment = rng::get_rng().random::<HashOutput>(); assert!(!(verify_commitment(&msg, &commitment, &salt))); }
105
106 #[test]
109 fn test_commit_decommit_fail_salt() {
110 let msg = rng::get_rng().random::<[u8; 32]>();
111 let (commitment, _) = commit(&msg);
112 let mut salt = [0u8; 2 * SECURITY as usize];
113 rng::get_rng().fill(&mut salt[..]);
114 assert!(!(verify_commitment(&msg, &commitment, &salt))); }
116}