Skip to content

Commit

Permalink
replace Result<T, Box<dyn Error>> with anyhow::Result<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-ferdinand committed Nov 21, 2022
1 parent b9a1597 commit 4b49377
Show file tree
Hide file tree
Showing 11 changed files with 207 additions and 190 deletions.
99 changes: 55 additions & 44 deletions triton-vm/src/bfield_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,11 @@ pub struct BFieldCodecError {
}

impl BFieldCodecError {
pub fn new(message: &str) -> Self {
Self {
#[allow(clippy::new_ret_no_self)]
pub fn new(message: &str) -> anyhow::Error {
anyhow::Error::new(Self {
message: message.to_string(),
}
}

pub fn boxed(message: &str) -> Box<dyn Error> {
Box::new(Self::new(message))
})
}
}

Expand All @@ -43,14 +40,14 @@ impl Error for BFieldCodecError {}
/// length-prepending. It does not record type information; this is
/// the responsibility of the decoder.
pub trait BFieldCodec {
fn decode(string: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>>;
fn decode(string: &[BFieldElement]) -> anyhow::Result<Box<Self>>;
fn encode(&self) -> Vec<BFieldElement>;
}

impl BFieldCodec for BFieldElement {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
if str.len() != 1 {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"trying to decode more or less than one BFieldElements as one BFieldElement",
));
}
Expand All @@ -64,9 +61,9 @@ impl BFieldCodec for BFieldElement {
}

impl BFieldCodec for XFieldElement {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
if str.len() != 3 {
Err(BFieldCodecError::boxed(
Err(BFieldCodecError::new(
"trying to decode slice of not 3 BFieldElements into XFieldElement",
))
} else {
Expand All @@ -82,9 +79,9 @@ impl BFieldCodec for XFieldElement {
}

impl BFieldCodec for Digest {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
if str.len() != DIGEST_LENGTH {
Err(BFieldCodecError::boxed(
Err(BFieldCodecError::new(
"trying to decode slice of not DIGEST_LENGTH BFieldElements into Digest",
))
} else {
Expand All @@ -98,17 +95,17 @@ impl BFieldCodec for Digest {
}

impl<T: BFieldCodec, S: BFieldCodec> BFieldCodec for (T, S) {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
// decode T
let maybe_element_zero = str.get(0);
if matches!(maybe_element_zero, None) {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"trying to decode empty slice as tuple",
));
}
let len_t = maybe_element_zero.unwrap().value() as usize;
if str.len() < 1 + len_t {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"prepended length of tuple element does not match with remaining string length",
));
}
Expand All @@ -117,13 +114,11 @@ impl<T: BFieldCodec, S: BFieldCodec> BFieldCodec for (T, S) {
// decode S
let maybe_next_element = str.get(1 + len_t);
if matches!(maybe_next_element, None) {
return Err(BFieldCodecError::boxed(
"trying to decode singleton as tuple",
));
return Err(BFieldCodecError::new("trying to decode singleton as tuple"));
}
let len_s = maybe_next_element.unwrap().value() as usize;
if str.len() != 1 + len_t + 1 + len_s {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"prepended length of second tuple element does not match with remaining string length",
));
}
Expand All @@ -133,10 +128,10 @@ impl<T: BFieldCodec, S: BFieldCodec> BFieldCodec for (T, S) {
if let Ok(s) = maybe_s {
Ok(Box::new((*t, *s)))
} else {
Err(BFieldCodecError::boxed("could not decode s"))
Err(BFieldCodecError::new("could not decode s"))
}
} else {
Err(BFieldCodecError::boxed("could not decode t"))
Err(BFieldCodecError::new("could not decode t"))
}
}

Expand All @@ -157,9 +152,9 @@ impl<T: BFieldCodec, S: BFieldCodec> BFieldCodec for (T, S) {
}

impl BFieldCodec for PartialAuthenticationPath<Digest> {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
if str.is_empty() {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"cannot decode empty string into PartialAuthenticationPath",
));
}
Expand All @@ -168,7 +163,7 @@ impl BFieldCodec for PartialAuthenticationPath<Digest> {
while index < str.len() {
let len = str[index].value();
if str.len() < index + 1 + len as usize {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"cannot decode vec of optional digests because of improper length prepending",
));
}
Expand All @@ -177,7 +172,7 @@ impl BFieldCodec for PartialAuthenticationPath<Digest> {
if let Ok(optional_digest) = decoded {
vect.push(*optional_digest);
} else {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"cannot decode optional digest in vec",
));
}
Expand All @@ -201,10 +196,10 @@ impl BFieldCodec for PartialAuthenticationPath<Digest> {
}

impl<T: BFieldCodec> BFieldCodec for Option<T> {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
let maybe_element_zero = str.get(0);
if matches!(maybe_element_zero, None) {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"trying to decode empty slice into option of elements",
));
}
Expand Down Expand Up @@ -235,7 +230,7 @@ impl<T: BFieldCodec> BFieldCodec for Option<T> {
}

impl BFieldCodec for Vec<BFieldElement> {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
Ok(Box::new(str.to_vec()))
}

Expand All @@ -245,9 +240,12 @@ impl BFieldCodec for Vec<BFieldElement> {
}

impl BFieldCodec for Vec<XFieldElement> {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
if str.len() % 3 != 0 {
return Err(BFieldCodecError::boxed("cannot decode string of BFieldElements into XFieldElements when string length is not a multiple of 3"));
return Err(BFieldCodecError::new(
"cannot decode string of BFieldElements into XFieldElements \
when string length is not a multiple of 3",
));
}
let mut vector = vec![];
for chunk in str.chunks(3) {
Expand All @@ -263,9 +261,12 @@ impl BFieldCodec for Vec<XFieldElement> {
}

impl BFieldCodec for Vec<Digest> {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
if str.len() % DIGEST_LENGTH != 0 {
return Err(BFieldCodecError::boxed("cannot decode string of BFieldElements into Digests when string length is not a multiple of DIGEST_LENGTH"));
return Err(BFieldCodecError::new(
"cannot decode string of BFieldElements into Digests \
when string length is not a multiple of DIGEST_LENGTH",
));
}
let mut vector: Vec<Digest> = vec![];
for chunk in str.chunks(DIGEST_LENGTH) {
Expand All @@ -284,7 +285,7 @@ impl<T> BFieldCodec for Vec<Vec<T>>
where
Vec<T>: BFieldCodec,
{
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
let mut index = 0;
let mut outer_vec: Vec<Vec<T>> = vec![];
while index < str.len() {
Expand All @@ -294,7 +295,7 @@ where
if let Some(inner_vec) = str.get(index..(index + len)) {
outer_vec.push(*Vec::<T>::decode(inner_vec)?);
} else {
return Err(BFieldCodecError::boxed(
return Err(BFieldCodecError::new(
"cannot decode string BFieldElements into Vec<Vec<T>>; length mismatch",
));
}
Expand All @@ -315,7 +316,7 @@ where
}

impl BFieldCodec for Vec<PartialAuthenticationPath<Digest>> {
fn decode(str: &[BFieldElement]) -> Result<Box<Self>, Box<dyn Error>> {
fn decode(str: &[BFieldElement]) -> anyhow::Result<Box<Self>> {
let mut index = 0;
let mut vector = vec![];

Expand All @@ -325,7 +326,10 @@ impl BFieldCodec for Vec<PartialAuthenticationPath<Digest>> {
index += 1;

if len_remaining < 2 || index + len_remaining > str.len() {
return Err(BFieldCodecError::boxed("cannot decode string of BFieldElements as Vec of PartialAuthenticationPaths due to length mismatch (1)"));
return Err(BFieldCodecError::new(
"cannot decode string of BFieldElements as Vec of PartialAuthenticationPaths \
due to length mismatch (1)",
));
}

let vec_len = str[index].value() as usize;
Expand All @@ -335,8 +339,9 @@ impl BFieldCodec for Vec<PartialAuthenticationPath<Digest>> {
// if the vector length and mask indicates some digests are following
// and we are already at the end of the buffer
if vec_len != 0 && mask != 0 && index == str.len() {
return Err(BFieldCodecError::boxed(
&format!("Cannot decode string of BFieldElements as Vec of PartialAuthenticationPaths due to length mismatch (2).\n\
return Err(BFieldCodecError::new(&format!(
"Cannot decode string of BFieldElements as Vec of PartialAuthenticationPaths \
due to length mismatch (2).\n\
vec_len: {}\n\
mask: {}\n\
index: {}\n\
Expand All @@ -346,12 +351,15 @@ impl BFieldCodec for Vec<PartialAuthenticationPath<Digest>> {
mask,
index,
str.len(),
str[0])
));
str[0]
)));
}

if (len_remaining - 2) % DIGEST_LENGTH != 0 {
return Err(BFieldCodecError::boxed("cannot decode string of BFieldElements as Vec of PartialAuthenticationPaths due to length mismatch (3)"));
return Err(BFieldCodecError::new(
"cannot decode string of BFieldElements as Vec of PartialAuthenticationPaths \
due to length mismatch (3)",
));
}

let mut pap = vec![];
Expand All @@ -363,7 +371,10 @@ impl BFieldCodec for Vec<PartialAuthenticationPath<Digest>> {
pap.push(Some(*Digest::decode(chunk)?));
index += DIGEST_LENGTH;
} else {
return Err(BFieldCodecError::boxed("cannot decode string of BFieldElements as Vec of PartialAuthenticationPaths due to length mismatch (4)"));
return Err(BFieldCodecError::new(
"cannot decode string of BFieldElements as Vec of \
PartialAuthenticationPaths due to length mismatch (4)",
));
}
}

Expand Down
6 changes: 3 additions & 3 deletions triton-vm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ impl Display for InstructionError {

impl Error for InstructionError {}

pub fn vm_err<T>(runtime_error: InstructionError) -> Result<T, Box<dyn Error>> {
pub fn vm_err<T>(runtime_error: InstructionError) -> anyhow::Result<T> {
Err(vm_fail(runtime_error))
}

pub fn vm_fail(runtime_error: InstructionError) -> Box<dyn Error> {
Box::new(runtime_error)
pub fn vm_fail(runtime_error: InstructionError) -> anyhow::Error {
anyhow::Error::new(runtime_error)
}
28 changes: 19 additions & 9 deletions triton-vm/src/fri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl<H: AlgebraicHasher> Fri<H> {
indices: &[usize],
root: Digest,
proof_stream: &mut ProofStream<ProofItem, H>,
) -> Result<Vec<XFieldElement>, Box<dyn Error>> {
) -> anyhow::Result<Vec<XFieldElement>> {
let fri_response = proof_stream.dequeue()?.as_fri_response()?;
let dequeued_paths_and_leafs = fri_response.0;
let paths = dequeued_paths_and_leafs.clone().into_iter().map(|(p, _)| p);
Expand All @@ -115,7 +115,9 @@ impl<H: AlgebraicHasher> Fri<H> {
) {
Ok(values)
} else {
Err(Box::new(FriValidationError::BadMerkleAuthenticationPath))
Err(anyhow::Error::new(
FriValidationError::BadMerkleAuthenticationPath,
))
}
}

Expand All @@ -124,7 +126,7 @@ impl<H: AlgebraicHasher> Fri<H> {
&self,
codeword: &[XFieldElement],
proof_stream: &mut ProofStream<ProofItem, H>,
) -> Result<(Vec<usize>, Digest), Box<dyn Error>> {
) -> anyhow::Result<(Vec<usize>, Digest)> {
debug_assert_eq!(
self.domain.length,
codeword.len(),
Expand Down Expand Up @@ -171,7 +173,7 @@ impl<H: AlgebraicHasher> Fri<H> {
&self,
codeword: &[XFieldElement],
proof_stream: &mut ProofStream<ProofItem, H>,
) -> Result<Vec<(Vec<XFieldElement>, MerkleTree<H, Maker>)>, Box<dyn Error>> {
) -> anyhow::Result<Vec<(Vec<XFieldElement>, MerkleTree<H, Maker>)>> {
let mut subgroup_generator = self.domain.generator;
let mut offset = self.domain.offset;
let mut codeword_local = codeword.to_vec();
Expand Down Expand Up @@ -300,7 +302,7 @@ impl<H: AlgebraicHasher> Fri<H> {
proof_stream: &mut ProofStream<ProofItem, H>,
first_codeword_mt_root: &Digest,
maybe_profiler: &mut Option<TritonProfiler>,
) -> Result<(), Box<dyn Error>> {
) -> anyhow::Result<()> {
prof_start!(maybe_profiler, "init");
let (num_rounds, degree_of_last_round) = self.num_rounds();
let num_rounds = num_rounds as usize;
Expand All @@ -311,7 +313,9 @@ impl<H: AlgebraicHasher> Fri<H> {

let first_root: Digest = proof_stream.dequeue()?.as_merkle_root()?;
if first_root != *first_codeword_mt_root {
return Err(Box::new(FriValidationError::BadMerkleRootForFirstCodeword));
return Err(anyhow::Error::new(
FriValidationError::BadMerkleRootForFirstCodeword,
));
}

roots.push(first_root);
Expand All @@ -338,7 +342,9 @@ impl<H: AlgebraicHasher> Fri<H> {
let last_codeword_mt: MerkleTree<H, Maker> = Maker::from_digests(&codeword_digests);
let last_root = roots.last().unwrap();
if *last_root != last_codeword_mt.get_root() {
return Err(Box::new(FriValidationError::BadMerkleRootForLastCodeword));
return Err(anyhow::Error::new(
FriValidationError::BadMerkleRootForLastCodeword,
));
}
prof_stop!(maybe_profiler, "last codeword matches root");

Expand Down Expand Up @@ -368,7 +374,9 @@ impl<H: AlgebraicHasher> Fri<H> {
"last_poly_degree is {}, degree_of_last_round is {}",
last_poly_degree, degree_of_last_round
);
return Err(Box::new(FriValidationError::LastIterationTooHighDegree));
return Err(anyhow::Error::new(
FriValidationError::LastIterationTooHighDegree,
));
}
prof_stop!(maybe_profiler, "last codeword has low degree");

Expand Down Expand Up @@ -443,7 +451,9 @@ impl<H: AlgebraicHasher> Fri<H> {
prof_start!(maybe_profiler, "compare last codeword");
a_indices = a_indices.iter().map(|x| x % current_domain_len).collect();
if (0..self.colinearity_checks_count).any(|i| last_codeword[a_indices[i]] != a_values[i]) {
return Err(Box::new(FriValidationError::MismatchingLastCodeword));
return Err(anyhow::Error::new(
FriValidationError::MismatchingLastCodeword,
));
}
prof_stop!(maybe_profiler, "compare last codeword");
Ok(())
Expand Down
Loading

0 comments on commit 4b49377

Please sign in to comment.