use std::collections::HashMap;
use std::sync::Arc;
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::transient_crypto::curve::Fr;
use moonproof_ledger::transient_crypto::proofs::{
Proof, ProofPreimage, ProvingKeyMaterial, ProvingProvider,
};
use crate::versioned::{ProofPreimageVersioned, ProofVersioned};
#[derive(Clone)]
pub struct HttpProvingProvider {
base_url: Arc<String>,
client: reqwest::Client,
contract_keys: Arc<HashMap<String, ProvingKeyMaterial>>,
resolver: crate::ContractKeyResolver,
}
impl std::fmt::Debug for HttpProvingProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HttpProvingProvider")
.field("base_url", &self.base_url)
.field("contract_keys_count", &self.contract_keys.len())
.finish_non_exhaustive()
}
}
impl HttpProvingProvider {
pub fn new(base_url: impl Into<String>) -> Self {
let contract_keys = Arc::new(HashMap::new());
Self {
base_url: Arc::new(base_url.into()),
client: build_http_client(),
resolver: crate::ContractKeyResolver::new(Arc::clone(&contract_keys)),
contract_keys,
}
}
#[must_use]
pub fn with_contract_keys(
mut self,
contract_keys: HashMap<String, ProvingKeyMaterial>,
) -> Self {
self.contract_keys = Arc::new(contract_keys);
self.resolver = crate::ContractKeyResolver::new(Arc::clone(&self.contract_keys));
self
}
fn url(&self, path: &str) -> String {
format!("{}{}", self.base_url, path)
}
fn key_ref(&self, key_location: &str) -> Option<&ProvingKeyMaterial> {
self.contract_keys.get(key_location)
}
}
fn build_http_client() -> reqwest::Client {
#[cfg(not(target_arch = "wasm32"))]
{
reqwest::Client::builder()
.tcp_nodelay(true)
.pool_max_idle_per_host(8)
.build()
.unwrap_or_else(|_| reqwest::Client::new())
}
#[cfg(target_arch = "wasm32")]
{
reqwest::Client::new()
}
}
impl ProvingProvider for HttpProvingProvider {
async fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, anyhow::Error> {
let ir = self
.key_ref(&preimage.key_location.0)
.map(|km| moonproof_ledger::transient_crypto::proofs::WrappedIr(km.ir_source.clone()));
let est_cap = ir.as_ref().map_or(2048, |w| w.0.len() + 2048);
let payload: (
ProofPreimageVersioned,
Option<moonproof_ledger::transient_crypto::proofs::WrappedIr>,
) = (ProofPreimageVersioned::V2(Arc::new(preimage.clone())), ir);
let mut body = Vec::with_capacity(est_cap);
tagged_serialize(&payload, &mut body)
.map_err(|e| anyhow::anyhow!("serialize check payload: {e}"))?;
let resp = self
.client
.post(self.url("/check"))
.header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
.body(body)
.send()
.await
.map_err(|e| anyhow::anyhow!("HTTP /check: {e}"))?;
let status = resp.status();
let bytes = resp
.bytes()
.await
.map_err(|e| anyhow::anyhow!("HTTP /check body: {e}"))?;
if !status.is_success() {
anyhow::bail!(
"remote /check returned {status}: {}",
String::from_utf8_lossy(&bytes)
);
}
let pi_skips: Vec<Option<u64>> = tagged_deserialize(&bytes[..])
.map_err(|e| anyhow::anyhow!("deserialize check response: {e}"))?;
pi_skips
.into_iter()
.map(|opt| opt.map(usize::try_from).transpose())
.collect::<Result<_, _>>()
.map_err(|e| anyhow::anyhow!("check response skip does not fit in usize: {e}"))
}
async fn prove(
self,
preimage: &ProofPreimage,
overwrite_binding_input: Option<Fr>,
) -> Result<Proof, anyhow::Error> {
let key_material = self.key_ref(&preimage.key_location.0);
let est_cap = key_material.map_or(2048, |km| {
km.prover_key.len() + km.verifier_key.len() + km.ir_source.len() + 2048
});
let payload: (
ProofPreimageVersioned,
Option<&ProvingKeyMaterial>,
Option<Fr>,
) = (
ProofPreimageVersioned::V2(Arc::new(preimage.clone())),
key_material,
overwrite_binding_input,
);
let mut body = Vec::with_capacity(est_cap);
tagged_serialize(&payload, &mut body)
.map_err(|e| anyhow::anyhow!("serialize prove payload: {e}"))?;
let resp = self
.client
.post(self.url("/prove"))
.header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
.body(body)
.send()
.await
.map_err(|e| anyhow::anyhow!("HTTP /prove: {e}"))?;
let status = resp.status();
let bytes = resp
.bytes()
.await
.map_err(|e| anyhow::anyhow!("HTTP /prove body: {e}"))?;
if !status.is_success() {
anyhow::bail!(
"remote /prove returned {status}: {}",
String::from_utf8_lossy(&bytes)
);
}
let proof_versioned: ProofVersioned = tagged_deserialize(&bytes[..])
.map_err(|e| anyhow::anyhow!("deserialize prove response: {e}"))?;
match proof_versioned {
ProofVersioned::V2(p) => Ok(p),
}
}
#[cfg(not(feature = "ledger8"))]
fn resolver(&self) -> &impl moonproof_ledger::transient_crypto::proofs::Resolver {
&self.resolver
}
fn split(&mut self) -> Self {
self.clone()
}
}