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

[Merged by Bors] - Add safe_sum and use it in state_processing #1620

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
70 changes: 70 additions & 0 deletions consensus/safe_arith/src/iter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use crate::{Result, SafeArith};

/// Extension trait for iterators, providing a safe replacement for `sum`.
pub trait SafeArithIter<T> {
fn safe_sum(self) -> Result<T>;
}

impl<I, T> SafeArithIter<T> for I
where
I: Iterator<Item = T> + Sized,
T: SafeArith,
{
fn safe_sum(mut self) -> Result<T> {
self.try_fold(T::ZERO, |acc, x| acc.safe_add(x))
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::ArithError;

#[test]
fn empty_sum() {
let v: Vec<u64> = vec![];
assert_eq!(v.into_iter().safe_sum(), Ok(0));
}

#[test]
fn unsigned_sum_small() {
let v = vec![400u64, 401, 402, 403, 404, 405, 406];
assert_eq!(
v.iter().copied().safe_sum().unwrap(),
v.iter().copied().sum()
);
}

#[test]
fn unsigned_sum_overflow() {
let v = vec![u64::MAX, 1];
assert_eq!(v.into_iter().safe_sum(), Err(ArithError::Overflow));
}

#[test]
fn signed_sum_small() {
let v = vec![-1i64, -2i64, -3i64, 3, 2, 1];
assert_eq!(v.into_iter().safe_sum(), Ok(0));
}

#[test]
fn signed_sum_overflow_above() {
let v = vec![1, 2, 3, 4, i16::MAX, 0, 1, 2, 3];
assert_eq!(v.into_iter().safe_sum(), Err(ArithError::Overflow));
}

#[test]
fn signed_sum_overflow_below() {
let v = vec![i16::MIN, -1];
assert_eq!(v.into_iter().safe_sum(), Err(ArithError::Overflow));
}

#[test]
fn signed_sum_almost_overflow() {
let v = vec![i64::MIN, 1, -1i64, i64::MAX, i64::MAX, 1];
assert_eq!(
v.iter().copied().safe_sum().unwrap(),
v.iter().copied().sum()
);
}
}
5 changes: 4 additions & 1 deletion consensus/safe_arith/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
//! Library for safe arithmetic on integers, avoiding overflow and division by zero.
mod iter;

pub use iter::SafeArithIter;

/// Error representing the failure of an arithmetic operation.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
Expand All @@ -7,7 +10,7 @@ pub enum ArithError {
DivisionByZero,
}

type Result<T> = std::result::Result<T, ArithError>;
pub type Result<T> = std::result::Result<T, ArithError>;

macro_rules! assign_method {
($name:ident, $op:ident, $doc_op:expr) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use safe_arith::SafeArith;
use safe_arith::{SafeArith, SafeArithIter};
use types::{BeaconStateError as Error, *};

/// Process slashings.
Expand All @@ -10,7 +10,7 @@ pub fn process_slashings<T: EthSpec>(
spec: &ChainSpec,
) -> Result<(), Error> {
let epoch = state.current_epoch();
let sum_slashings = state.get_all_slashings().iter().sum::<u64>();
let sum_slashings = state.get_all_slashings().iter().copied().safe_sum()?;

for (index, validator) in state.validators.iter().enumerate() {
if validator.slashed
Expand Down