Skip to content
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ dyn-clone = "1.0.18"
log = "0.4"
env_logger = "0.11"
lazy_static = "1.5.0"
thiserror = { version = "2.0.12" }
# enabled by features:
plonky2 = { git = "https://github.com/0xPolygonZero/plonky2", optional = true }
serde = "1.0.219"
Expand Down
10 changes: 5 additions & 5 deletions src/backends/plonky2/circuits/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use std::{array, iter};

use anyhow::Result;
use plonky2::{
field::{
extension::Extendable,
Expand All @@ -19,6 +18,7 @@ use plonky2::{
use crate::{
backends::plonky2::{
basetypes::D,
error::BackendResult,
mainpod::{Operation, OperationArg, Statement},
primitives::merkletree::MerkleClaimAndProofTarget,
},
Expand Down Expand Up @@ -74,8 +74,8 @@ impl StatementArgTarget {
pw: &mut PartialWitness<F>,
params: &Params,
arg: &StatementArg,
) -> Result<()> {
pw.set_target_arr(&self.elements, &arg.to_fields(params))
) -> BackendResult<()> {
Ok(pw.set_target_arr(&self.elements, &arg.to_fields(params))?)
}

fn new(first: ValueTarget, second: ValueTarget) -> Self {
Expand Down Expand Up @@ -134,7 +134,7 @@ impl StatementTarget {
pw: &mut PartialWitness<F>,
params: &Params,
st: &Statement,
) -> Result<()> {
) -> BackendResult<()> {
pw.set_target_arr(&self.predicate, &st.predicate().to_fields(params))?;
for (i, arg) in st
.args()
Expand Down Expand Up @@ -173,7 +173,7 @@ impl OperationTarget {
pw: &mut PartialWitness<F>,
params: &Params,
op: &Operation,
) -> Result<()> {
) -> BackendResult<()> {
pw.set_target_arr(&self.op_type, &op.op_type().to_fields(params))?;
for (i, arg) in op
.args()
Expand Down
20 changes: 10 additions & 10 deletions src/backends/plonky2/circuits/mainpod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use anyhow::Result;
use itertools::zip_eq;
use plonky2::{
hash::{hash_types::HashOutTarget, poseidon::PoseidonHash},
Expand All @@ -16,6 +15,7 @@ use crate::{
},
signedpod::{SignedPodVerifyGadget, SignedPodVerifyTarget},
},
error::BackendResult,
mainpod,
primitives::merkletree::{
MerkleClaimAndProof, MerkleClaimAndProofTarget, MerkleProofGadget,
Expand Down Expand Up @@ -44,7 +44,7 @@ impl OperationVerifyGadget {
op: &OperationTarget,
prev_statements: &[StatementTarget],
merkle_claims: &[MerkleClaimTarget],
) -> Result<()> {
) -> BackendResult<()> {
let _true = builder._true();
let _false = builder._false();

Expand Down Expand Up @@ -332,7 +332,7 @@ impl OperationVerifyGadget {
st: &StatementTarget,
op: &OperationTarget,
resolved_op_args: &[StatementTarget],
) -> Result<BoolTarget> {
) -> BackendResult<BoolTarget> {
let op_code_ok = op.has_native_type(builder, NativeOperation::CopyStatement);

let expected_statement = &resolved_op_args[0];
Expand All @@ -347,7 +347,7 @@ struct MainPodVerifyGadget {
}

impl MainPodVerifyGadget {
fn eval(&self, builder: &mut CircuitBuilder<F, D>) -> Result<MainPodVerifyTarget> {
fn eval(&self, builder: &mut CircuitBuilder<F, D>) -> BackendResult<MainPodVerifyTarget> {
let params = &self.params;
// 1. Verify all input signed pods
let mut signed_pods = Vec::new();
Expand Down Expand Up @@ -398,7 +398,7 @@ impl MainPodVerifyGadget {
};
let merkle_proofs: Vec<_> = (0..params.max_merkle_proofs)
.map(|_| mp_gadget.eval(builder))
.collect::<Result<_>>()?;
.collect::<BackendResult<_>>()?;
let merkle_claims: Vec<_> = merkle_proofs
.clone()
.into_iter()
Expand Down Expand Up @@ -476,7 +476,7 @@ impl MainPodVerifyTarget {
&self,
pw: &mut PartialWitness<F>,
input: &MainPodVerifyInput,
) -> Result<()> {
) -> BackendResult<()> {
assert!(input.signed_pods.len() <= self.params.max_input_signed_pods);
for (i, signed_pod) in input.signed_pods.iter().enumerate() {
self.signed_pods[i].set_targets(pw, signed_pod)?;
Expand Down Expand Up @@ -510,7 +510,7 @@ pub struct MainPodVerifyCircuit {
}

impl MainPodVerifyCircuit {
pub fn eval(&self, builder: &mut CircuitBuilder<F, D>) -> Result<MainPodVerifyTarget> {
pub fn eval(&self, builder: &mut CircuitBuilder<F, D>) -> BackendResult<MainPodVerifyTarget> {
let main_pod = MainPodVerifyGadget {
params: self.params.clone(),
}
Expand Down Expand Up @@ -539,7 +539,7 @@ mod tests {
op: mainpod::Operation,
prev_statements: Vec<mainpod::Statement>,
merkle_proofs: Vec<MerkleClaimAndProof>,
) -> Result<()> {
) -> BackendResult<()> {
let params = Params::default();
let mp_gadget = MerkleProofGadget {
max_depth: params.max_depth_mt_gadget,
Expand All @@ -556,7 +556,7 @@ mod tests {
let merkle_proofs_target: Vec<_> = merkle_proofs
.iter()
.map(|_| mp_gadget.eval(&mut builder))
.collect::<Result<_>>()?;
.collect::<BackendResult<_>>()?;
let merkle_claims_target: Vec<_> = merkle_proofs_target
.clone()
.into_iter()
Expand Down Expand Up @@ -595,7 +595,7 @@ mod tests {
}

#[test]
fn test_operation_verify() -> Result<()> {
fn test_operation_verify() -> BackendResult<()> {
let params = Params::default();

// None
Expand Down
10 changes: 5 additions & 5 deletions src/backends/plonky2/circuits/signedpod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::iter;

use anyhow::Result;
use itertools::Itertools;
use plonky2::{
hash::hash_types::{HashOut, HashOutTarget},
Expand All @@ -15,6 +14,7 @@ use crate::{
backends::plonky2::{
basetypes::D,
circuits::common::{CircuitBuilderPod, StatementArgTarget, StatementTarget, ValueTarget},
error::BackendResult,
primitives::{
merkletree::{
MerkleClaimAndProof, MerkleProofExistenceGadget, MerkleProofExistenceTarget,
Expand All @@ -34,7 +34,7 @@ pub struct SignedPodVerifyGadget {
}

impl SignedPodVerifyGadget {
pub fn eval(&self, builder: &mut CircuitBuilder<F, D>) -> Result<SignedPodVerifyTarget> {
pub fn eval(&self, builder: &mut CircuitBuilder<F, D>) -> BackendResult<SignedPodVerifyTarget> {
// 1. Verify id
let id = builder.add_virtual_hash();
let mut mt_proofs = Vec::new();
Expand Down Expand Up @@ -117,7 +117,7 @@ impl SignedPodVerifyTarget {
statements
}

pub fn set_targets(&self, pw: &mut PartialWitness<F>, pod: &SignedPod) -> Result<()> {
pub fn set_targets(&self, pw: &mut PartialWitness<F>, pod: &SignedPod) -> BackendResult<()> {
// set the self.mt_proofs witness with the following order:
// - KEY_TYPE leaf proof
// - KEY_SIGNER leaf proof
Expand All @@ -139,7 +139,7 @@ impl SignedPodVerifyTarget {
)?;
Ok(v)
})
.collect::<Result<Vec<&Value>>>()?[1];
.collect::<BackendResult<Vec<&Value>>>()?[1];

// add the verification of the rest of leaves
let mut curr = 2; // since we already added key_type and key_signer
Expand Down Expand Up @@ -201,7 +201,7 @@ pub mod tests {
};

#[test]
fn test_signed_pod_verify() -> Result<()> {
fn test_signed_pod_verify() -> BackendResult<()> {
let params = Params {
max_signed_pod_values: 6,
..Default::default()
Expand Down
91 changes: 91 additions & 0 deletions src/backends/plonky2/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use std::{backtrace::Backtrace, fmt::Debug};

use crate::middleware::{PodId, PodType, Value};

pub type BackendResult<T, E = BackendError> = core::result::Result<T, E>;

#[derive(thiserror::Error, Debug)]
pub enum InnerError {
#[error("id does not match, expected {0}, found {1}")]
IdNotEqual(PodId, PodId),
#[error("type does not match, expected {0}, found {1}")]
TypeNotEqual(PodType, Value),

// POD related
#[error("invalid POD ID")]
PodIdInvalid,
#[error("verification failed: POD does not have type statement")]
NotTypeStatement,
#[error("repeated ValueOf")]
RepeatedValueOf,
#[error("Statement did not check")]
StatementNotCheck,
#[error("Key not found")]
KeyNotFound,

// Other
#[error("{0}")]
Custom(String),
}

#[derive(thiserror::Error)]
pub enum BackendError {
#[error("Inner: {inner}\n{backtrace}")]
Inner {
inner: Box<InnerError>,
backtrace: Box<Backtrace>,
},
#[error("anyhow::Error: {0}")]
Anyhow(#[from] anyhow::Error),
#[error("Plonky2 proof failed to verify: {0}")]
Plonky2ProofFail(anyhow::Error),
#[error(transparent)]
Tree(#[from] crate::backends::plonky2::primitives::merkletree::error::TreeError),
#[error(transparent)]
Middleware(#[from] crate::middleware::MiddlewareError),
}

impl Debug for BackendError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}

macro_rules! new {
($inner:expr) => {
BackendError::Inner {
inner: Box::new($inner),
backtrace: Box::new(Backtrace::capture()),
}
};
}
use InnerError::*;
impl BackendError {
pub(crate) fn custom(s: String) -> Self {
new!(Custom(s))
}
pub(crate) fn plonky2_proof_fail(e: anyhow::Error) -> Self {
Self::Plonky2ProofFail(e)
}
pub(crate) fn key_not_found() -> Self {
new!(KeyNotFound)
}
pub(crate) fn statement_not_check() -> Self {
new!(StatementNotCheck)
}
pub(crate) fn repeated_value_of() -> Self {
new!(RepeatedValueOf)
}
pub(crate) fn not_type_statement() -> Self {
new!(NotTypeStatement)
}
pub(crate) fn pod_id_invalid() -> Self {
new!(PodIdInvalid)
}
pub(crate) fn id_not_equal(expected: PodId, found: PodId) -> Self {
new!(IdNotEqual(expected, found))
}
pub(crate) fn type_not_equal(expected: PodType, found: Value) -> Self {
new!(TypeNotEqual(expected, found))
}
}
Loading
Loading