Skip to content

Commit

Permalink
good
Browse files Browse the repository at this point in the history
  • Loading branch information
mattstam committed Dec 7, 2024
1 parent b28becd commit 7b2b890
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 36 deletions.
31 changes: 23 additions & 8 deletions crates/sdk/src/network-v2/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::network_v2::proto::network::{
CreateProgramResponse, FulfillmentStatus, FulfillmentStrategy, GetNonceRequest,
GetProgramRequest, GetProgramResponse, GetProofRequestStatusRequest,
GetProofRequestStatusResponse, MessageFormat, ProofMode, RequestProofRequest,
RequestProofRequestBody, RequestProofResponse,
RequestProofRequestBody,
};
use crate::network_v2::types::HashType;
use crate::network_v2::types::{RequestId, TransactionHash, VerifyingKeyHash};
Expand Down Expand Up @@ -194,7 +194,10 @@ impl NetworkClient {
.proof_uri
.as_ref()
.ok_or_else(|| anyhow::anyhow!("No proof URI provided"))?;
let proof_bytes = self.download_artifact(proof_uri).await?;
let proof_bytes = self
.download_artifact(proof_uri)
.await
.map_err(|e| Error::ArtifactDownload { message: e.to_string() })?;
Some(bincode::deserialize(&proof_bytes).context("Failed to deserialize proof")?)
}
_ => None,
Expand All @@ -204,6 +207,7 @@ impl NetworkClient {
}

/// Creates a proof request with the given verifying key hash and stdin.
#[allow(clippy::too_many_arguments)]
pub async fn request_proof(
&self,
vk_hash: &VerifyingKeyHash,
Expand All @@ -216,7 +220,9 @@ impl NetworkClient {
) -> Result<(TransactionHash, RequestId)> {
// Calculate the deadline.
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Invalid start time");
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.map_err(|e| Error::Other(anyhow::anyhow!("Invalid system time: {}", e)))?;
let deadline = since_the_epoch.as_secs() + timeout_secs;

// Create the stdin artifact.
Expand Down Expand Up @@ -273,21 +279,30 @@ impl NetworkClient {
self.http.put(&presigned_url).body(bincode::serialize::<T>(item)?).send().await?;

if !response.status().is_success() {
log::debug!("Artifact upload failed with status: {}", response.status());
let status = response.status();
let text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to get error response text: {}", e));
return Err(anyhow::anyhow!("HTTP {}: {}", status, text));
}
assert!(response.status().is_success());

Ok(uri)
}

/// Download an artifact from a URI.
async fn download_artifact(&self, uri: &str) -> Result<Vec<u8>> {
let response = self.http.get(uri).send().await.context("Failed to download from URI")?;
let response = self.http.get(uri).send().await?;

if !response.status().is_success() {
return Err(anyhow::anyhow!("Failed to download artifact: HTTP {}", response.status()));
let status = response.status();
let text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to get error response text: {}", e));
return Err(anyhow::anyhow!("HTTP {}: {}", status, text));
}

Ok(response.bytes().await.context("Failed to read response body")?.to_vec())
Ok(response.bytes().await?.to_vec())
}
}
11 changes: 7 additions & 4 deletions crates/sdk/src/network-v2/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@ pub enum Error {
#[error("Proof request timed out")]
RequestTimedOut,

#[error("Registration failed")]
RegistrationFailed,
#[error("Artifact upload failed: {message}")]
ArtifactUpload { message: String },

#[error("Network error")]
NetworkError(#[from] Status),
#[error("Artifact download failed: {message}")]
ArtifactDownload { message: String },

#[error("RPC error")]
RpcError(#[from] Status),

#[error("Other error: {0}")]
Other(#[from] anyhow::Error),
Expand Down
7 changes: 4 additions & 3 deletions crates/sdk/src/network-v2/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,12 @@ impl NetworkProver {
vk: &SP1VerifyingKey,
elf: &[u8],
) -> Result<VerifyingKeyHash> {
log::info!("Registering program with verifying key hash");
self.client.register_program(vk, elf).await
}

/// Requests a proof from the prover network, returning the request ID.
#[allow(clippy::too_many_arguments)]
pub async fn request_proof(
&self,
vk_hash: &VerifyingKeyHash,
Expand Down Expand Up @@ -290,7 +292,7 @@ impl NetworkProver {
stdin: SP1Stdin,
) -> Result<SP1ProofWithPublicValues, Error> {
// Ensure the program is registered.
let vk_hash = self.register_program(&pk.vk, &pk.elf).await.map_err(Error::Other)?;
let vk_hash = self.register_program(&pk.vk, &pk.elf).await?;

// Get the configured settings.
let version = SP1_CIRCUIT_VERSION;
Expand All @@ -302,8 +304,7 @@ impl NetworkProver {
// Request the proof.
let request_id = self
.request_proof(&vk_hash, &stdin, version, mode, strategy, timeout_secs, cycle_limit)
.await
.map_err(Error::Other)?;
.await?;

// Wait for the proof to be generated.
self.wait_proof(&request_id, timeout_secs).await
Expand Down
4 changes: 2 additions & 2 deletions crates/sdk/src/network-v2/types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::fmt;

const DEFAULT_EXPLORER_URL: &str = "https://network.succinct.xyz";
/// The default URL for the proof network explorer.
pub const DEFAULT_EXPLORER_URL: &str = "https://network.succinct.xyz";

/// A 32-byte hash that uniquely identifies a proof request.
#[derive(Debug, Clone, PartialEq, Eq)]
Expand All @@ -18,7 +19,6 @@ pub struct VerifyingKeyHash(Vec<u8>);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransactionHash(Vec<u8>);

// Common trait for hex formatting and explorer URLs
pub trait HashType: Sized {
fn as_bytes(&self) -> &[u8];
fn new(bytes: Vec<u8>) -> Self;
Expand Down
1 change: 1 addition & 0 deletions examples/Cargo.lock

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

20 changes: 2 additions & 18 deletions examples/fibonacci/script/bin/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ async fn main() {
// Setup logging.
utils::setup_logger();


// Create the prover.
let private_key = env::var("SP1_PRIVATE_KEY").expect("PRIVATE_KEY must be set");
let prover = NetworkProver::new(&private_key, None, false)
Expand All @@ -34,18 +33,11 @@ async fn main() {
let mut stdin = SP1Stdin::new();
stdin.write(&1000u32);

// Send the proof request to the prover network.
let proof_result = prover.prove(&pk, stdin).await;
let mut proof = match proof_result {
Ok(proof) => proof,
Err(e) => match e {
Error::SimulationFailed => {
eprintln!("Failed to simulate program execution. Try setting a manual cycle limit with skip_simulation()");
std::process::exit(1);
}
Error::RequestTimedOut => {
eprintln!("Proof generation timed out. Try increasing the timeout duration");
std::process::exit(1);
}
Error::RequestUnexecutable => {
eprintln!("Program is not executable. Check your input parameters");
std::process::exit(1);
Expand All @@ -54,15 +46,7 @@ async fn main() {
eprintln!("No prover available to fulfill the request. Try again later");
std::process::exit(1);
}
Error::RegistrationFailed => {
eprintln!("Failed to register program with the network");
std::process::exit(1);
}
Error::NetworkError(status) => {
eprintln!("Network communication error: {}", status);
std::process::exit(1);
}
Error::Other(e) => {
_ => {
eprintln!("Unexpected error: {}", e);
std::process::exit(1);
}
Expand Down
4 changes: 3 additions & 1 deletion examples/tendermint/script/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ publish = false

[dependencies]
sp1-sdk = { workspace = true }
serde_json = { workspace = true, default-features = false, features = ["alloc"] }
serde_json = { workspace = true, default-features = false, features = [
"alloc",
] }
tendermint-light-client-verifier = { version = "0.35.0", default-features = false, features = [
"rust-crypto",
] }
Expand Down

0 comments on commit 7b2b890

Please sign in to comment.