AleoNet / snarkVM

A Virtual Machine for Zero-Knowledge Executions
https://snarkvm.org
Apache License 2.0
1.01k stars 1.46k forks source link

[Optimization] Inefficient fetching of `credits.aleo` PKs #2416

Open raychu86 opened 3 months ago

raychu86 commented 3 months ago

It looks like our VM does not fetch the credits.aleo proving keys from the resources folder and simply resynthesizes them from scratch at time of use. This is completely safe, however will incur a one-time synthesis cost.

When we fetch the proving keys functions via Stack::get_proving_key, we check if the function is a credits.aleo function and read the proving key directly from the bytes in .resources if it is. This is done in Stack::execute - https://github.com/AleoHQ/snarkVM/blob/2cbf34a1010bf781277cdc6ff1ae966230cf97c1/synthesizer/process/src/stack/execute.rs#L462

However a few lines above, we are always re-synthesizing the key at first time of use: https://github.com/AleoHQ/snarkVM/blob/2cbf34a1010bf781277cdc6ff1ae966230cf97c1/synthesizer/process/src/stack/execute.rs#L425-L429 This ignores the optimization we have for the PKs where we can simply read from bytes instead of resynthesizing.

Note: The current behavior does NOT impact security, but can be optimized.

ljedrz commented 3 months ago

Would the following tweak suffice?

diff --git a/synthesizer/process/src/stack/execute.rs b/synthesizer/process/src/stack/execute.rs
index 4a2936d91..3c4331c79 100644
--- a/synthesizer/process/src/stack/execute.rs
+++ b/synthesizer/process/src/stack/execute.rs
@@ -421,8 +421,9 @@ impl<N: Network> StackExecute<N> for Stack<N> {
         if matches!(registers.call_stack(), CallStack::Synthesize(..))
             || matches!(registers.call_stack(), CallStack::Execute(..))
         {
-            // If the proving key does not exist, then synthesize it.
-            if !self.contains_proving_key(function.name()) {
+            // If the proving key does not exist, then synthesize it. This is not needed for `credits.aleo`.
+            if self.program_id() != &ProgramID::from_str("credits.aleo")? && !self.contains_proving_key(function.name())
+            {
                 // Add the circuit key to the mapping.
                 self.synthesize_from_assignment(function.name(), &assignment)?;
                 lap!(timer, "Synthesize the {} circuit key", function.name());
raychu86 commented 1 week ago

@ljedrz That should be sufficient. Could you open up a PR with this change so we can test it?