From fa327c77e34e0cfb7994842c23f539ab11bf5d3b Mon Sep 17 00:00:00 2001 From: marcofleon Date: Mon, 4 Nov 2024 11:32:23 +0000 Subject: [PATCH] util: Add ConsumeArithUInt256InRange fuzzing helper --- src/test/fuzz/util.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/test/fuzz/util.h b/src/test/fuzz/util.h index de09745730..8e2b8639c2 100644 --- a/src/test/fuzz/util.h +++ b/src/test/fuzz/util.h @@ -180,6 +180,22 @@ template return UintToArith256(ConsumeUInt256(fuzzed_data_provider)); } +[[nodiscard]] inline arith_uint256 ConsumeArithUInt256InRange(FuzzedDataProvider& fuzzed_data_provider, const arith_uint256& min, const arith_uint256& max) noexcept +{ + assert(min <= max); + const arith_uint256 range = max - min; + const arith_uint256 value = ConsumeArithUInt256(fuzzed_data_provider); + arith_uint256 result = value; + // Avoid division by 0, in case range + 1 results in overflow. + if (range != ~arith_uint256(0)) { + const arith_uint256 quotient = value / (range + 1); + result = value - (quotient * (range + 1)); + } + result += min; + assert(result >= min && result <= max); + return result; +} + [[nodiscard]] std::map ConsumeCoins(FuzzedDataProvider& fuzzed_data_provider) noexcept; [[nodiscard]] CTxDestination ConsumeTxDestination(FuzzedDataProvider& fuzzed_data_provider) noexcept;