From 2ab4e5b42b4593c584694cfa1a695325843925e7 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Wed, 13 Oct 2021 14:12:42 +1030 Subject: [PATCH] utils: add max_unsigned/min_unsigned helpers. We are usually dealing with unsigned values, so use this. Signed-off-by: Rusty Russell --- bitcoin/script.c | 4 +--- common/utils.h | 24 ++++++++++++++++++++++++ onchaind/onchaind.c | 3 +-- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/bitcoin/script.c b/bitcoin/script.c index fdd05be54..6a3e6f8c4 100644 --- a/bitcoin/script.c +++ b/bitcoin/script.c @@ -12,8 +12,6 @@ /* To push 0-75 bytes onto stack. */ #define OP_PUSHBYTES(val) (val) -#define max(a, b) ((a) > (b) ? (a) : (b)) - /* Bitcoin's OP_HASH160 is RIPEMD(SHA256()) */ static void hash160(struct ripemd160 *redeemhash, const void *mem, size_t len) { @@ -556,7 +554,7 @@ u8 *bitcoin_wscript_to_local(const tal_t *ctx, u16 to_self_delay, add_op(&script, OP_IF); add_push_key(&script, revocation_pubkey); add_op(&script, OP_ELSE); - add_number(&script, max(lease_remaining, to_self_delay)); + add_number(&script, max_unsigned(lease_remaining, to_self_delay)); add_op(&script, OP_CHECKSEQUENCEVERIFY); add_op(&script, OP_DROP); add_push_key(&script, local_delayedkey); diff --git a/common/utils.h b/common/utils.h index 0b396bb87..0282f5a53 100644 --- a/common/utils.h +++ b/common/utils.h @@ -1,6 +1,7 @@ #ifndef LIGHTNING_COMMON_UTILS_H #define LIGHTNING_COMMON_UTILS_H #include "config.h" +#include #include #include #include @@ -12,6 +13,29 @@ extern secp256k1_context *secp256k1_ctx; extern const struct chainparams *chainparams; +/* Unsigned min/max macros: BUILD_ASSERT make sure types are unsigned */ +#if HAVE_TYPEOF +#define MUST_BE_UNSIGNED_INT(x) BUILD_ASSERT_OR_ZERO((typeof(x))(-1)>=0) +#else +#define MUST_BE_UNSIGNED_INT(x) 0 +#endif + +#define min_unsigned(a, b) \ + (MUST_BE_UNSIGNED_INT(a) + MUST_BE_UNSIGNED_INT(b) + min_u64((a), (b))) + +#define max_unsigned(a, b) \ + (MUST_BE_UNSIGNED_INT(a) + MUST_BE_UNSIGNED_INT(b) + max_u64((a), (b))) + +static inline u64 min_u64(u64 a, u64 b) +{ + return a < b ? a : b; +} + +static inline u64 max_u64(u64 a, u64 b) +{ + return a < b ? b : a; +} + /* Marker which indicates an (tal) pointer argument is stolen * (i.e. eventually freed) by the function. Unlike TAKEN, which * indicates it's only stolen if caller says take() */ diff --git a/onchaind/onchaind.c b/onchaind/onchaind.c index 425a5da74..39836e1c4 100644 --- a/onchaind/onchaind.c +++ b/onchaind/onchaind.c @@ -23,7 +23,6 @@ /* stdin == requests */ #define REQ_FD STDIN_FILENO #define HSM_FD 3 -#define max(a, b) ((a) > (b) ? (a) : (b)) /* Required in various places: keys for commitment transaction. */ static const struct keyset *keyset; @@ -2837,7 +2836,7 @@ static void handle_our_unilateral(const struct tx_parts *tx, our_unilateral_to_us(&outs, tx, tx_blockheight, i, amt, - max(to_self_delay[LOCAL], csv), + max_unsigned(to_self_delay[LOCAL], csv), script[LOCAL], local_wscript, is_replay);