Skip to content

Commit

Permalink
feat: updated error (#1354)
Browse files Browse the repository at this point in the history
  • Loading branch information
dprats authored Feb 19, 2025
1 parent 5831a38 commit 9a050e6
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 54 deletions.
2 changes: 1 addition & 1 deletion clients/cli/Cargo.lock

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

2 changes: 1 addition & 1 deletion clients/cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "nexus-network"
version = "0.5.2"
version = "0.5.3"
edition = "2021"
rust-version = "1.75"
build = "build.rs"
Expand Down
42 changes: 29 additions & 13 deletions clients/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut proof_count = 1;
loop {
println!("\n================================================");
println!("\nStarting proof #{}...\n", proof_count);
println!(
"{}",
format!("\nStarting proof #{} ...\n", proof_count).yellow()
);
match anonymous_proving() {
Ok(_) => (),
Err(e) => println!("Error in anonymous proving: {}", e),
Expand All @@ -116,17 +119,30 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.bright_cyan()
);
let flops = flops::measure_flops();
println!("Node computational capacity: {:.2} FLOPS", flops);
println!("You are proving with the following node ID: {}", node_id);
let flops_formatted = format!("{:.2}", flops);
let flops_str = format!("{} FLOPS", flops_formatted);
println!(
"{}: {}",
"Computational capacity of this node".bold(),
flops_str.bright_cyan()
);
println!(
"{}: {}",
"You are proving with node ID".bold(),
node_id.bright_cyan()
);

let mut proof_count = 1;
loop {
println!("\n================================================");
println!("\nStarting proof #{}...\n", proof_count);
println!(
"{}",
format!("\nStarting proof #{} ...\n", proof_count).yellow()
);

match authenticated_proving(&node_id, &environment).await {
Ok(_) => (),
Err(e) => println!("Error in authenticated proving: {}", e),
Err(e) => println!("\tError: {}", e),
}
proof_count += 1;
tokio::time::sleep(std::time::Duration::from_secs(4)).await;
Expand All @@ -151,19 +167,20 @@ async fn authenticated_proving(
) -> Result<(), Box<dyn std::error::Error>> {
let client = OrchestratorClient::new(environment.clone());

println!("1. Fetching a task to prove from Nexus Orchestrator...");
let proof_task = client.get_proof_task(node_id).await?;
println!("1. Received proof task from Nexus Orchestrator...");
println!("2. Received a task to prove from Nexus Orchestrator...");

let public_input: u32 = proof_task.public_inputs[0] as u32;

println!("2. Compiling guest program...");
println!("3. Compiling guest program...");
let elf_file_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("assets")
.join("fib_input");
let prover =
Stwo::<Local>::new_from_file(&elf_file_path).expect("failed to load guest program");

println!("3. Creating proof with inputs...");
println!("4. Creating ZK proof with inputs...");
let (view, proof) = prover
.prove_with_input::<(), u32>(&(), &public_input)
.expect("Failed to run prover");
Expand All @@ -175,11 +192,11 @@ async fn authenticated_proving(
let proof_hash = format!("{:x}", Keccak256::digest(&proof_bytes));

println!("\tProof size: {} bytes", proof_bytes.len());
println!("4. Submitting proof...");
println!("5. Submitting ZK proof to Nexus Orchestrator...");
client
.submit_proof(node_id, &proof_hash, proof_bytes)
.await?;
println!("{}", "5. Proof successfully submitted".green());
println!("{}", "6. ZK proof successfully submitted".green());

Ok(())
}
Expand All @@ -199,7 +216,7 @@ fn anonymous_proving() -> Result<(), Box<dyn std::error::Error>> {
Stwo::<Local>::new_from_file(&elf_file_path).expect("failed to load guest program");

//3. Run the prover
println!("2. Creating proof...");
println!("2. Creating ZK proof...");
let (view, proof) = prover
.prove_with_input::<(), u32>(&(), &public_input)
.expect("Failed to run prover");
Expand All @@ -211,11 +228,10 @@ fn anonymous_proving() -> Result<(), Box<dyn std::error::Error>> {
println!(
"{}",
format!(
"3. Proof successfully created with size: {} bytes",
"3. ZK proof successfully created with size: {} bytes",
proof_bytes.len()
)
.green(),
);
println!("{}", "\nProof successfully created".green());
Ok(())
}
85 changes: 48 additions & 37 deletions clients/cli/src/orchestrator_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,56 @@ impl OrchestratorClient {
let request_bytes = request_data.encode_to_vec();
let url = format!("{}{}", self.base_url, url);

let response = match method {
"POST" => {
self.client
.post(&url)
.header("Content-Type", "application/octet-stream")
.body(request_bytes)
.send()
.await?
}
"GET" => self.client.get(&url).send().await?,
_ => return Err("Unsupported method".into()),
let friendly_connection_error =
"[CONNECTION] Unable to reach server. The service might be temporarily unavailable."
.to_string();
let friendly_messages = match method {
"POST" => match self
.client
.post(&url)
.header("Content-Type", "application/octet-stream")
.body(request_bytes)
.send()
.await
{
Ok(resp) => resp,
Err(_) => return Err(friendly_connection_error.into()),
},
"GET" => match self.client.get(&url).send().await {
Ok(resp) => resp,
Err(_) => return Err(friendly_connection_error.into()),
},
_ => return Err("[METHOD] Unsupported HTTP method".into()),
};

if !response.status().is_success() {
return Err(format!(
"Unexpected status {}: {}",
response.status(),
response.text().await?
)
.into());
if !friendly_messages.status().is_success() {
let status = friendly_messages.status();
let error_text = friendly_messages.text().await?;

// Clean up error text by removing HTML
let clean_error = if error_text.contains("<html>") {
format!("HTTP {}", status.as_u16())
} else {
error_text
};

let friendly_message = match status.as_u16() {
400 => "[400] Invalid request".to_string(),
401 => "[401] Authentication failed. Please check your credentials.".to_string(),
403 => "[403] You don't have permission to perform this action.".to_string(),
404 => "[404] The requested resource was not found.".to_string(),
408 => "[408] The server timed out waiting for your request. Please try again.".to_string(),
429 => "[429] Too many requests. Please try again later.".to_string(),
502 => "[502] Unable to reach the server. Please try again later.".to_string(),
504 => "[504] Gateway Timeout: The server took too long to respond. Please try again later.".to_string(),
500..=599 => format!("[{}] A server error occurred. Our team has been notified. Please try again later.", status),
_ => format!("[{}] Unexpected error: {}", status, clean_error),
};

return Err(friendly_message.into());
}

let response_bytes = response.bytes().await?;
let response_bytes = friendly_messages.bytes().await?;
if response_bytes.is_empty() {
return Ok(None);
}
Expand Down Expand Up @@ -105,26 +132,10 @@ impl OrchestratorClient {
}),
};

let url = format!("{}/tasks/submit", self.base_url);
let response = self
.client
.post(&url)
.header("Content-Type", "application/octet-stream")
.body(request.encode_to_vec())
.send()
self.make_request::<SubmitProofRequest, ()>("/tasks/submit", "POST", &request)
.await?;

if !response.status().is_success() {
return Err(format!(
"Unexpected status {}: {}",
response.status(),
response.text().await?
)
.into());
}

let response_text = response.text().await?;
println!("\tNexus Orchestrator response: {}", response_text);
println!("\tNexus Orchestrator: Proof submitted successfully");
Ok(())
}
}
1 change: 0 additions & 1 deletion clients/cli/src/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ pub async fn run_initial_setup() -> SetupResult {
if use_existing_config == "y" {
match fs::read_to_string(&node_id_path) {
Ok(content) => {
println!("\nUsing existing node ID: {}", content.trim());
return SetupResult::Connected(content.trim().to_string());
}
Err(e) => {
Expand Down
2 changes: 1 addition & 1 deletion clients/cli/src/utils/cli_branding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub fn print_banner() {
"{} {} {}\n",
"Welcome to the".bright_white(),
"Nexus Network CLI".bright_cyan().bold(),
"v0.5.2".bright_white()
"v0.5.3".bright_white()
);
println!(
"{}",
Expand Down

0 comments on commit 9a050e6

Please sign in to comment.