Skip to content

Commit

Permalink
checked arithmetic
Browse files Browse the repository at this point in the history
  • Loading branch information
brentstone committed Nov 14, 2023
1 parent cd36dfb commit 1b8d247
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
25 changes: 21 additions & 4 deletions proof_of_stake/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,13 @@ where
let val = handle
.get_delta_val(storage, current_epoch + offset)?
.unwrap_or_default();
handle.set(storage, val + delta, current_epoch, offset)
handle.set(
storage,
val.checked_add(&delta)
.expect("Validator deltas updated amount should not overflow"),
current_epoch,
offset,
)
}

/// Read PoS total stake (sum of deltas).
Expand Down Expand Up @@ -698,7 +704,13 @@ where
let val = handle
.get_delta_val(storage, current_epoch + offset)?
.unwrap_or_default();
handle.set(storage, val + delta, current_epoch, offset)
handle.set(
storage,
val.checked_add(&delta)
.expect("Total deltas updated amount should not overflow"),
current_epoch,
offset,
)
}

/// Check if the provided address is a validator address
Expand Down Expand Up @@ -985,7 +997,10 @@ where

// tracing::debug!("VALIDATOR STAKE BEFORE UPDATE: {}", tokens_pre);

let tokens_post = tokens_pre.change() + token_change;
let tokens_post = tokens_pre
.change()
.checked_add(&token_change)
.expect("Post-validator set update token amount has overflowed");
debug_assert!(tokens_post.non_negative());
let tokens_post = token::Amount::from_change(tokens_post);

Expand Down Expand Up @@ -1473,7 +1488,9 @@ where
},
_validator,
) = entry?;
Ok(acc + amount)
Ok(acc.checked_add(amount).expect(
"Total consensus stake computation should not overflow.",
))
})
}

Expand Down
7 changes: 6 additions & 1 deletion proof_of_stake/src/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ impl PosRewardsCalculator {

/// Implement as ceiling of (2/3) * validator set stake
fn get_min_required_votes(&self) -> Amount {
((self.total_stake * 2u64) + (3u64 - 1u64)) / 3u64
(self
.total_stake
.checked_mul(2.into())
.expect("Amount overflow while computing minimum required votes")
+ (3u64 - 1u64))
/ 3u64
}
}

0 comments on commit 1b8d247

Please sign in to comment.