This repository has been archived by the owner on Oct 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.rs
86 lines (76 loc) · 2.54 KB
/
http.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use anyhow::{bail, Result};
use axum::{http::StatusCode, routing::post, Json, Router};
use ethereum_types::U256;
use paladin::runtime::Runtime;
use proof_gen::{proof_types::GeneratedBlockProof, types::PlonkyProofIntern};
use prover::ProverInput;
use serde::{Deserialize, Serialize};
use serde_json::to_writer;
use tracing::{debug, error, info};
/// The main function for the HTTP mode.
pub(crate) async fn http_main(runtime: Runtime, port: u16, output_dir: PathBuf) -> Result<()> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
debug!("listening on {}", addr);
let runtime = Arc::new(runtime);
let app = Router::new().route(
"/prove",
post({
let runtime = runtime.clone();
move |body| prove(body, runtime, output_dir.clone())
}),
);
Ok(axum::Server::bind(&addr)
.serve(app.into_make_service())
.await?)
}
/// Writes the generated block proof to a file.
///
/// Returns the fully qualified file name.
fn write_to_file(
output_dir: PathBuf,
block_number: U256,
generated_block_proof: &GeneratedBlockProof,
) -> Result<PathBuf> {
let file_name = format!("proof-{}.json", block_number);
let fully_qualified_file_name = output_dir.join(file_name);
let file = std::fs::File::create(fully_qualified_file_name.clone());
match file {
Ok(file) => {
to_writer(file, &generated_block_proof.intern)?;
Ok(fully_qualified_file_name)
}
Err(e) => {
bail!("Error while writing to file: {e:#?}");
}
}
}
#[derive(Serialize, Deserialize, Debug)]
struct HttpProverInput {
prover_input: ProverInput,
previous: Option<PlonkyProofIntern>,
}
async fn prove(
Json(payload): Json<HttpProverInput>,
runtime: Arc<Runtime>,
output_dir: PathBuf,
) -> StatusCode {
debug!("Received payload: {:#?}", payload);
let block_number = payload.prover_input.get_block_number();
match payload.prover_input.prove(&runtime, payload.previous).await {
Ok(b_proof) => match write_to_file(output_dir, block_number, &b_proof) {
Ok(file) => {
info!("Successfully wrote proof to {}", file.display());
StatusCode::OK
}
Err(e) => {
error!("{e}");
StatusCode::INTERNAL_SERVER_ERROR
}
},
Err(e) => {
error!("Error while proving block {block_number}: {e:#?}");
StatusCode::INTERNAL_SERVER_ERROR
}
}
}