Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2025-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <test/fuzz/FuzzedDataProvider.h>6#include <test/fuzz/fuzz.h>7#include <util/check.h>8#include <util/overflow.h>10#include <algorithm>11#include <limits>12#include <optional>14namespace {15//! Test overflow operations for type T using a wider type, W, to verify results.16template <typename T, typename W>17void TestOverflow(FuzzedDataProvider& fuzzed_data_provider)18{19constexpr auto min{std::numeric_limits<T>::min()};20constexpr auto max{std::numeric_limits<T>::max()};21// Range needs to be at least twice as big to allow two numbers to be added without overflowing.22static_assert(min >= std::numeric_limits<W>::min() / 2);23static_assert(max <= std::numeric_limits<W>::max() / 2);25auto widen = [](T value) -> W { return value; };26auto clamp = [](W value) -> W { return std::clamp<W>(value, min, max); };27auto check = [](W value) -> std::optional<W> { if (value >= min && value <= max) return value; else return std::nullopt; };29const T i = fuzzed_data_provider.ConsumeIntegral<T>();30const T j = fuzzed_data_provider.ConsumeIntegral<T>();31const unsigned shift = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, std::numeric_limits<W>::digits - std::numeric_limits<T>::digits);33Assert(clamp(widen(i) + widen(j)) == SaturatingAdd(i, j));34Assert(check(widen(i) + widen(j)) == CheckedAdd(i, j));36Assert(clamp(widen(i) << shift) == SaturatingLeftShift(i, shift));37Assert(check(widen(i) << shift) == CheckedLeftShift(i, shift));38}39} // namespace41FUZZ_TARGET(overflow)42{43FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());44TestOverflow<int8_t, int64_t>(fuzzed_data_provider);45TestOverflow<int16_t, int64_t>(fuzzed_data_provider);46TestOverflow<int32_t, int64_t>(fuzzed_data_provider);47TestOverflow<uint8_t, uint64_t>(fuzzed_data_provider);48TestOverflow<uint16_t, uint64_t>(fuzzed_data_provider);49TestOverflow<uint32_t, uint64_t>(fuzzed_data_provider);50}
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.