From a52bdeee015bd7236d03a1763764a8db4acc6c08 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Sun, 19 Jun 2022 16:47:11 +0930 Subject: [PATCH] common: add msat to sat convert helper. We don't always want to round down, sometimes we want to fail. Signed-off-by: Rusty Russell --- common/amount.c | 10 ++++++++++ common/amount.h | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/common/amount.c b/common/amount.c index fa1870700..e17a68044 100644 --- a/common/amount.c +++ b/common/amount.c @@ -18,6 +18,16 @@ bool amount_sat_to_msat(struct amount_msat *msat, return true; } +bool amount_msat_to_sat(struct amount_sat *sat, + struct amount_msat msat) +{ + if (msat.millisatoshis % MSAT_PER_SAT) + return false; + sat->satoshis = msat.millisatoshis / MSAT_PER_SAT; + return true; +} + + /* You can always truncate millisatoshis->satoshis. */ struct amount_sat amount_msat_to_sat_round_down(struct amount_msat msat) { diff --git a/common/amount.h b/common/amount.h index b7277d7ee..b16e92593 100644 --- a/common/amount.h +++ b/common/amount.h @@ -53,6 +53,10 @@ struct amount_sat amount_sat(u64 satoshis); WARN_UNUSED_RESULT bool amount_sat_to_msat(struct amount_msat *msat, struct amount_sat sat); +/* You may not always be able to convert millisatoshis->satoshis without rounding. */ +WARN_UNUSED_RESULT bool amount_msat_to_sat(struct amount_sat *sat, + struct amount_msat msat); + /* You can always truncate millisatoshis->satoshis. */ struct amount_sat amount_msat_to_sat_round_down(struct amount_msat msat);