use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::{BackendError, BackendHealth, CircuitInfo, ProofOutput, ProverBackend, Result};
#[derive(Debug)]
pub struct RemoteBackend {
client: Client,
base_url: String,
}
#[derive(Serialize)]
struct ProveRequest<'a> {
zkir: &'a str,
witness: &'a str,
}
#[derive(Serialize)]
struct VerifyRequest<'a> {
zkir: &'a str,
witness: &'a str,
proof: &'a str,
}
#[derive(Serialize)]
struct CircuitInfoRequest<'a> {
zkir: &'a str,
}
#[derive(Deserialize)]
struct VerifyResponse {
valid: bool,
}
#[derive(Deserialize)]
struct HealthResponse {
status: String,
#[serde(default)]
message: String,
}
impl RemoteBackend {
pub fn new(base_url: String) -> Self {
let client = Client::builder()
.timeout(std::time::Duration::from_mins(5))
.tcp_nodelay(true)
.pool_max_idle_per_host(8)
.build()
.expect("failed to build HTTP client");
Self { client, base_url }
}
pub fn base_url(&self) -> &str {
&self.base_url
}
fn url(&self, path: &str) -> String {
format!("{}{}", self.base_url.trim_end_matches('/'), path)
}
}
#[async_trait]
impl ProverBackend for RemoteBackend {
async fn prove(&self, zkir_json: &str, witness_json: &str) -> Result<ProofOutput> {
let resp = self
.client
.post(self.url("/api/prove"))
.json(&ProveRequest {
zkir: zkir_json,
witness: witness_json,
})
.send()
.await
.map_err(|e| BackendError::Network(e.to_string()))?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(BackendError::ProvingFailed(format!(
"Server returned {status}: {body}"
)));
}
resp.json::<ProofOutput>()
.await
.map_err(|e| BackendError::ProvingFailed(format!("Invalid response: {e}")))
}
async fn verify(&self, zkir_json: &str, witness_json: &str, proof_hex: &str) -> Result<bool> {
let resp = self
.client
.post(self.url("/api/verify"))
.json(&VerifyRequest {
zkir: zkir_json,
witness: witness_json,
proof: proof_hex,
})
.send()
.await
.map_err(|e| BackendError::Network(e.to_string()))?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(BackendError::VerificationFailed(format!(
"Server returned {status}: {body}"
)));
}
let result: VerifyResponse = resp
.json()
.await
.map_err(|e| BackendError::VerificationFailed(format!("Invalid response: {e}")))?;
Ok(result.valid)
}
async fn circuit_info(&self, zkir_json: &str) -> Result<CircuitInfo> {
let resp = self
.client
.post(self.url("/api/circuit-info"))
.json(&CircuitInfoRequest { zkir: zkir_json })
.send()
.await
.map_err(|e| BackendError::Network(e.to_string()))?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(BackendError::InvalidInput(format!(
"Server returned {status}: {body}"
)));
}
resp.json::<CircuitInfo>()
.await
.map_err(|e| BackendError::InvalidInput(format!("Invalid response: {e}")))
}
async fn health(&self) -> Result<BackendHealth> {
let resp = self
.client
.get(self.url("/api/health"))
.send()
.await
.map_err(|e| {
BackendError::Network(format!("Cannot reach server at {}: {e}", self.base_url))
})?;
if !resp.status().is_success() {
return Ok(BackendHealth {
healthy: false,
name: self.name().to_string(),
message: format!("Server returned {}", resp.status()),
});
}
match resp.json::<HealthResponse>().await {
Ok(h) => Ok(BackendHealth {
healthy: h.status == "ok" || h.status == "healthy",
name: self.name().to_string(),
message: if h.message.is_empty() {
h.status
} else {
h.message
},
}),
Err(_) => Ok(BackendHealth {
healthy: true,
name: self.name().to_string(),
message: "Server reachable".to_string(),
}),
}
}
fn name(&self) -> &'static str {
"remote"
}
}