Skip to content

Commit e4c8b9e

Browse files
committed
migrate from anyhow to thiserror (#190). pending polish error msgs
1 parent 17e6c2a commit e4c8b9e

31 files changed

+544
-211
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ dyn-clone = "1.0.18"
1717
log = "0.4"
1818
env_logger = "0.11"
1919
lazy_static = "1.5.0"
20+
thiserror = { version = "2.0.12" }
2021
# enabled by features:
2122
plonky2 = { git = "https://github.com/0xPolygonZero/plonky2", optional = true }
2223
serde = "1.0.219"

src/backends/plonky2/circuits/common.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
33
use std::{array, iter};
44

5-
use anyhow::Result;
65
use plonky2::{
76
field::{
87
extension::Extendable,
@@ -27,6 +26,7 @@ use crate::{
2726
EMPTY_VALUE, F, HASH_SIZE, OPERATION_ARG_F_LEN, OPERATION_AUX_F_LEN, STATEMENT_ARG_F_LEN,
2827
VALUE_SIZE,
2928
},
29+
Result,
3030
};
3131

3232
pub const CODE_SIZE: usize = HASH_SIZE + 2;
@@ -75,7 +75,7 @@ impl StatementArgTarget {
7575
params: &Params,
7676
arg: &StatementArg,
7777
) -> Result<()> {
78-
pw.set_target_arr(&self.elements, &arg.to_fields(params))
78+
Ok(pw.set_target_arr(&self.elements, &arg.to_fields(params))?)
7979
}
8080

8181
fn new(first: ValueTarget, second: ValueTarget) -> Self {

src/backends/plonky2/circuits/mainpod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use anyhow::Result;
21
use itertools::zip_eq;
32
use plonky2::{
43
hash::{hash_types::HashOutTarget, poseidon::PoseidonHash},
@@ -26,6 +25,7 @@ use crate::{
2625
AnchoredKey, NativeOperation, NativePredicate, Params, PodType, Statement, StatementArg,
2726
ToFields, Value, F, KEY_TYPE, SELF, VALUE_SIZE,
2827
},
28+
Result,
2929
};
3030

3131
//

src/backends/plonky2/circuits/signedpod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::iter;
22

3-
use anyhow::Result;
43
use itertools::Itertools;
54
use plonky2::{
65
hash::hash_types::{HashOut, HashOutTarget},
@@ -27,6 +26,7 @@ use crate::{
2726
hash_str, Key, NativePredicate, Params, PodType, Predicate, RawValue, ToFields, Value, F,
2827
KEY_SIGNER, KEY_TYPE, SELF,
2928
},
29+
Result,
3030
};
3131

3232
pub struct SignedPodVerifyGadget {

src/backends/plonky2/mainpod/mod.rs

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ pub mod operation;
22
pub mod statement;
33
use std::any::Any;
44

5-
use anyhow::{anyhow, Result};
65
use itertools::Itertools;
76
pub use operation::*;
87
use plonky2::{
@@ -23,9 +22,11 @@ use crate::{
2322
signedpod::SignedPod,
2423
},
2524
middleware::{
26-
self, AnchoredKey, Hash, MainPodInputs, NativeOperation, NonePod, OperationType, Params,
27-
Pod, PodId, PodProver, PodType, StatementArg, ToFields, F, KEY_TYPE, SELF,
25+
self, error::MiddlewareError, AnchoredKey, Hash, MainPodInputs, NativeOperation, NonePod,
26+
OperationType, Params, Pod, PodId, PodProver, PodType, StatementArg, ToFields, F, KEY_TYPE,
27+
SELF,
2828
},
29+
Error, Result,
2930
};
3031

3132
/// Hash a list of public statements to derive the PodId
@@ -72,11 +73,11 @@ pub(crate) fn extract_merkle_proofs(
7273
})
7374
.collect::<Result<Vec<_>>>()?;
7475
if merkle_proofs.len() > params.max_merkle_proofs {
75-
Err(anyhow!(
76+
Err(Error::Custom(format!(
7677
"The number of required Merkle proofs ({}) exceeds the maximum number ({}).",
7778
merkle_proofs.len(),
7879
params.max_merkle_proofs
79-
))
80+
)))
8081
} else {
8182
fill_pad(
8283
&mut merkle_proofs,
@@ -98,10 +99,10 @@ fn find_op_arg(statements: &[Statement], op_arg: &middleware::Statement) -> Resu
9899
(&middleware::Statement::try_from(s.clone()).ok()? == op_arg).then_some(i)
99100
})
100101
.map(OperationArg::Index)
101-
.ok_or(anyhow!(
102+
.ok_or(Error::Custom(format!(
102103
"Statement corresponding to op arg {} not found",
103104
op_arg
104-
)),
105+
))),
105106
}
106107
}
107108

@@ -122,10 +123,10 @@ fn find_op_aux(
122123
.and_then(|mid_pf: merkletree::MerkleProof| (&mid_pf == pf_arg).then_some(i))
123124
})
124125
.map(OperationAux::MerkleProofIndex)
125-
.ok_or(anyhow!(
126+
.ok_or(Error::Custom(format!(
126127
"Merkle proof corresponding to op arg {} not found",
127128
op_aux
128-
)),
129+
))),
129130
}
130131
}
131132

@@ -384,11 +385,7 @@ impl Pod for MainPod {
384385
// 2. get the id out of the public statements
385386
let id: PodId = PodId(hash_statements(&self.public_statements, &self.params));
386387
if id != self.id {
387-
return Err(anyhow!(
388-
"id does not match, expected {}, computed {}",
389-
self.id,
390-
id
391-
));
388+
return Err(Error::Middleware(MiddlewareError::IdNotEqual(self.id, id)));
392389
}
393390

394391
// 1, 3, 4, 5 verification via the zkSNARK proof
@@ -402,7 +399,7 @@ impl Pod for MainPod {
402399

403400
let data = builder.build::<C>();
404401
data.verify(self.proof.clone())
405-
.map_err(|e| anyhow!("MainPod proof verification failure: {:?}", e))
402+
.map_err(|e| Error::Custom(format!("MainPod proof verification failure: {:?}", e)))
406403
}
407404

408405
fn id(&self) -> PodId {

src/backends/plonky2/mainpod/operation.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
use std::fmt;
22

3-
use anyhow::{anyhow, Result};
43
use plonky2::field::types::Field;
54

65
// use serde::{Deserialize, Serialize};
76
use crate::{
87
backends::plonky2::{mainpod::Statement, primitives::merkletree::MerkleClaimAndProof},
98
middleware::{self, OperationType, Params, ToFields, F},
9+
Error, Result,
1010
};
1111

1212
#[derive(Clone, Debug, PartialEq)]
@@ -78,7 +78,7 @@ impl Operation {
7878
OperationAux::MerkleProofIndex(i) => merkle_proofs
7979
.get(i)
8080
.cloned()
81-
.ok_or(anyhow!("Missing Merkle proof index {}", i))
81+
.ok_or(Error::Custom(format!("Missing Merkle proof index {}", i)))
8282
.and_then(|mp| {
8383
mp.try_into()
8484
.map(crate::middleware::OperationAux::MerkleProof)

src/backends/plonky2/mainpod/statement.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
use std::fmt;
22

3-
use anyhow::{anyhow, Result};
4-
53
// use serde::{Deserialize, Serialize};
6-
use crate::middleware::{
7-
self, NativePredicate, Params, Predicate, StatementArg, ToFields, WildcardValue,
4+
use crate::{
5+
middleware::{self, NativePredicate, Params, Predicate, StatementArg, ToFields, WildcardValue},
6+
Error, Result,
87
};
98

109
#[derive(Clone, Debug, PartialEq)]
@@ -36,7 +35,7 @@ impl ToFields for Statement {
3635
}
3736

3837
impl TryFrom<Statement> for middleware::Statement {
39-
type Error = anyhow::Error;
38+
type Error = Error;
4039
fn try_from(s: Statement) -> Result<Self> {
4140
type S = middleware::Statement;
4241
type NP = NativePredicate;
@@ -78,7 +77,10 @@ impl TryFrom<Statement> for middleware::Statement {
7877
(NP::MaxOf, (Some(SA::Key(ak1)), Some(SA::Key(ak2)), Some(SA::Key(ak3))), 3) => {
7978
S::MaxOf(ak1, ak2, ak3)
8079
}
81-
_ => Err(anyhow!("Ill-formed statement expression {:?}", s))?,
80+
_ => Err(Error::Custom(format!(
81+
"Ill-formed statement expression {:?}",
82+
s
83+
)))?,
8284
},
8385
Predicate::Custom(cpr) => {
8486
let vs: Vec<WildcardValue> = proper_args

src/backends/plonky2/mock/mainpod.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
use std::{any::Any, fmt};
66

7-
use anyhow::{anyhow, Result};
7+
// use base64::prelude::*;
88

99
// use base64::prelude::*;
1010
// use serde::{Deserialize, Serialize};
@@ -21,6 +21,7 @@ use crate::{
2121
self, hash_str, AnchoredKey, MainPodInputs, NativePredicate, Params, Pod, PodId, PodProver,
2222
Predicate, StatementArg, KEY_TYPE, SELF,
2323
},
24+
Error, Result,
2425
};
2526

2627
pub struct MockProver {}
@@ -168,9 +169,9 @@ impl MockMainPod {
168169

169170
// pub fn deserialize(serialized: String) -> Result<Self> {
170171
// let proof = String::from_utf8(BASE64_STANDARD.decode(&serialized)?)
171-
// .map_err(|e| anyhow::anyhow!("Invalid base64 encoding: {}", e))?;
172+
// .map_err(|e| Error::Custom(format!("Invalid base64 encoding: {}", e)))?;
172173
// let pod: MockMainPod = serde_json::from_str(&proof)
173-
// .map_err(|e| anyhow::anyhow!("Failed to parse proof: {}", e))?;
174+
// .map_err(|e| Error::Custom(format!("Failed to parse proof: {}", e)))?;
174175

175176
// Ok(pod)
176177
// }
@@ -245,18 +246,16 @@ impl Pod for MockMainPod {
245246
.collect::<Result<Vec<_>>>()
246247
.unwrap();
247248
if !ids_match {
248-
return Err(anyhow!("Verification failed: POD ID is incorrect."));
249+
return Err(Error::PodIdInvalid);
249250
}
250251
if !has_type_statement {
251-
return Err(anyhow!(
252-
"Verification failed: POD does not have type statement."
253-
));
252+
return Err(Error::NotTypeStatement);
254253
}
255254
if !value_ofs_unique {
256-
return Err(anyhow!("Verification failed: Repeated ValueOf"));
255+
return Err(Error::RepeatedValueOf);
257256
}
258257
if !statement_check.iter().all(|b| *b) {
259-
return Err(anyhow!("Verification failed: Statement did not check."));
258+
return Err(Error::StatementNotCheck);
260259
}
261260
Ok(())
262261
}

0 commit comments

Comments
 (0)