Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Json RPC #19

Merged
merged 9 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lightclient-circuits/src/committee_update_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ use sync_committee_primitives::consensus_types::BeaconBlockHeader;

#[allow(type_alias_bounds)]
#[derive(Clone, Debug, Default)]
pub struct CommitteeUpdateCircuit<S: Spec, F: Field> {
pub struct CommitteeUpdateCircuit<S: Spec + ?Sized, F: Field> {
ec2 marked this conversation as resolved.
Show resolved Hide resolved
_f: PhantomData<F>,
_spec: PhantomData<S>,
}
Expand Down
2 changes: 1 addition & 1 deletion lightclient-circuits/src/sync_step_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ use ssz_rs::{Merkleized, Node};

#[allow(type_alias_bounds)]
#[derive(Clone, Debug, Default)]
pub struct SyncStepCircuit<S: Spec, F: Field> {
pub struct SyncStepCircuit<S: Spec + ?Sized, F: Field> {
_f: PhantomData<F>,
_spec: PhantomData<S>,
}
Expand Down
4 changes: 2 additions & 2 deletions lightclient-circuits/src/util/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ pub trait PinnableCircuit<F: ff::Field>: CircuitExt<F> {
}
}

pub trait AppCircuit: Sized {
pub trait AppCircuit {
type Pinning: Halo2ConfigPinning;
type Witness: Clone;
type Witness: Clone + Default;
ec2 marked this conversation as resolved.
Show resolved Hide resolved

/// Creates a [`PinnableCircuit`], auto-configuring the circuit if not in production or prover mode.
///
Expand Down
5 changes: 5 additions & 0 deletions prover/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ strum = { version = "=0.25", features = ["derive"] }
cli-batteries = "=0.4"
eyre = "0.6"
anstyle = "=1.0.0"
axum = "0.6"
tokio = { version = "1.32", features = ["macros"] }

jsonrpc-v2 = { version = "0.12", default-features = false, features = ["easy-errors", "macros", "bytes-v10"] }

http = "0.2"

# halo2
halo2curves = { git = "https://github.com/privacy-scaling-explorations/halo2curves", tag = "0.3.1" }
Expand Down
19 changes: 17 additions & 2 deletions prover/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use strum::EnumString;

#[derive(Clone, clap::Parser)]
pub struct Options {
#[command(name = "spectre-prover")]
#[command(about = "Spectre prover", long_about = None)]
pub struct Cli {
#[command(subcommand)]
pub subcommand: Subcommands,
}
#[derive(Clone, clap::Parser)]
#[allow(clippy::large_enum_variant)]
pub enum Subcommands {
Rpc,
Circuit(CircuitOptions),
}

#[derive(Clone, clap::Parser)]
pub struct CircuitOptions {
#[command(subcommand)]
pub proof: Proof,

Expand Down Expand Up @@ -88,7 +103,7 @@ pub enum Out {
Tx,
}

#[derive(Clone, Debug, PartialEq, EnumString)]
#[derive(Clone, Debug, PartialEq, EnumString, Serialize, Deserialize)]
pub enum Spec {
#[strum(serialize = "minimal")]
Minimal,
Expand Down
95 changes: 76 additions & 19 deletions prover/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,41 @@
#![allow(incomplete_features)]
#![feature(associated_type_bounds)]
use std::{
fs::{self, File},
future::Future,
io::Write,
path::Path,
str::FromStr,
sync::Arc,
};

use args::{Args, Options, Out, Proof};
mod rpc;
use args::{Args, Cli, Out, Proof};
use axum::{response::IntoResponse, routing::post, Router};
use cli_batteries::version;
use ethers::prelude::*;
use halo2curves::bn256::{Bn256, Fr, G1Affine};
use http::StatusCode;
use itertools::Itertools;
use jsonrpc_v2::{MapRouter as JsonRpcMapRouter, Server as JsonRpcServer};
use lightclient_circuits::{
committee_update_circuit::CommitteeUpdateCircuit,
sync_step_circuit::SyncStepCircuit,
util::{gen_srs, AppCircuit},
};
use preprocessor::{fetch_rotation_args, fetch_step_args};
use rpc::{gen_evm_proof_rotation_circuit_handler, gen_evm_proof_step_circuit_handler};

use snark_verifier::{
loader::halo2::halo2_ecc::halo2_base::halo2_proofs::{
plonk::VerifyingKey, poly::kzg::commitment::ParamsKZG,
},
system::halo2::Config,
};
use snark_verifier_sdk::{halo2::aggregation::AggregationCircuit, read_instances, Snark};

use std::str::FromStr;
use std::{
fs::{self, File},
future::Future,
io::Write,
net::TcpListener,
path::Path,
sync::Arc,
};
mod args;
use jsonrpc_v2::RequestObject as JsonRpcRequestObject;
pub type JsonRpcServerState = Arc<JsonRpcServer<JsonRpcMapRouter>>;

ethers::contract::abigen!(
SnarkVerifierSol,
Expand All @@ -37,16 +44,41 @@ ethers::contract::abigen!(
]"#,
);

fn main() {
cli_batteries::run(version!(), app);
}
async fn app(options: Cli) -> eyre::Result<()> {
match options.subcommand {
args::Subcommands::Rpc => {
let tcp_listener = TcpListener::bind("0.0.0.0:3000").unwrap();
ec2 marked this conversation as resolved.
Show resolved Hide resolved
let rpc_server = Arc::new(
JsonRpcServer::new()
.with_method(
"genEvmProofAndInstancesStepSyncCircuit",
gen_evm_proof_step_circuit_handler,
)
.with_method(
"genEvmProofAndInstancesRotationCircuit",
gen_evm_proof_rotation_circuit_handler,
)
.finish_unwrapped(),
);
let router = Router::new()
.route("/rpc", post(handler))
.with_state(rpc_server);

async fn app(options: Options) -> eyre::Result<()> {
match options.spec {
args::Spec::Minimal => spec_app::<eth_types::Minimal>(&options.proof).await,
args::Spec::Testnet => spec_app::<eth_types::Testnet>(&options.proof).await,
args::Spec::Mainnet => spec_app::<eth_types::Testnet>(&options.proof).await,
// log::info!("Ready for RPC connections");
let server = axum::Server::from_tcp(tcp_listener)
.unwrap()
.serve(router.into_make_service());
server.await.unwrap();

// info!("Stopped accepting RPC connections");
ec2 marked this conversation as resolved.
Show resolved Hide resolved
}
args::Subcommands::Circuit(op) => match op.spec {
args::Spec::Minimal => spec_app::<eth_types::Minimal>(&op.proof).await.unwrap(),
args::Spec::Testnet => spec_app::<eth_types::Testnet>(&op.proof).await.unwrap(),
args::Spec::Mainnet => spec_app::<eth_types::Testnet>(&op.proof).await.unwrap(),
},
}
Ok(())
}

async fn spec_app<S: eth_types::Spec>(proof: &Proof) -> eyre::Result<()> {
Expand Down Expand Up @@ -241,6 +273,31 @@ async fn generic_circuit_cli<
Ok(())
}

async fn handler(
axum::extract::State(rpc_server): axum::extract::State<JsonRpcServerState>,
axum::Json(rpc_call): axum::Json<JsonRpcRequestObject>,
) -> impl IntoResponse {
let response_headers = [("content-type", "application/json-rpc;charset=utf-8")];
let response = rpc_server.handle(rpc_call).await;

let response_str = serde_json::to_string(&response);
match response_str {
Ok(result) => (StatusCode::OK, response_headers, result),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
response_headers,
err.to_string(),
),
}
}

#[tokio::main]
async fn main() {
cli_batteries::run(version!(), app);

// Ok(())
ec2 marked this conversation as resolved.
Show resolved Hide resolved
}

fn read_snark(
params: &ParamsKZG<Bn256>,
vk: &VerifyingKey<G1Affine>,
Expand Down
Loading
Loading