Skip to content

Commit

Permalink
Fix crash bug in create_spending_txes
Browse files Browse the repository at this point in the history
The randomly-generated bitcoin amounts have to be rounded due to floating
point calculations. Because satoshi amounts are represented as u64 in
certain cases the subtractions would result in a value less than zero,
leading to a panic. This was fixed by using a slightly different formula.
  • Loading branch information
chris-belcher committed Jan 14, 2021
1 parent 450f8dc commit 1194975
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/wallet_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,8 +744,15 @@ impl Wallet {
.collect::<Vec<u64>>();

//rounding errors mean usually 1 or 2 satoshis are lost, add them back
let remainder = coinswap_amount - output_values.iter().sum::<u64>();
*output_values.last_mut().unwrap() = output_values.last().unwrap() + remainder;

//this calculation works like this:
//o = [a, b, c, ...] | list of output values
//t = coinswap amount | total desired value
//a <-- a + (t - (a+b+c+...)) | assign new first output value
//a <-- a + (t -a-b-c-...) | rearrange
//a <-- t - b - c -... |
*output_values.first_mut().unwrap() = coinswap_amount
- output_values.iter().skip(1).sum::<u64>();
assert_eq!(output_values.iter().sum::<u64>(), coinswap_amount);

let mut spending_txes = Vec::<Transaction>::new();
Expand Down

0 comments on commit 1194975

Please sign in to comment.