1use rand::thread_rng;
5use sha3::{Digest, Sha3_256};
6
7use crate::{
8 algebra::{
9 scalar::{Scalar, ScalarResult},
10 stark_curve::{StarkPoint, StarkPointResult},
11 },
12 fabric::ResultValue,
13};
14
15pub(crate) struct PedersenCommitment {
19 pub(crate) value: Scalar,
21 pub(crate) blinder: Scalar,
23 pub(crate) commitment: StarkPoint,
25}
26
27impl PedersenCommitment {
28 pub(crate) fn verify(&self) -> bool {
30 let generator = StarkPoint::generator();
31 let commitment = generator * self.value + generator * self.blinder;
32
33 commitment == self.commitment
34 }
35}
36
37pub(crate) struct PedersenCommitmentResult {
39 pub(crate) value: ScalarResult,
41 pub(crate) blinder: Scalar,
43 pub(crate) commitment: StarkPointResult,
45}
46
47impl PedersenCommitmentResult {
48 pub(crate) fn commit(value: ScalarResult) -> PedersenCommitmentResult {
50 let mut rng = thread_rng();
53 let blinder = Scalar::random(&mut rng);
54 let generator = StarkPoint::generator();
55 let commitment = generator * &value + generator * blinder;
56
57 PedersenCommitmentResult {
58 value,
59 blinder,
60 commitment,
61 }
62 }
63}
64
65pub(crate) struct HashCommitment {
73 pub(crate) value: StarkPoint,
75 pub(crate) blinder: Scalar,
77 pub(crate) commitment: Scalar,
79}
80
81impl HashCommitment {
82 pub(crate) fn verify(&self) -> bool {
84 let mut bytes = self.value.to_bytes();
86 bytes.append(&mut self.blinder.to_bytes_be());
87
88 let mut hasher = Sha3_256::new();
90 hasher.update(bytes);
91
92 let out_bytes = hasher.finalize();
93 let out = Scalar::from_be_bytes_mod_order(out_bytes.as_slice());
94
95 out == self.commitment
96 }
97}
98
99pub(crate) struct HashCommitmentResult {
101 pub(crate) value: StarkPointResult,
103 pub(crate) blinder: Scalar,
105 pub(crate) commitment: ScalarResult,
107}
108
109impl HashCommitmentResult {
110 pub(crate) fn commit(value: StarkPointResult) -> HashCommitmentResult {
112 let mut rng = thread_rng();
113 let blinder = Scalar::random(&mut rng);
114 let comm = value.fabric.new_gate_op(vec![value.id], move |mut args| {
115 let value: StarkPoint = args.remove(0).into();
116
117 let mut bytes = value.to_bytes();
119 bytes.append(&mut blinder.to_bytes_be());
120
121 let mut hasher = Sha3_256::new();
123 hasher.update(bytes);
124
125 let out_bytes = hasher.finalize();
126 let out = Scalar::from_be_bytes_mod_order(out_bytes.as_slice());
127
128 ResultValue::Scalar(out)
129 });
130
131 HashCommitmentResult {
132 value,
133 blinder,
134 commitment: comm,
135 }
136 }
137}