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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Copyright (c) 2019-2025 Provable Inc.
// This file is part of the snarkVM library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![forbid(unsafe_code)]
#![allow(clippy::too_many_arguments)]
// #![warn(clippy::cast_possible_truncation)]
// TODO (howardwu): Update the return type on `execute` after stabilizing the interface.
#![allow(clippy::type_complexity)]
mod cost;
pub use cost::*;
mod stack;
pub use stack::*;
mod trace;
pub use trace::*;
mod traits;
pub use traits::*;
mod authorize;
mod deploy;
mod evaluate;
mod execute;
mod finalize;
mod verify_deployment;
mod verify_execution;
mod verify_fee;
#[cfg(test)]
mod tests;
use algorithms::snark::varuna::VarunaVersion;
use console::{
account::PrivateKey,
network::prelude::*,
program::{Identifier, Literal, Locator, Plaintext, ProgramID, Record, Response, Value, compute_function_id},
types::{Field, U16, U64},
};
use ledger_block::{Deployment, Execution, Fee, Input, Output, Transaction, Transition};
use ledger_store::{FinalizeStorage, FinalizeStore, atomic_batch_scope};
use synthesizer_program::{
Branch,
Closure,
Command,
FinalizeGlobalState,
FinalizeOperation,
Instruction,
Program,
RegistersLoad,
RegistersStore,
StackKeys,
StackProgram,
};
use synthesizer_snark::{ProvingKey, UniversalSRS, VerifyingKey};
use aleo_std::prelude::{finish, lap, timer};
use indexmap::IndexMap;
#[cfg(feature = "locktick")]
use locktick::parking_lot::RwLock;
#[cfg(not(feature = "locktick"))]
use parking_lot::RwLock;
use std::{collections::HashMap, sync::Arc};
#[cfg(feature = "aleo-cli")]
use colored::Colorize;
#[derive(Clone)]
pub struct Process<N: Network> {
/// The universal SRS.
universal_srs: UniversalSRS<N>,
/// The mapping of program IDs to stacks.
stacks: Arc<RwLock<IndexMap<ProgramID<N>, Arc<Stack<N>>>>>,
/// The mapping of program IDs to old stacks.
old_stacks: Arc<RwLock<IndexMap<ProgramID<N>, Option<Arc<Stack<N>>>>>>,
}
impl<N: Network> Process<N> {
/// Initializes a new process.
#[inline]
pub fn setup<A: circuit::Aleo<Network = N>, R: Rng + CryptoRng>(rng: &mut R) -> Result<Self> {
let timer = timer!("Process:setup");
// Initialize the process.
let mut process =
Self { universal_srs: UniversalSRS::load()?, stacks: Default::default(), old_stacks: Default::default() };
lap!(timer, "Initialize process");
// Initialize the 'credits.aleo' program.
let program = Program::credits()?;
lap!(timer, "Load credits program");
// Compute the 'credits.aleo' program stack.
let stack = Stack::new(&process, &program)?;
lap!(timer, "Initialize stack");
// Synthesize the 'credits.aleo' circuit keys.
for function_name in program.functions().keys() {
stack.synthesize_key::<A, _>(function_name, rng)?;
lap!(timer, "Synthesize circuit keys for {function_name}");
}
lap!(timer, "Synthesize credits program keys");
// Add the 'credits.aleo' stack to the process.
process.add_stack(stack);
finish!(timer);
// Return the process.
Ok(process)
}
/// Adds a new program to the process.
/// If the program exists, then the existing program is replaced and discarded.
/// If you intend to `execute` the program, use `deploy` and `finalize_deployment` instead.
#[inline]
pub fn add_program(&mut self, program: &Program<N>) -> Result<Option<Arc<Stack<N>>>> {
// Initialize the 'credits.aleo' program ID.
let credits_program_id = ProgramID::<N>::from_str("credits.aleo")?;
// If the program is not 'credits.aleo', compute the program stack, and add it to the process.
if program.id() != &credits_program_id {
return Ok(self.add_stack(Stack::new(self, program)?));
}
Ok(None)
}
/// Adds a new stack to the process.
/// If the program exists, then the existing stack is replaced and discarded
/// If you intend to `execute` the program, use `deploy` and `finalize_deployment` instead.
#[inline]
pub fn add_stack(&mut self, stack: Stack<N>) -> Option<Arc<Stack<N>>> {
// Get the program ID.
let program_id = *stack.program_id();
// Arc the stack first to limit the scope of the write lock.
let stack = Arc::new(stack);
// Insert the stack into the process, replacing the existing stack if it exists.
self.stacks.write().insert(program_id, stack)
}
/// Stages a stack to be added to the process.
/// The new stack is active, while the old stack is retained in `old_stacks`.
/// The `commit_stacks` method must be called to finalize the addition of the new stack.
/// The `revert_stacks` method can be called to revert the staged stacks.
#[inline]
pub fn stage_stack(&self, stack: Stack<N>) {
// Get the program ID.
let program_id = *stack.program_id();
// Arc the stack first to limit the scope of the write lock.
let stack = Arc::new(stack);
// If no entry in `old_stacks` exists for `program_id`, store the old stack.
// Note: If `old_stack` is `None`, it means that we are adding a new program to the process.
let old_stack = self.stacks.write().insert(program_id, stack);
let mut old_stacks = self.old_stacks.write();
if !old_stacks.contains_key(&program_id) {
old_stacks.insert(program_id, old_stack);
}
}
/// Commits the staged stacks to the process.
/// This finalizes the addition of the new stacks and clears the old stacks.
#[inline]
pub fn commit_stacks(&self) {
// Clear the old stacks.
self.old_stacks.write().clear();
}
/// Reverts the staged stacks, restoring the previous state of the process.
/// This will remove the new stacks and restore the old stacks.
#[inline]
pub fn revert_stacks(&self) {
// Restore the old stacks.
for (program_id, stack) in self.old_stacks.write().drain(..) {
// If the stack is `None`, remove the program from the process.
// Otherwise, insert the old stack back into the process.
if let Some(stack) = stack {
self.stacks.write().insert(program_id, stack);
} else {
self.stacks.write().shift_remove(&program_id);
}
}
}
}
impl<N: Network> Process<N> {
/// Initializes a new process.
#[inline]
pub fn load() -> Result<Self> {
let timer = timer!("Process::load");
// Initialize the process.
let mut process =
Self { universal_srs: UniversalSRS::load()?, stacks: Default::default(), old_stacks: Default::default() };
lap!(timer, "Initialize process");
// Initialize the 'credits.aleo' program.
let program = Program::credits()?;
lap!(timer, "Load credits program");
// Compute the 'credits.aleo' program stack.
let stack = Stack::new(&process, &program)?;
lap!(timer, "Initialize stack");
// Synthesize the 'credits.aleo' verifying keys.
for function_name in program.functions().keys() {
// Load the verifying key.
let verifying_key = N::get_credits_verifying_key(function_name.to_string())?;
// Retrieve the number of public and private variables.
// Note: This number does *NOT* include the number of constants. This is safe because
// this program is never deployed, as it is a first-class citizen of the protocol.
let num_variables = verifying_key.circuit_info.num_public_and_private_variables as u64;
// Insert the verifying key.
stack.insert_verifying_key(function_name, VerifyingKey::new(verifying_key.clone(), num_variables))?;
lap!(timer, "Load verifying key for {function_name}");
}
lap!(timer, "Load circuit keys");
// Add the stack to the process.
process.add_stack(stack);
finish!(timer, "Process::load");
// Return the process.
Ok(process)
}
/// Initializes a new process with the V0 credits.aleo verifiying keys.
#[inline]
pub fn load_v0() -> Result<Self> {
let timer = timer!("Process::load_v0");
// Initialize the process.
let mut process =
Self { universal_srs: UniversalSRS::load()?, stacks: Default::default(), old_stacks: Default::default() };
lap!(timer, "Initialize process");
// Initialize the 'credits.aleo' program.
let program = Program::credits()?;
lap!(timer, "Load credits program");
// Compute the 'credits.aleo' program stack.
let stack = Stack::new(&process, &program)?;
lap!(timer, "Initialize stack");
// Synthesize the 'credits.aleo' verifying keys.
for function_name in program.functions().keys() {
// Load the verifying key.
let verifying_key = N::get_credits_v0_verifying_key(function_name.to_string())?;
// Retrieve the number of public and private variables.
// Note: This number does *NOT* include the number of constants. This is safe because
// this program is never deployed, as it is a first-class citizen of the protocol.
let num_variables = verifying_key.circuit_info.num_public_and_private_variables as u64;
// Insert the verifying key.
stack.insert_verifying_key(function_name, VerifyingKey::new(verifying_key.clone(), num_variables))?;
lap!(timer, "Load verifying key for {function_name}");
}
lap!(timer, "Load circuit keys");
// Add the stack to the process.
process.add_stack(stack);
finish!(timer, "Process::load_v0");
// Return the process.
Ok(process)
}
/// Initializes a new process without downloading the 'credits.aleo' circuit keys (for web contexts).
#[inline]
#[cfg(feature = "wasm")]
pub fn load_web() -> Result<Self> {
// Initialize the process.
let mut process =
Self { universal_srs: UniversalSRS::load()?, stacks: Default::default(), old_stacks: Default::default() };
// Initialize the 'credits.aleo' program.
let program = Program::credits()?;
// Compute the 'credits.aleo' program stack.
let stack = Stack::new(&process, &program)?;
// Add the stack to the process.
process.add_stack(stack);
// Return the process.
Ok(process)
}
/// Returns the universal SRS.
#[inline]
pub const fn universal_srs(&self) -> &UniversalSRS<N> {
&self.universal_srs
}
/// Returns `true` if the process contains the program with the given ID.
#[inline]
pub fn contains_program(&self, program_id: &ProgramID<N>) -> bool {
self.stacks.read().contains_key(program_id)
}
/// Returns the stack for the given program ID.
#[inline]
pub fn get_stack(&self, program_id: impl TryInto<ProgramID<N>>) -> Result<Arc<Stack<N>>> {
// Prepare the program ID.
let program_id = program_id.try_into().map_err(|_| anyhow!("Invalid program ID"))?;
// Retrieve the stack.
let stack = self
.stacks
.read()
.get(&program_id)
.ok_or_else(|| anyhow!("Program '{program_id}' does not exist"))?
.clone();
// Ensure the program ID matches.
ensure!(stack.program_id() == &program_id, "Expected program '{}', found '{program_id}'", stack.program_id());
// Return the stack.
Ok(stack)
}
/// Returns the proving key for the given program ID and function name.
#[inline]
pub fn get_proving_key(
&self,
program_id: impl TryInto<ProgramID<N>>,
function_name: impl TryInto<Identifier<N>>,
) -> Result<ProvingKey<N>> {
// Prepare the function name.
let function_name = function_name.try_into().map_err(|_| anyhow!("Invalid function name"))?;
// Return the proving key.
self.get_stack(program_id)?.get_proving_key(&function_name)
}
/// Returns the verifying key for the given program ID and function name.
#[inline]
pub fn get_verifying_key(
&self,
program_id: impl TryInto<ProgramID<N>>,
function_name: impl TryInto<Identifier<N>>,
) -> Result<VerifyingKey<N>> {
// Prepare the function name.
let function_name = function_name.try_into().map_err(|_| anyhow!("Invalid function name"))?;
// Return the verifying key.
self.get_stack(program_id)?.get_verifying_key(&function_name)
}
/// Inserts the given proving key, for the given program ID and function name.
#[inline]
pub fn insert_proving_key(
&self,
program_id: &ProgramID<N>,
function_name: &Identifier<N>,
proving_key: ProvingKey<N>,
) -> Result<()> {
self.get_stack(program_id)?.insert_proving_key(function_name, proving_key)
}
/// Removes the given proving key, for the given program ID and function name.
#[inline]
pub fn remove_proving_key(&self, program_id: &ProgramID<N>, function_name: &Identifier<N>) -> Result<()> {
self.get_stack(program_id)?.remove_proving_key(function_name);
Ok(())
}
/// Inserts the given verifying key, for the given program ID and function name.
#[inline]
pub fn insert_verifying_key(
&self,
program_id: &ProgramID<N>,
function_name: &Identifier<N>,
verifying_key: VerifyingKey<N>,
) -> Result<()> {
self.get_stack(program_id)?.insert_verifying_key(function_name, verifying_key)
}
/// Removes the given verifying key, for the given program ID and function name.
#[inline]
pub fn remove_verifying_key(&self, program_id: &ProgramID<N>, function_name: &Identifier<N>) -> Result<()> {
self.get_stack(program_id)?.remove_verifying_key(function_name);
Ok(())
}
/// Synthesizes the proving and verifying key for the given program ID and function name.
#[inline]
pub fn synthesize_key<A: circuit::Aleo<Network = N>, R: Rng + CryptoRng>(
&self,
program_id: &ProgramID<N>,
function_name: &Identifier<N>,
rng: &mut R,
) -> Result<()> {
// Synthesize the proving and verifying key.
self.get_stack(program_id)?.synthesize_key::<A, R>(function_name, rng)
}
}
#[cfg(test)]
pub mod test_helpers {
use super::*;
use console::{account::PrivateKey, network::MainnetV0, program::Identifier};
use ledger_block::Transition;
use ledger_query::Query;
use ledger_store::{BlockStore, helpers::memory::BlockMemory};
use synthesizer_program::Program;
use aleo_std::StorageMode;
use once_cell::sync::OnceCell;
type CurrentNetwork = MainnetV0;
type CurrentAleo = circuit::network::AleoV0;
/// Returns an execution for the given program and function name.
pub fn get_execution(
process: &mut Process<CurrentNetwork>,
program: &Program<CurrentNetwork>,
function_name: &Identifier<CurrentNetwork>,
inputs: impl ExactSizeIterator<Item = impl TryInto<Value<CurrentNetwork>>>,
) -> Execution<CurrentNetwork> {
// Initialize a new rng.
let rng = &mut TestRng::default();
// Initialize a private key.
let private_key = PrivateKey::new(rng).unwrap();
// Add the program to the process if doesn't yet exist.
if !process.contains_program(program.id()) {
process.add_program(program).unwrap();
}
// Compute the authorization.
let authorization =
process.authorize::<CurrentAleo, _>(&private_key, program.id(), function_name, inputs, rng).unwrap();
// Execute the program.
let (_, mut trace) = process.execute::<CurrentAleo, _>(authorization, rng).unwrap();
// Initialize a new block store.
let block_store = BlockStore::<CurrentNetwork, BlockMemory<_>>::open(StorageMode::new_test(None)).unwrap();
// Prepare the assignments from the block store.
trace.prepare(&ledger_query::Query::from(block_store)).unwrap();
// Get the locator.
let locator = format!("{:?}:{function_name:?}", program.id());
// Return the execution object.
trace.prove_execution::<CurrentAleo, _>(&locator, VarunaVersion::V1, rng).unwrap()
}
pub fn sample_key() -> (Identifier<CurrentNetwork>, ProvingKey<CurrentNetwork>, VerifyingKey<CurrentNetwork>) {
static INSTANCE: OnceCell<(
Identifier<CurrentNetwork>,
ProvingKey<CurrentNetwork>,
VerifyingKey<CurrentNetwork>,
)> = OnceCell::new();
INSTANCE
.get_or_init(|| {
// Initialize a new program.
let (string, program) = Program::<CurrentNetwork>::parse(
r"
program testing.aleo;
function compute:
input r0 as u32.private;
input r1 as u32.public;
add r0 r1 into r2;
output r2 as u32.public;",
)
.unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
// Declare the function name.
let function_name = Identifier::from_str("compute").unwrap();
// Initialize the RNG.
let rng = &mut TestRng::default();
// Construct the process.
let process = sample_process(&program);
// Synthesize a proving and verifying key.
process.synthesize_key::<CurrentAleo, _>(program.id(), &function_name, rng).unwrap();
// Get the proving and verifying key.
let proving_key = process.get_proving_key(program.id(), function_name).unwrap();
let verifying_key = process.get_verifying_key(program.id(), function_name).unwrap();
(function_name, proving_key, verifying_key)
})
.clone()
}
pub(crate) fn sample_execution() -> Execution<CurrentNetwork> {
static INSTANCE: OnceCell<Execution<CurrentNetwork>> = OnceCell::new();
INSTANCE
.get_or_init(|| {
// Initialize a new program.
let (string, program) = Program::<CurrentNetwork>::parse(
r"
program testing.aleo;
function compute:
input r0 as u32.private;
input r1 as u32.public;
add r0 r1 into r2;
output r2 as u32.public;",
)
.unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
// Declare the function name.
let function_name = Identifier::from_str("compute").unwrap();
// Initialize the RNG.
let rng = &mut TestRng::default();
// Initialize a new caller account.
let caller_private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
// Initialize a new block store.
let block_store =
BlockStore::<CurrentNetwork, BlockMemory<_>>::open(StorageMode::new_test(None)).unwrap();
// Construct the process.
let process = sample_process(&program);
// Authorize the function call.
let authorization = process
.authorize::<CurrentAleo, _>(
&caller_private_key,
program.id(),
function_name,
["5u32", "10u32"].into_iter(),
rng,
)
.unwrap();
assert_eq!(authorization.len(), 1);
// Execute the request.
let (_response, mut trace) = process.execute::<CurrentAleo, _>(authorization, rng).unwrap();
assert_eq!(trace.transitions().len(), 1);
// Prepare the trace.
trace.prepare(&Query::from(block_store)).unwrap();
// Compute the execution.
trace.prove_execution::<CurrentAleo, _>("testing", VarunaVersion::V1, rng).unwrap()
})
.clone()
}
pub fn sample_transition() -> Transition<CurrentNetwork> {
// Retrieve the execution.
let mut execution = sample_execution();
// Ensure the execution is not empty.
assert!(!execution.is_empty());
// Return the transition.
execution.pop().unwrap()
}
/// Initializes a new process with the given program.
pub(crate) fn sample_process(program: &Program<CurrentNetwork>) -> Process<CurrentNetwork> {
// Construct a new process.
let mut process = Process::load().unwrap();
// Add the program to the process.
process.add_program(program).unwrap();
// Return the process.
process
}
}