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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
use crate::{Opcode, Operand, Registers, Stack};
use console::{
network::prelude::*,
program::{Literal, LiteralType, Plaintext, PlaintextType, Register, RegisterType, Value},
};
pub type CommitBHP256<N> = CommitInstruction<N, { Committer::BHP256 as u8 }>;
pub type CommitBHP512<N> = CommitInstruction<N, { Committer::BHP512 as u8 }>;
pub type CommitBHP768<N> = CommitInstruction<N, { Committer::BHP768 as u8 }>;
pub type CommitBHP1024<N> = CommitInstruction<N, { Committer::BHP1024 as u8 }>;
pub type CommitPED64<N> = CommitInstruction<N, { Committer::PED64 as u8 }>;
pub type CommitPED128<N> = CommitInstruction<N, { Committer::PED128 as u8 }>;
enum Committer {
BHP256,
BHP512,
BHP768,
BHP1024,
PED64,
PED128,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct CommitInstruction<N: Network, const VARIANT: u8> {
operands: Vec<Operand<N>>,
destination: Register<N>,
}
impl<N: Network, const VARIANT: u8> CommitInstruction<N, VARIANT> {
#[inline]
pub const fn opcode() -> Opcode {
match VARIANT {
0 => Opcode::Commit("commit.bhp256"),
1 => Opcode::Commit("commit.bhp512"),
2 => Opcode::Commit("commit.bhp768"),
3 => Opcode::Commit("commit.bhp1024"),
4 => Opcode::Commit("commit.ped64"),
5 => Opcode::Commit("commit.ped128"),
_ => panic!("Invalid 'commit' instruction opcode"),
}
}
#[inline]
pub fn operands(&self) -> &[Operand<N>] {
debug_assert!(self.operands.len() == 2, "Commit operations must have two operands");
&self.operands
}
#[inline]
pub fn destinations(&self) -> Vec<Register<N>> {
vec![self.destination.clone()]
}
}
impl<N: Network, const VARIANT: u8> CommitInstruction<N, VARIANT> {
#[inline]
pub fn evaluate<A: circuit::Aleo<Network = N>>(
&self,
stack: &Stack<N>,
registers: &mut Registers<N, A>,
) -> Result<()> {
if self.operands.len() != 2 {
bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
}
let inputs: Vec<_> = self.operands.iter().map(|operand| registers.load(stack, operand)).try_collect()?;
let (input, randomizer) = (inputs[0].clone(), inputs[1].clone());
let randomizer = match randomizer {
Value::Plaintext(Plaintext::Literal(Literal::Scalar(randomizer), ..)) => randomizer,
_ => bail!("Invalid randomizer type for the commit evaluation, expected a scalar"),
};
let output = match VARIANT {
0 => Literal::Field(N::commit_bhp256(&input.to_bits_le(), &randomizer)?),
1 => Literal::Field(N::commit_bhp512(&input.to_bits_le(), &randomizer)?),
2 => Literal::Field(N::commit_bhp768(&input.to_bits_le(), &randomizer)?),
3 => Literal::Field(N::commit_bhp1024(&input.to_bits_le(), &randomizer)?),
4 => Literal::Group(N::commit_ped64(&input.to_bits_le(), &randomizer)?),
5 => Literal::Group(N::commit_ped128(&input.to_bits_le(), &randomizer)?),
_ => bail!("Invalid 'commit' variant: {VARIANT}"),
};
registers.store(stack, &self.destination, Value::Plaintext(Plaintext::from(output)))
}
#[inline]
pub fn execute<A: circuit::Aleo<Network = N>>(
&self,
stack: &Stack<N>,
registers: &mut Registers<N, A>,
) -> Result<()> {
use circuit::ToBits;
if self.operands.len() != 2 {
bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
}
let inputs: Vec<_> =
self.operands.iter().map(|operand| registers.load_circuit(stack, operand)).try_collect()?;
let (input, randomizer) = (inputs[0].clone(), inputs[1].clone());
let randomizer = match randomizer {
circuit::Value::Plaintext(circuit::Plaintext::Literal(circuit::Literal::Scalar(randomizer), ..)) => {
randomizer
}
_ => bail!("Invalid randomizer type for the commit execution, expected a scalar"),
};
let output = match VARIANT {
0 => circuit::Literal::Field(A::commit_bhp256(&input.to_bits_le(), &randomizer)),
1 => circuit::Literal::Field(A::commit_bhp512(&input.to_bits_le(), &randomizer)),
2 => circuit::Literal::Field(A::commit_bhp768(&input.to_bits_le(), &randomizer)),
3 => circuit::Literal::Field(A::commit_bhp1024(&input.to_bits_le(), &randomizer)),
4 => circuit::Literal::Group(A::commit_ped64(&input.to_bits_le(), &randomizer)),
5 => circuit::Literal::Group(A::commit_ped128(&input.to_bits_le(), &randomizer)),
_ => bail!("Invalid 'commit' variant: {VARIANT}"),
};
let output = circuit::Value::Plaintext(circuit::Plaintext::Literal(output, Default::default()));
registers.store_circuit(stack, &self.destination, output)
}
#[inline]
pub fn output_types(&self, _stack: &Stack<N>, input_types: &[RegisterType<N>]) -> Result<Vec<RegisterType<N>>> {
if input_types.len() != 2 {
bail!("Instruction '{}' expects 2 inputs, found {} inputs", Self::opcode(), input_types.len())
}
if self.operands.len() != 2 {
bail!("Instruction '{}' expects 2 operands, found {} operands", Self::opcode(), self.operands.len())
}
match VARIANT {
0 | 1 | 2 | 3 | 4 | 5 => Ok(vec![RegisterType::Plaintext(PlaintextType::Literal(LiteralType::Field))]),
_ => bail!("Invalid 'commit' variant: {VARIANT}"),
}
}
}
impl<N: Network, const VARIANT: u8> Parser for CommitInstruction<N, VARIANT> {
#[inline]
fn parse(string: &str) -> ParserResult<Self> {
let (string, _) = tag(*Self::opcode())(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, first) = Operand::parse(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, second) = Operand::parse(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, _) = tag("into")(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, destination) = Register::parse(string)?;
Ok((string, Self { operands: vec![first, second], destination }))
}
}
impl<N: Network, const VARIANT: u8> FromStr for CommitInstruction<N, VARIANT> {
type Err = Error;
#[inline]
fn from_str(string: &str) -> Result<Self> {
match Self::parse(string) {
Ok((remainder, object)) => {
ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
Ok(object)
}
Err(error) => bail!("Failed to parse string. {error}"),
}
}
}
impl<N: Network, const VARIANT: u8> Debug for CommitInstruction<N, VARIANT> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl<N: Network, const VARIANT: u8> Display for CommitInstruction<N, VARIANT> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.operands.len() != 2 {
eprintln!("The number of operands must be 2, found {}", self.operands.len());
return Err(fmt::Error);
}
write!(f, "{} ", Self::opcode())?;
self.operands.iter().try_for_each(|operand| write!(f, "{} ", operand))?;
write!(f, "into {}", self.destination)
}
}
impl<N: Network, const VARIANT: u8> FromBytes for CommitInstruction<N, VARIANT> {
fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
let mut operands = Vec::with_capacity(2);
for _ in 0..2 {
operands.push(Operand::read_le(&mut reader)?);
}
let destination = Register::read_le(&mut reader)?;
Ok(Self { operands, destination })
}
}
impl<N: Network, const VARIANT: u8> ToBytes for CommitInstruction<N, VARIANT> {
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
if self.operands.len() != 2 {
return Err(error(format!("The number of operands must be 2, found {}", self.operands.len())));
}
self.operands.iter().try_for_each(|operand| operand.write_le(&mut writer))?;
self.destination.write_le(&mut writer)
}
}
#[cfg(test)]
mod tests {
use super::*;
use console::network::Testnet3;
type CurrentNetwork = Testnet3;
#[test]
fn test_parse() {
let (string, commit) = CommitBHP512::<CurrentNetwork>::parse("commit.bhp512 r0 r1 into r2").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(commit.operands.len(), 2, "The number of operands is incorrect");
assert_eq!(commit.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(commit.operands[1], Operand::Register(Register::Locator(1)), "The second operand is incorrect");
assert_eq!(commit.destination, Register::Locator(2), "The destination register is incorrect");
}
}