Skip to content

Commit

Permalink
fix: check for overflow while adding values
Browse files Browse the repository at this point in the history
  • Loading branch information
RolandSherwin authored and bochaco committed Jun 29, 2023
1 parent 57e91a5 commit 3c27b94
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/transaction/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ pub enum Error {
MissingTxInputs,
#[error("Dbc id is not unique across all tx inputs.")]
DbcIdNotUniqueAcrossInputs,
#[error("Overflow occurred while adding values")]
NumericOverflow,
}
16 changes: 14 additions & 2 deletions src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,20 @@ impl DbcTransaction {
}

// Check that the input and output amounts are equal.
let input_sum: u64 = self.inputs.iter().map(|i| i.amount.value).sum();
let output_sum: u64 = self.outputs.iter().map(|o| o.amount.value).sum();
let input_sum: u64 = self
.inputs
.iter()
.map(|i| i.amount.value)
.try_fold(0, |acc: u64, i| {
acc.checked_add(i).ok_or(Error::NumericOverflow)
})?;
let output_sum: u64 = self
.outputs
.iter()
.map(|o| o.amount.value)
.try_fold(0, |acc: u64, o| {
acc.checked_add(o).ok_or(Error::NumericOverflow)
})?;

if input_sum != output_sum {
Err(Error::InconsistentDbcTransaction)
Expand Down

0 comments on commit 3c27b94

Please sign in to comment.