Skip to content

Commit

Permalink
pex makes zkps now and its fast
Browse files Browse the repository at this point in the history
  • Loading branch information
ludns committed Nov 10, 2024
1 parent cdc2562 commit e488fae
Show file tree
Hide file tree
Showing 7 changed files with 159 additions and 59 deletions.
39 changes: 39 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pex/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ futures = "0.3.31"
postcard = "1.0.10"
serde = "1.0.214"
rand = "0.8.5"
indicatif = "0.17.8"
21 changes: 19 additions & 2 deletions pex/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use plonky2::{
use pod2::{
pod::{
entry::Entry,
gadget::GadgetID,
gadget::{plonky_pod::ProverParams, GadgetID, PlonkyButNotPlonkyGadget},
origin::Origin,
payload::HashablePayload,
statement::{AnchoredKey, StatementRef},
Expand Down Expand Up @@ -214,6 +214,7 @@ pub struct Env {
bindings: Arc<Mutex<HashMap<String, Value>>>,
sk: Option<SchnorrSecretKey>,
script_id: Option<ScriptId>,
prover_params: Option<Arc<Mutex<ProverParams<M, N, NS, VL>>>>,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -741,7 +742,12 @@ impl PodBuilder {
.iter()
.map(|(_, ops)| ops.clone())
.collect::<Vec<OpCmd>>()[..];
POD::execute_plonky_gadget::<M, N, NS, VL>(&gpg_input, pending_ops)
if let Some(prover_params) = &env.prover_params {
let mut params = prover_params.lock().unwrap();
POD::execute_plonky_gadget::<M, N, NS, VL>(&mut params, &gpg_input, pending_ops)
} else {
POD::execute_oracle_gadget(&gpg_input, pending_ops)
}
}
}
}
Expand All @@ -753,6 +759,7 @@ impl Env {
pod_store: Arc<Mutex<MyPods>>,
sk: Option<SchnorrSecretKey>,
script_id: Option<ScriptId>,
prover_params: Option<Arc<Mutex<ProverParams<M, N, NS, VL>>>>,
) -> Self {
Self {
user,
Expand All @@ -763,6 +770,7 @@ impl Env {
bindings: Arc::new(Mutex::new(HashMap::new())),
sk,
script_id,
prover_params,
}
}

Expand All @@ -777,6 +785,7 @@ impl Env {
bindings: Arc::new(Mutex::new(self.bindings.lock().unwrap().clone())),
sk: self.sk.clone(),
script_id: self.script_id.clone(),
prover_params: self.prover_params.clone(),
}
}

Expand Down Expand Up @@ -1845,6 +1854,7 @@ mod tests {
pod_store.clone(),
Some(SchnorrSecretKey { sk: 42 }),
None,
None,
);
(env, pod_store)
}
Expand Down Expand Up @@ -2708,6 +2718,7 @@ mod tests {
Arc::new(Mutex::new(MyPods::default())),
Some(SchnorrSecretKey { sk: 42 }),
None,
None,
);

// Create Bob's environment
Expand All @@ -2717,6 +2728,7 @@ mod tests {
Arc::new(Mutex::new(MyPods::default())),
Some(SchnorrSecretKey { sk: 43 }),
None,
None,
);

// Alice creates a value
Expand All @@ -2740,6 +2752,7 @@ mod tests {
alice_pod_store.clone(),
Some(SchnorrSecretKey { sk: 42 }),
None,
None,
);

let bob_env = Env::new(
Expand All @@ -2748,6 +2761,7 @@ mod tests {
bob_pod_store.clone(),
Some(SchnorrSecretKey { sk: 43 }),
None,
None,
);

// First, Alice creates her initial pod
Expand Down Expand Up @@ -2795,6 +2809,7 @@ mod tests {
Arc::new(Mutex::new(MyPods::default())),
Some(SchnorrSecretKey { sk: 42 }),
None,
None,
);

// Try to get a value from Bob that doesn't exist
Expand All @@ -2820,6 +2835,7 @@ mod tests {
alice_pod_store.clone(),
Some(SchnorrSecretKey { sk: 42 }),
None,
None,
);

let bob_env = Env::new(
Expand All @@ -2828,6 +2844,7 @@ mod tests {
bob_pod_store.clone(),
Some(SchnorrSecretKey { sk: 43 }),
None,
None,
);

// Alice creates a complex pod
Expand Down
141 changes: 90 additions & 51 deletions pex/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::sync::{Arc, Mutex};

use colored::*;
use constants::*;
use eyre::{eyre, Result};
use indicatif::{ProgressBar, ProgressStyle};
use pex::{
repl::{
display::print_pod_details,
Expand All @@ -10,14 +12,31 @@ use pex::{
store::iroh::IrohStore,
};
use pex::{Env, MyPods, Value};
use pod2::signature::schnorr::{SchnorrSecretKey, SchnorrSigner};
use pod2::{
pod::gadget::PlonkyButNotPlonkyGadget,
signature::schnorr::{SchnorrSecretKey, SchnorrSigner},
};
use reedline::{
default_emacs_keybindings, ColumnarMenu, DefaultPrompt, DefaultPromptSegment, Emacs, KeyCode,
KeyModifiers, MenuBuilder, Reedline, ReedlineEvent, ReedlineMenu, Signal,
};
use std::time::Instant;

use rand::Rng;

fn create_spinner(msg: &str) -> ProgressBar {
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::default_spinner()
.tick_chars("⣾⣽⣻⢿⡿⣟⣯⣷")
.template("{spinner:.green} {msg}")
.unwrap(),
);
pb.set_message(msg.to_string());
pb.enable_steady_tick(std::time::Duration::from_millis(100));
pb
}

fn get_username_from_key(sk: &SchnorrSecretKey) -> String {
let cosmic_prefixes = [
"stellar",
Expand Down Expand Up @@ -86,6 +105,7 @@ async fn main() -> Result<()> {
let shared = Arc::new(IrohStore::new(secret_key));
let task_bound_shared = shared.clone();
let (sync_tx, sync_rx) = tokio::sync::oneshot::channel();
let spinner = create_spinner("Synchronizing REPL with peers...");
let init_task = tokio::task::spawn(async move { task_bound_shared.initialize(sync_tx).await });
tokio::select! {
init_result = init_task => {
Expand All @@ -96,19 +116,32 @@ async fn main() -> Result<()> {
}
sync_result = sync_rx => {
match sync_result {
Ok(()) => println!("Store successfully reached sync state"),
Err(err) => {println!("Failed to receive sync signal"); println!("{:?}", err);},
Ok(()) => {
spinner.finish_and_clear();
println!("🛰️ REPL Synchronized with other peers");
},
Err(err) => {
println!("Failed to receive sync signal");
println!("{:?}", err);
},
}
}
}

let pod_store = Arc::new(Mutex::new(MyPods::default()));
let spinner = create_spinner("Generating prover parameters...");
let circuit_data = PlonkyButNotPlonkyGadget::<M, N, NS, VL>::circuit_data().unwrap();
let prover_params =
PlonkyButNotPlonkyGadget::<M, N, NS, VL>::build_prover_params(circuit_data).unwrap();
spinner.finish_and_clear();
println!("⚙️ Prover parameters generated");
let env = Env::new(
username.clone(),
shared.clone(),
pod_store.clone(),
Some(schnorr_key),
None,
Some(Arc::new(Mutex::new(prover_params))),
);

let commands = vec![
Expand Down Expand Up @@ -185,59 +218,65 @@ async fn main() -> Result<()> {
continue;
}
"" => continue,
_ => match pex::eval(input, env.clone()).await {
Ok(result) => match result {
Value::PodRef(pod) => {
if !input.contains(&username) {
println!("\n{}", "Created new POD:".green());
_ => {
let spinner = create_spinner("Generating ZKP...");
let result = pex::eval(input, env.clone()).await;
spinner.finish_and_clear();

match result {
Ok(result) => match result {
Value::PodRef(pod) => {
if !input.contains(&username) {
println!("\n{}", "Created new POD:".green());
let store = env.pod_store.lock().unwrap();
print_pod_details(&pod, &store);
drop(store);
env.pod_store.lock().unwrap().add_pod(pod);
} else {
println!("\n{}", "Participated in POD creation".green());
};
}
value if input.trim().starts_with("[pod?") => {
println!("\n{}", "Matching POD:".green());
let store = env.pod_store.lock().unwrap();
print_pod_details(&pod, &store);
drop(store);
env.pod_store.lock().unwrap().add_pod(pod);
} else {
println!("\n{}", "Participated in POD creation".green());
};
}
value if input.trim().starts_with("[pod?") => {
println!("\n{}", "Matching POD:".green());
let store = env.pod_store.lock().unwrap();

// Function to extract statement refs
let get_statement_refs = |val: &Value| -> Vec<String> {
match val {
Value::SRef(sref) => vec![sref.1.clone()],
Value::List(values) => values
.iter()
.filter_map(|v| {
if let Value::SRef(sref) = v {
Some(sref.1.clone())
} else {
None
}
})
.collect(),
_ => vec![],
}
};
// Function to extract statement refs
let get_statement_refs = |val: &Value| -> Vec<String> {
match val {
Value::SRef(sref) => vec![sref.1.clone()],
Value::List(values) => values
.iter()
.filter_map(|v| {
if let Value::SRef(sref) = v {
Some(sref.1.clone())
} else {
None
}
})
.collect(),
_ => vec![],
}
};

let statement_refs = get_statement_refs(&value);
let statement_refs = get_statement_refs(&value);

// Find matching pod
if let Some(pod) = store.pods.iter().find(|pod| {
statement_refs.iter().any(|ref_str| {
pod.payload
.statements_list
.iter()
.any(|(id, _)| id == ref_str)
})
}) {
print_pod_details(pod, &store);
// Find matching pod
if let Some(pod) = store.pods.iter().find(|pod| {
statement_refs.iter().any(|ref_str| {
pod.payload
.statements_list
.iter()
.any(|(id, _)| id == ref_str)
})
}) {
print_pod_details(pod, &store);
}
}
}
_ => println!("=> {:?}", result),
},
Err(e) => println!("{}: {}", "Error".red().bold(), e),
},
_ => println!("=> {:?}", result),
},
Err(e) => println!("{}: {}", "Error".red().bold(), e),
}
}
}
}
Ok(Signal::CtrlC) => {
Expand Down
Loading

0 comments on commit e488fae

Please sign in to comment.