Skip to content

Commit

Permalink
common: Add multiplication primitives for amount_msat and amount_sat
Browse files Browse the repository at this point in the history
The scale variants weren't usable since they use `double` as a scale
factor, which in turn causes imprecisions.
  • Loading branch information
cdecker committed Aug 17, 2022
1 parent 44d0905 commit 976fdfd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
16 changes: 16 additions & 0 deletions common/amount.c
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,22 @@ struct amount_sat amount_sat_div(struct amount_sat sat, u64 div)
return sat;
}

bool amount_sat_mul(struct amount_sat *res, struct amount_sat sat, u64 mul)
{
if ( mul_overflows_u64(sat.satoshis, mul))
return false;
res->satoshis = sat.satoshis * mul;
return true;
}

bool amount_msat_mul(struct amount_msat *res, struct amount_msat msat, u64 mul)
{
if ( mul_overflows_u64(msat.millisatoshis, mul))
return false;
res->millisatoshis = msat.millisatoshis * mul;
return true;
}

bool amount_msat_fee(struct amount_msat *fee,
struct amount_msat amt,
u32 fee_base_msat,
Expand Down
3 changes: 3 additions & 0 deletions common/amount.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ WARN_UNUSED_RESULT bool amount_sat_scale(struct amount_sat *val,
struct amount_msat amount_msat_div(struct amount_msat msat, u64 div);
struct amount_sat amount_sat_div(struct amount_sat sat, u64 div);

bool amount_sat_mul(struct amount_sat *res, struct amount_sat sat, u64 mul);
bool amount_msat_mul(struct amount_msat *res, struct amount_msat msat, u64 mul);

/* Is a == b? */
bool amount_sat_eq(struct amount_sat a, struct amount_sat b);
bool amount_msat_eq(struct amount_msat a, struct amount_msat b);
Expand Down

0 comments on commit 976fdfd

Please sign in to comment.