moonproof_backend/
remote.rs1use async_trait::async_trait;
2use reqwest::Client;
3use serde::{Deserialize, Serialize};
4
5use crate::{BackendError, BackendHealth, CircuitInfo, ProofOutput, ProverBackend, Result};
6
7#[derive(Debug)]
8pub struct RemoteBackend {
9 client: Client,
10 base_url: String,
11}
12
13#[derive(Serialize)]
14struct ProveRequest<'a> {
15 zkir: &'a str,
16 witness: &'a str,
17}
18
19#[derive(Serialize)]
20struct VerifyRequest<'a> {
21 zkir: &'a str,
22 witness: &'a str,
23 proof: &'a str,
24}
25
26#[derive(Serialize)]
27struct CircuitInfoRequest<'a> {
28 zkir: &'a str,
29}
30
31#[derive(Deserialize)]
32struct VerifyResponse {
33 valid: bool,
34}
35
36#[derive(Deserialize)]
37struct HealthResponse {
38 status: String,
39 #[serde(default)]
40 message: String,
41}
42
43impl RemoteBackend {
44 pub fn new(base_url: String) -> Self {
45 let client = Client::builder()
46 .timeout(std::time::Duration::from_mins(5))
47 .tcp_nodelay(true)
48 .pool_max_idle_per_host(8)
49 .build()
50 .expect("failed to build HTTP client");
51 Self { client, base_url }
52 }
53
54 pub fn base_url(&self) -> &str {
55 &self.base_url
56 }
57
58 fn url(&self, path: &str) -> String {
59 format!("{}{}", self.base_url.trim_end_matches('/'), path)
60 }
61}
62
63#[async_trait]
64impl ProverBackend for RemoteBackend {
65 async fn prove(&self, zkir_json: &str, witness_json: &str) -> Result<ProofOutput> {
66 let resp = self
67 .client
68 .post(self.url("/api/prove"))
69 .json(&ProveRequest {
70 zkir: zkir_json,
71 witness: witness_json,
72 })
73 .send()
74 .await
75 .map_err(|e| BackendError::Network(e.to_string()))?;
76
77 if !resp.status().is_success() {
78 let status = resp.status();
79 let body = resp.text().await.unwrap_or_default();
80 return Err(BackendError::ProvingFailed(format!(
81 "Server returned {status}: {body}"
82 )));
83 }
84
85 resp.json::<ProofOutput>()
86 .await
87 .map_err(|e| BackendError::ProvingFailed(format!("Invalid response: {e}")))
88 }
89
90 async fn verify(&self, zkir_json: &str, witness_json: &str, proof_hex: &str) -> Result<bool> {
91 let resp = self
92 .client
93 .post(self.url("/api/verify"))
94 .json(&VerifyRequest {
95 zkir: zkir_json,
96 witness: witness_json,
97 proof: proof_hex,
98 })
99 .send()
100 .await
101 .map_err(|e| BackendError::Network(e.to_string()))?;
102
103 if !resp.status().is_success() {
104 let status = resp.status();
105 let body = resp.text().await.unwrap_or_default();
106 return Err(BackendError::VerificationFailed(format!(
107 "Server returned {status}: {body}"
108 )));
109 }
110
111 let result: VerifyResponse = resp
112 .json()
113 .await
114 .map_err(|e| BackendError::VerificationFailed(format!("Invalid response: {e}")))?;
115
116 Ok(result.valid)
117 }
118
119 async fn circuit_info(&self, zkir_json: &str) -> Result<CircuitInfo> {
120 let resp = self
121 .client
122 .post(self.url("/api/circuit-info"))
123 .json(&CircuitInfoRequest { zkir: zkir_json })
124 .send()
125 .await
126 .map_err(|e| BackendError::Network(e.to_string()))?;
127
128 if !resp.status().is_success() {
129 let status = resp.status();
130 let body = resp.text().await.unwrap_or_default();
131 return Err(BackendError::InvalidInput(format!(
132 "Server returned {status}: {body}"
133 )));
134 }
135
136 resp.json::<CircuitInfo>()
137 .await
138 .map_err(|e| BackendError::InvalidInput(format!("Invalid response: {e}")))
139 }
140
141 async fn health(&self) -> Result<BackendHealth> {
142 let resp = self
143 .client
144 .get(self.url("/api/health"))
145 .send()
146 .await
147 .map_err(|e| {
148 BackendError::Network(format!("Cannot reach server at {}: {e}", self.base_url))
149 })?;
150
151 if !resp.status().is_success() {
152 return Ok(BackendHealth {
153 healthy: false,
154 name: self.name().to_string(),
155 message: format!("Server returned {}", resp.status()),
156 });
157 }
158
159 match resp.json::<HealthResponse>().await {
160 Ok(h) => Ok(BackendHealth {
161 healthy: h.status == "ok" || h.status == "healthy",
162 name: self.name().to_string(),
163 message: if h.message.is_empty() {
164 h.status
165 } else {
166 h.message
167 },
168 }),
169 Err(_) => Ok(BackendHealth {
170 healthy: true,
171 name: self.name().to_string(),
172 message: "Server reachable".to_string(),
173 }),
174 }
175 }
176
177 fn name(&self) -> &'static str {
178 "remote"
179 }
180}