refactor: use _MiB consistently for Mebibyte conversions
What changed, and why it matters
This is a code cleanup change that replaces scattered hard-coded byte counts like 1024*1024 with a single named helper, _MiB, and adds unit tests for it. It does not change any user-visible behavior or fix a known security bug. The main safety benefit is making future accidental mistakes (for example, writing the wrong number of zeros) less likely and turning some oversized-value mistakes into compile-time errors.
No security response needed. Treat as normal code-quality refactor. Reviewers may optionally verify that no arithmetic expression changed its result type in a way that affects comparisons or divisions, and that brace-initialization did not introduce unintended narrowing errors on supported platforms.
Security signals we found
Refactoring only: no functional change in byte values or logic
Brace-init narrowing guard added for values derived from _MiB/_GiB literals
Unit tests extended for overflow boundary of 32-bit size_t
No bug fix, CVE, or exploit path described in commit message
Evidence from the diff
The commit refactors Bitcoin Core to use the existing _MiB and _GiB user-defined literals from util/byte_units.h instead of inline constants such as 10241024, 1<<20, 1048576, and 32<<20. It also switches declarations to brace initialization so that assigning an oversized value to a narrower type becomes a narrowing compile error. The change touches benchmarks, init logic, database code, Qt options, logging, validation, and tests. Values are preserved exactly (e.g., 1<<20 becomes 1_MiB, 32<<20 becomes 32_MiB, 5501024*1024 becomes 550_MiB). A few expressions involving signed quantities are rewritten with explicit casts to keep the same arithmetic. Unit tests are extended to verify equivalences and 32-bit size_t overflow behavior of the _MiB literal.
Changed components
src/util/byte_units.h usageinit/pruning argument handlingblock storage and chainstate cache sizingLevelDB/coins DB batch loggingQt options model prune target conversionsrandom environment entropy collectionsignature/script execution cache defaultsbenchmark and test harnessesInspect captured patch +138 / −82
diff --git a/src/bench/chacha20.cpp b/src/bench/chacha20.cpp
index 37165177..b5a333d0 100644
--- a/src/bench/chacha20.cpp
+++ b/src/bench/chacha20.cpp
@@ -7,6 +7,7 @@
#include <crypto/chacha20.h>
#include <crypto/chacha20poly1305.h>
#include <span.h>
+#include <util/byte_units.h>
#include <cstddef>
#include <cstdint>
@@ -15,7 +16,7 @@
/* Number of bytes to process per iteration */
static const uint64_t BUFFER_SIZE_TINY = 64;
static const uint64_t BUFFER_SIZE_SMALL = 256;
-static const uint64_t BUFFER_SIZE_LARGE = 1024*1024;
+static const uint64_t BUFFER_SIZE_LARGE{1_MiB};
static void CHACHA20(benchmark::Bench& bench, size_t buffersize)
{
diff --git a/src/bench/lockedpool.cpp b/src/bench/lockedpool.cpp
index 27fd609a..61b35cce 100644
--- a/src/bench/lockedpool.cpp
+++ b/src/bench/lockedpool.cpp
@@ -7,6 +7,7 @@
#include <cstddef>
#include <cstdint>
+#include <util/byte_units.h>
#include <vector>
#define ASIZE 2048
@@ -15,7 +16,7 @@
static void BenchLockedPool(benchmark::Bench& bench)
{
void *synth_base = reinterpret_cast<void*>(0x08000000);
- const size_t synth_size = 1024*1024;
+ const size_t synth_size{1_MiB};
Arena b(synth_base, synth_size, 16);
std::vector<void*> addr{ASIZE, nullptr};
diff --git a/src/bench/poly1305.cpp b/src/bench/poly1305.cpp
index e782164a..ef5a573d 100644
--- a/src/bench/poly1305.cpp
+++ b/src/bench/poly1305.cpp
@@ -6,6 +6,7 @@
#include <bench/bench.h>
#include <crypto/poly1305.h>
#include <span.h>
+#include <util/byte_units.h>
#include <cstddef>
#include <cstdint>
@@ -14,7 +15,7 @@
/* Number of bytes to process per iteration */
static constexpr uint64_t BUFFER_SIZE_TINY = 64;
static constexpr uint64_t BUFFER_SIZE_SMALL = 256;
-static constexpr uint64_t BUFFER_SIZE_LARGE = 1024*1024;
+static constexpr uint64_t BUFFER_SIZE_LARGE{1_MiB};
static void POLY1305(benchmark::Bench& bench, size_t buffersize)
{
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index eb222078..3212f6d3 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -19,6 +19,7 @@
#include <serialize.h>
#include <span.h>
#include <streams.h>
+#include <util/byte_units.h>
#include <util/fs.h>
#include <util/fs_helpers.h>
#include <util/log.h>
@@ -280,12 +281,12 @@ void CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
const bool log_memory = LogAcceptCategory(BCLog::LEVELDB, util::log::Level::Debug);
double mem_before = 0;
if (log_memory) {
- mem_before = DynamicMemoryUsage() / 1024.0 / 1024;
+ mem_before = DynamicMemoryUsage() / double(1_MiB);
}
leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
HandleError(status);
if (log_memory) {
- double mem_after = DynamicMemoryUsage() / 1024.0 / 1024;
+ double mem_after{DynamicMemoryUsage() / double(1_MiB)};
LogDebug(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
m_name, mem_before, mem_after);
}
diff --git a/src/dbwrapper.h b/src/dbwrapper.h
index 2eee6c1c..f0cfe2dc 100644
--- a/src/dbwrapper.h
+++ b/src/dbwrapper.h
@@ -9,6 +9,7 @@
#include <serialize.h>
#include <span.h>
#include <streams.h>
+#include <util/byte_units.h>
#include <util/check.h>
#include <util/fs.h>
@@ -21,7 +22,7 @@
static const size_t DBWRAPPER_PREALLOC_KEY_SIZE = 64;
static const size_t DBWRAPPER_PREALLOC_VALUE_SIZE = 1024;
-static const size_t DBWRAPPER_MAX_FILE_SIZE = 32 << 20; // 32 MiB
+static const size_t DBWRAPPER_MAX_FILE_SIZE{32_MiB};
//! User-controlled performance and debug options.
struct DBOptions {
diff --git a/src/index/blockfilterindex.cpp b/src/index/blockfilterindex.cpp
index e63aa4a3..d4fd7025 100644
--- a/src/index/blockfilterindex.cpp
+++ b/src/index/blockfilterindex.cpp
@@ -49,9 +49,9 @@
*/
constexpr uint8_t DB_FILTER_POS{'P'};
-constexpr unsigned int MAX_FLTR_FILE_SIZE = 0x1000000; // 16 MiB
+constexpr unsigned int MAX_FLTR_FILE_SIZE{16_MiB};
/** The pre-allocation chunk size for fltr?????.dat files */
-constexpr unsigned int FLTR_FILE_CHUNK_SIZE = 0x100000; // 1 MiB
+constexpr unsigned int FLTR_FILE_CHUNK_SIZE{1_MiB};
/** Maximum size of the cfheaders cache
* We have a limit to prevent a bug in filling this cache
* potentially turning into an OOM. At 2000 entries, this cache
diff --git a/src/init.cpp b/src/init.cpp
index 4b6e00bd..a9445754 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -77,6 +77,7 @@
#include <txmempool.h>
#include <util/asmap.h>
#include <util/batchpriority.h>
+#include <util/byte_units.h>
#include <util/chaintype.h>
#include <util/check.h>
#include <util/fs.h>
@@ -525,7 +526,7 @@ void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)
argsman.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex. "
"Warning: Reverting this setting requires re-downloading the entire blockchain. "
- "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
+ "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-reindex", "If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-reindex-chainstate", "If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-settings=<file>", strprintf("Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
@@ -1328,8 +1329,8 @@ static ChainstateLoadResult InitAndLoadChainstate(
return {ChainstateLoadStatus::FAILURE_FATAL, mempool_error};
}
LogInfo("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)",
- cache_sizes.coins * (1.0 / 1024 / 1024),
- mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
+ cache_sizes.coins / double(1_MiB),
+ mempool_opts.max_size_bytes / double(1_MiB));
ChainstateManager::Options chainman_opts{
.chainparams = chainparams,
.datadir = args.GetDataDirNet(),
@@ -1467,7 +1468,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
// Check disk space every 5 minutes to avoid db corruption.
scheduler.scheduleEvery([&args, &node]{
- constexpr uint64_t min_disk_space = 50 << 20; // 50 MB
+ constexpr uint64_t min_disk_space{50_MiB};
if (!CheckDiskSpace(args.GetBlocksDirPath(), min_disk_space)) {
LogError("Shutting down due to lack of disk space!\n");
if (!(Assert(node.shutdown_request))()) {
@@ -1835,18 +1836,18 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
const auto [index_cache_sizes, kernel_cache_sizes] = CalculateCacheSizes(args, g_enabled_filter_types.size());
LogInfo("Cache configuration:");
- LogInfo("* Using %.1f MiB for block index database", kernel_cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
+ LogInfo("* Using %.1f MiB for block index database", kernel_cache_sizes.block_tree_db / double(1_MiB));
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
- LogInfo("* Using %.1f MiB for transaction index database", index_cache_sizes.tx_index * (1.0 / 1024 / 1024));
+ LogInfo("* Using %.1f MiB for transaction index database", index_cache_sizes.tx_index / double(1_MiB));
}
if (args.GetBoolArg("-txospenderindex", DEFAULT_TXOSPENDERINDEX)) {
- LogInfo("* Using %.1f MiB for transaction output spender index database", index_cache_sizes.txospender_index * (1.0 / 1024 / 1024));
+ LogInfo("* Using %.1f MiB for transaction output spender index database", index_cache_sizes.txospender_index / double(1_MiB));
}
for (BlockFilterType filter_type : g_enabled_filter_types) {
LogInfo("* Using %.1f MiB for %s block filter index database",
- index_cache_sizes.filter_index * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type));
+ index_cache_sizes.filter_index / double(1_MiB), BlockFilterTypeName(filter_type));
}
- LogInfo("* Using %.1f MiB for chain state database", kernel_cache_sizes.coins_db * (1.0 / 1024 / 1024));
+ LogInfo("* Using %.1f MiB for chain state database", kernel_cache_sizes.coins_db / double(1_MiB));
assert(!node.mempool);
assert(!node.chainman);
diff --git a/src/logging.h b/src/logging.h
index 1f0e8889..3417b4b7 100644
--- a/src/logging.h
+++ b/src/logging.h
@@ -9,6 +9,7 @@
#include <crypto/siphash.h>
#include <logging/categories.h> // IWYU pragma: export
#include <span.h>
+#include <util/byte_units.h>
#include <util/fs.h>
#include <util/log.h> // IWYU pragma: export
#include <util/stdmutex.h>
@@ -62,7 +63,7 @@ struct LogCategory {
namespace BCLog {
constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
- constexpr uint64_t RATELIMIT_MAX_BYTES{1024 * 1024}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
+ constexpr uint64_t RATELIMIT_MAX_BYTES{1_MiB}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
constexpr auto RATELIMIT_WINDOW{1h}; // time window after which log ratelimit stats are reset
constexpr bool DEFAULT_LOGRATELIMIT{true};
diff --git a/src/node/blockmanager_args.cpp b/src/node/blockmanager_args.cpp
index 1f84819b..3a5f4d75 100644
--- a/src/node/blockmanager_args.cpp
+++ b/src/node/blockmanager_args.cpp
@@ -8,6 +8,7 @@
#include <node/blockstorage.h>
#include <node/database_args.h>
#include <tinyformat.h>
+#include <util/byte_units.h>
#include <util/result.h>
#include <util/translation.h>
#include <validation.h>
@@ -23,12 +24,12 @@ util::Result<void> ApplyArgsManOptions(const ArgsManager& args, BlockManager::Op
if (nPruneArg < 0) {
return util::Error{_("Prune cannot be configured with a negative value.")};
}
- uint64_t nPruneTarget{uint64_t(nPruneArg) * 1024 * 1024};
+ uint64_t nPruneTarget{uint64_t(nPruneArg) * 1_MiB};
if (nPruneArg == 1) { // manual pruning: -prune=1
nPruneTarget = BlockManager::PRUNE_TARGET_MANUAL;
} else if (nPruneTarget) {
if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
- return util::Error{strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)};
+ return util::Error{strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1_MiB)};
}
}
opts.prune_target = nPruneTarget;
diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp
index 27394e0d..b0842a00 100644
--- a/src/node/blockstorage.cpp
+++ b/src/node/blockstorage.cpp
@@ -394,8 +394,8 @@ void BlockManager::FindFilesToPrune(
}
LogDebug(BCLog::PRUNE, "[%s] target=%dMiB actual=%dMiB diff=%dMiB min_height=%d max_prune_height=%d removed %d blk/rev pairs\n",
- chain.GetRole(), target / 1024 / 1024, nCurrentUsage / 1024 / 1024,
- (int64_t(target) - int64_t(nCurrentUsage)) / 1024 / 1024,
+ chain.GetRole(), target / 1_MiB, nCurrentUsage / 1_MiB,
+ (int64_t(target) - int64_t(nCurrentUsage)) / int64_t(1_MiB),
min_block_to_prune, last_block_can_prune, count);
}
diff --git a/src/node/blockstorage.h b/src/node/blockstorage.h
index d46db3fb..a081b954 100644
--- a/src/node/blockstorage.h
+++ b/src/node/blockstorage.h
@@ -18,6 +18,7 @@
#include <streams.h>
#include <sync.h>
#include <uint256.h>
+#include <util/byte_units.h> // IWYU pragma: keep
#include <util/expected.h>
#include <util/fs.h>
#include <util/hasher.h>
@@ -116,11 +117,11 @@ using kernel::CBlockFileInfo;
using kernel::BlockTreeDB;
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
-static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
+static const unsigned int BLOCKFILE_CHUNK_SIZE{16_MiB};
/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
-static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
+static const unsigned int UNDOFILE_CHUNK_SIZE{1_MiB};
/** The maximum size of a blk?????.dat file (since 0.8) */
-static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
+static const unsigned int MAX_BLOCKFILE_SIZE{128_MiB};
/** Size of header written by WriteBlock before a serialized CBlock (8 bytes) */
static constexpr uint32_t STORAGE_HEADER_BYTES{std::tuple_size_v<MessageStartChars> + sizeof(unsigned int)};
diff --git a/src/node/chainstate.cpp b/src/node/chainstate.cpp
index 0738c00a..1725fe70 100644
--- a/src/node/chainstate.cpp
+++ b/src/node/chainstate.cpp
@@ -14,6 +14,7 @@
#include <tinyformat.h>
#include <txdb.h>
#include <uint256.h>
+#include <util/byte_units.h>
#include <util/fs.h>
#include <util/log.h>
#include <util/signalinterrupt.h>
@@ -163,7 +164,7 @@ ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSize
LogInfo("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.");
} else if (chainman.m_blockman.GetPruneTarget()) {
LogInfo("Prune configured to target %u MiB on disk for block and undo files.",
- chainman.m_blockman.GetPruneTarget() / 1024 / 1024);
+ chainman.m_blockman.GetPruneTarget() / 1_MiB);
}
LOCK(cs_main);
diff --git a/src/node/chainstatemanager_args.cpp b/src/node/chainstatemanager_args.cpp
index 640fe128..bf91a750 100644
--- a/src/node/chainstatemanager_args.cpp
+++ b/src/node/chainstatemanager_args.cpp
@@ -12,6 +12,7 @@
#include <node/database_args.h>
#include <tinyformat.h>
#include <uint256.h>
+#include <util/byte_units.h>
#include <util/result.h>
#include <util/strencodings.h>
#include <util/translation.h>
@@ -64,7 +65,7 @@ util::Result<void> ApplyArgsManOptions(const ArgsManager& args, ChainstateManage
// script execution cache create the minimum possible cache (2
// elements). Therefore, we can use 0 as a floor here.
// 2. Multiply first, divide after to avoid integer truncation.
- size_t clamped_size_each = std::max<int64_t>(*max_size, 0) * (1 << 20) / 2;
+ size_t clamped_size_each{size_t(std::max<int64_t>(*max_size, 0) * 1_MiB / 2)};
opts.script_execution_cache_bytes = clamped_size_each;
opts.signature_cache_bytes = clamped_size_each;
}
diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h
index 4cbd5319..feef00a3 100644
--- a/src/qt/optionsmodel.h
+++ b/src/qt/optionsmodel.h
@@ -8,6 +8,7 @@
#include <cstdint>
#include <qt/bitcoinunits.h>
#include <qt/guiconstants.h>
+#include <util/byte_units.h>
#include <QAbstractListModel>
#include <QFont>
@@ -26,12 +27,12 @@ static constexpr uint16_t DEFAULT_GUI_PROXY_PORT = 9050;
/**
* Convert configured prune target MiB to displayed GB. Round up to avoid underestimating max disk usage.
*/
-static inline int PruneMiBtoGB(int64_t mib) { return (mib * 1024 * 1024 + GB_BYTES - 1) / GB_BYTES; }
+static inline int PruneMiBtoGB(int64_t mib) { return (mib * 1_MiB + GB_BYTES - 1) / GB_BYTES; }
/**
* Convert displayed prune target GB to configured MiB. Round down so roundtrip GB -> MiB -> GB conversion is stable.
*/
-static inline int64_t PruneGBtoMiB(int gb) { return gb * GB_BYTES / 1024 / 1024; }
+static inline int64_t PruneGBtoMiB(int gb) { return gb * GB_BYTES / 1_MiB; }
/** Interface from Qt to configuration data structure for Bitcoin client.
To Qt, the options are presented as a list with the different options
diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp
index d30a8acf..a00eb181 100644
--- a/src/qt/rpcconsole.cpp
+++ b/src/qt/rpcconsole.cpp
@@ -21,6 +21,7 @@
#endif // ENABLE_WALLET
#include <rpc/client.h>
#include <rpc/server.h>
+#include <util/byte_units.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/time.h>
@@ -529,7 +530,7 @@ RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformSty
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
- ui->lineEdit->setMaxLength(16 * 1024 * 1024);
+ ui->lineEdit->setMaxLength(16_MiB);
ui->messagesWidget->installEventFilter(this);
connect(ui->hidePeersDetailButton, &QAbstractButton::clicked, this, &RPCConsole::clearSelectedNode);
diff --git a/src/randomenv.cpp b/src/randomenv.cpp
index 662625b5..c85e9181 100644
--- a/src/randomenv.cpp
+++ b/src/randomenv.cpp
@@ -13,6 +13,7 @@
#include <crypto/sha512.h>
#include <span.h>
#include <support/cleanse.h>
+#include <util/byte_units.h>
#include <util/time.h>
#include <algorithm>
@@ -113,7 +114,7 @@ void AddFile(CSHA512& hasher, const char *path)
if (n > 0) hasher.Write(fbuf, n);
total += n;
/* not bothering with EINTR handling. */
- } while (n == sizeof(fbuf) && total < 1048576); // Read only the first 1 Mbyte
+ } while (n == sizeof(fbuf) && total < 1_MiB); // Read only the first 1 Mbyte
close(f);
}
}
diff --git a/src/script/sigcache.h b/src/script/sigcache.h
index fb388096..fe9a3562 100644
--- a/src/script/sigcache.h
+++ b/src/script/sigcache.h
@@ -12,6 +12,7 @@
#include <script/interpreter.h>
#include <span.h>
#include <uint256.h>
+#include <util/byte_units.h>
#include <util/hasher.h>
#include <cstddef>
@@ -25,7 +26,7 @@ class XOnlyPubKey;
// DoS prevention: limit cache size to 32MiB (over 1000000 entries on 64-bit
// systems). Due to how we count cache size, actual memory usage is slightly
// more (~32.25 MiB)
-static constexpr size_t DEFAULT_VALIDATION_CACHE_BYTES{32 << 20};
+static constexpr size_t DEFAULT_VALIDATION_CACHE_BYTES{32_MiB};
static constexpr size_t DEFAULT_SIGNATURE_CACHE_BYTES{DEFAULT_VALIDATION_CACHE_BYTES / 2};
static constexpr size_t DEFAULT_SCRIPT_EXECUTION_CACHE_BYTES{DEFAULT_VALIDATION_CACHE_BYTES / 2};
static_assert(DEFAULT_VALIDATION_CACHE_BYTES == DEFAULT_SIGNATURE_CACHE_BYTES + DEFAULT_SCRIPT_EXECUTION_CACHE_BYTES);
diff --git a/src/test/allocator_tests.cpp b/src/test/allocator_tests.cpp
index 65a0629d..f5e9b202 100644
--- a/src/test/allocator_tests.cpp
+++ b/src/test/allocator_tests.cpp
@@ -8,6 +8,7 @@
#include <limits>
#include <memory>
#include <stdexcept>
+#include <util/byte_units.h>
#include <utility>
#include <vector>
@@ -20,7 +21,7 @@ BOOST_AUTO_TEST_CASE(arena_tests)
// Fake memory base address for testing
// without actually using memory.
void *synth_base = reinterpret_cast<void*>(0x08000000);
- const size_t synth_size = 1024*1024;
+ const size_t synth_size{1_MiB};
Arena b(synth_base, synth_size, 16);
void *chunk = b.alloc(1000);
#ifdef ARENA_DEBUG
diff --git a/src/test/blockfilter_index_tests.cpp b/src/test/blockfilter_index_tests.cpp
index 25762e07..f5a18fdd 100644
--- a/src/test/blockfilter_index_tests.cpp
+++ b/src/test/blockfilter_index_tests.cpp
@@ -14,6 +14,7 @@
#include <test/util/blockfilter.h>
#include <test/util/common.h>
#include <test/util/setup_common.h>
+#include <util/byte_units.h>
#include <validation.h>
#include <boost/test/unit_test.hpp>
@@ -116,7 +117,7 @@ bool BuildChainTestingSetup::BuildChain(const CBlockIndex* pindex,
BOOST_FIXTURE_TEST_CASE(blockfilter_index_initial_sync, BuildChainTestingSetup)
{
- BlockFilterIndex filter_index(interfaces::MakeChain(m_node), BlockFilterType::BASIC, 1 << 20, true);
+ BlockFilterIndex filter_index(interfaces::MakeChain(m_node), BlockFilterType::BASIC, 1_MiB, true);
BOOST_REQUIRE(filter_index.Init());
uint256 last_header;
@@ -277,14 +278,14 @@ BOOST_FIXTURE_TEST_CASE(blockfilter_index_init_destroy, BasicTestingSetup)
filter_index = GetBlockFilterIndex(BlockFilterType::BASIC);
BOOST_CHECK(filter_index == nullptr);
- BOOST_CHECK(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1 << 20, true, false));
+ BOOST_CHECK(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1_MiB, true, false));
filter_index = GetBlockFilterIndex(BlockFilterType::BASIC);
BOOST_CHECK(filter_index != nullptr);
BOOST_CHECK(filter_index->GetFilterType() == BlockFilterType::BASIC);
// Initialize returns false if index already exists.
- BOOST_CHECK(!InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1 << 20, true, false));
+ BOOST_CHECK(!InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1_MiB, true, false));
int iter_count = 0;
ForEachBlockFilterIndex([&iter_count](BlockFilterIndex& _index) { iter_count++; });
@@ -299,7 +300,7 @@ BOOST_FIXTURE_TEST_CASE(blockfilter_index_init_destroy, BasicTestingSetup)
BOOST_CHECK(filter_index == nullptr);
// Reinitialize index.
- BOOST_CHECK(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1 << 20, true, false));
+ BOOST_CHECK(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1_MiB, true, false));
DestroyAllBlockFilterIndexes();
diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp
index 2a180f25..2cad6698 100644
--- a/src/test/coins_tests.cpp
+++ b/src/test/coins_tests.cpp
@@ -13,6 +13,7 @@
#include <txdb.h>
#include <uint256.h>
#include <undo.h>
+#include <util/byte_units.h>
#include <util/strencodings.h>
#include <map>
@@ -296,7 +297,7 @@ BOOST_FIXTURE_TEST_SUITE(coins_tests_dbbase, BasicTestingSetup)
BOOST_FIXTURE_TEST_CASE(coins_cache_dbbase_simulation_test, CacheTest)
{
- CCoinsViewDB db_base{{.path = "test", .cache_bytes = 1 << 23, .memory_only = true}, {}};
+ CCoinsViewDB db_base{{.path = "test", .cache_bytes = 8_MiB, .memory_only = true}, {}};
SimulationTest(&db_base, true);
}
@@ -1048,7 +1049,7 @@ void TestFlushBehavior(
BOOST_FIXTURE_TEST_CASE(ccoins_flush_behavior, FlushTest)
{
// Create two in-memory caches atop a leveldb view.
- CCoinsViewDB base{{.path = "test", .cache_bytes = 1 << 23, .memory_only = true}, {}};
+ CCoinsViewDB base{{.path = "test", .cache_bytes = 8_MiB, .memory_only = true}, {}};
std::vector<std::unique_ptr<CCoinsViewCacheTest>> caches;
caches.push_back(std::make_unique<CCoinsViewCacheTest>(&base));
caches.push_back(std::make_unique<CCoinsViewCacheTest>(caches.back().get()));
diff --git a/src/test/coinstatsindex_tests.cpp b/src/test/coinstatsindex_tests.cpp
index 9b32aabb..f7f97c9b 100644
--- a/src/test/coinstatsindex_tests.cpp
+++ b/src/test/coinstatsindex_tests.cpp
@@ -9,6 +9,7 @@
#include <kernel/types.h>
#include <test/util/setup_common.h>
#include <test/util/validation.h>
+#include <util/byte_units.h>
#include <validation.h>
#include <boost/test/unit_test.hpp>
@@ -19,7 +20,7 @@ BOOST_AUTO_TEST_SUITE(coinstatsindex_tests)
BOOST_FIXTURE_TEST_CASE(coinstatsindex_initial_sync, TestChain100Setup)
{
- CoinStatsIndex coin_stats_index{interfaces::MakeChain(m_node), 1 << 20, true};
+ CoinStatsIndex coin_stats_index{interfaces::MakeChain(m_node), 1_MiB, true};
BOOST_REQUIRE(coin_stats_index.Init());
const CBlockIndex* block_index;
@@ -75,7 +76,7 @@ BOOST_FIXTURE_TEST_CASE(coinstatsindex_unclean_shutdown, TestChain100Setup)
Chainstate& chainstate = Assert(m_node.chainman)->ActiveChainstate();
const CChainParams& params = Params();
{
- CoinStatsIndex index{interfaces::MakeChain(m_node), 1 << 20};
+ CoinStatsIndex index{interfaces::MakeChain(m_node), 1_MiB};
BOOST_REQUIRE(index.Init());
index.Sync();
std::shared_ptr<const CBlock> new_block;
@@ -101,7 +102,7 @@ BOOST_FIXTURE_TEST_CASE(coinstatsindex_unclean_shutdown, TestChain100Setup)
}
{
- CoinStatsIndex index{interfaces::MakeChain(m_node), 1 << 20};
+ CoinStatsIndex index{interfaces::MakeChain(m_node), 1_MiB};
BOOST_REQUIRE(index.Init());
// Make sure the index can be loaded.
BOOST_REQUIRE(index.StartBackgroundSync());
diff --git a/src/test/cuckoocache_tests.cpp b/src/test/cuckoocache_tests.cpp
index 5c723596..9d2cb8e4 100644
--- a/src/test/cuckoocache_tests.cpp
+++ b/src/test/cuckoocache_tests.cpp
@@ -7,6 +7,7 @@
#include <script/sigcache.h>
#include <test/util/random.h>
#include <test/util/setup_common.h>
+#include <util/byte_units.h>
#include <boost/test/unit_test.hpp>
@@ -39,8 +40,7 @@ BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes)
{
SeedRandomForTest(SeedRand::ZEROS);
CuckooCache::cache<uint256, SignatureCacheHasher> cc{};
- size_t megabytes = 4;
- cc.setup_bytes(megabytes << 20);
+ cc.setup_bytes(4_MiB);
for (int x = 0; x < 100000; ++x) {
cc.insert(m_rng.rand256());
}
@@ -59,7 +59,7 @@ double test_cache(size_t megabytes, double load)
SeedRandomForTest(SeedRand::ZEROS);
std::vector<uint256> hashes;
Cache set{};
- size_t bytes = megabytes * (1 << 20);
+ size_t bytes{megabytes * 1_MiB};
set.setup_bytes(bytes);
uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));
hashes.resize(n_insert);
@@ -132,7 +132,7 @@ void test_cache_erase(size_t megabytes)
SeedRandomForTest(SeedRand::ZEROS);
std::vector<uint256> hashes;
Cache set{};
- size_t bytes = megabytes * (1 << 20);
+ size_t bytes{megabytes * 1_MiB};
set.setup_bytes(bytes);
uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));
hashes.resize(n_insert);
@@ -197,7 +197,7 @@ void test_cache_erase_parallel(size_t megabytes)
SeedRandomForTest(SeedRand::ZEROS);
std::vector<uint256> hashes;
Cache set{};
- size_t bytes = megabytes * (1 << 20);
+ size_t bytes{megabytes * 1_MiB};
set.setup_bytes(bytes);
uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));
hashes.resize(n_insert);
@@ -335,8 +335,7 @@ void test_cache_generations()
const uint32_t WINDOW_SIZE = 60;
const uint32_t POP_AMOUNT = (BLOCK_SIZE / WINDOW_SIZE) / 2;
const double load = 10;
- const size_t megabytes = 4;
- const size_t bytes = megabytes * (1 << 20);
+ const size_t bytes{4_MiB};
const uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));
std::vector<block_activity> hashes;
diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp
index 3896ea64..19e70ded 100644
--- a/src/test/dbwrapper_tests.cpp
+++ b/src/test/dbwrapper_tests.cpp
@@ -7,6 +7,7 @@
#include <test/util/random.h>
#include <test/util/setup_common.h>
#include <uint256.h>
+#include <util/byte_units.h>
#include <util/string.h>
#include <memory>
@@ -74,7 +75,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper_basic_data)
// Perform tests both obfuscated and non-obfuscated.
for (bool obfuscate : {false, true}) {
fs::path ph = m_args.GetDataDirBase() / (obfuscate ? "dbwrapper_1_obfuscate_true" : "dbwrapper_1_obfuscate_false");
- CDBWrapper dbw({.path = ph, .cache_bytes = 1 << 20, .memory_only = false, .wipe_data = true, .obfuscate = obfuscate});
+ CDBWrapper dbw({.path = ph, .cache_bytes = 1_MiB, .memory_only = false, .wipe_data = true, .obfuscate = obfuscate});
uint256 res;
uint32_t res_uint_32;
@@ -155,7 +156,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper_batch)
// Perform tests both obfuscated and non-obfuscated.
for (const bool obfuscate : {false, true}) {
fs::path ph = m_args.GetDataDirBase() / (obfuscate ? "dbwrapper_batch_obfuscate_true" : "dbwrapper_batch_obfuscate_false");
- CDBWrapper dbw({.path = ph, .cache_bytes = 1 << 20, .memory_only = true, .wipe_data = false, .obfuscate = obfuscate});
+ CDBWrapper dbw({.path = ph, .cache_bytes = 1_MiB, .memory_only = true, .wipe_data = false, .obfuscate = obfuscate});
uint8_t key{'i'};
uint256 in = m_rng.rand256();
@@ -191,7 +192,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
// Perform tests both obfuscated and non-obfuscated.
for (const bool obfuscate : {false, true}) {
fs::path ph = m_args.GetDataDirBase() / (obfuscate ? "dbwrapper_iterator_obfuscate_true" : "dbwrapper_iterator_obfuscate_false");
- CDBWrapper dbw({.path = ph, .cache_bytes = 1 << 20, .memory_only = true, .wipe_data = false, .obfuscate = obfuscate});
+ CDBWrapper dbw({.path = ph, .cache_bytes = 1_MiB, .memory_only = true, .wipe_data = false, .obfuscate = obfuscate});
// The two keys are intentionally chosen for ordering
uint8_t key{'j'};
@@ -307,7 +308,7 @@ BOOST_AUTO_TEST_CASE(existing_data_reindex)
BOOST_AUTO_TEST_CASE(iterator_ordering)
{
fs::path ph = m_args.GetDataDirBase() / "iterator_ordering";
- CDBWrapper dbw({.path = ph, .cache_bytes = 1 << 20, .memory_only = true, .wipe_data = false, .obfuscate = false});
+ CDBWrapper dbw({.path = ph, .cache_bytes = 1_MiB, .memory_only = true, .wipe_data = false, .obfuscate = false});
for (int x=0x00; x<256; ++x) {
uint8_t key = x;
uint32_t value = x*x;
@@ -375,7 +376,7 @@ struct StringContentsSerializer {
BOOST_AUTO_TEST_CASE(iterator_string_ordering)
{
fs::path ph = m_args.GetDataDirBase() / "iterator_string_ordering";
- CDBWrapper dbw({.path = ph, .cache_bytes = 1 << 20, .memory_only = true, .wipe_data = false, .obfuscate = false});
+ CDBWrapper dbw({.path = ph, .cache_bytes = 1_MiB, .memory_only = true, .wipe_data = false, .obfuscate = false});
for (int x = 0; x < 10; ++x) {
for (int y = 0; y < 10; ++y) {
std::string key{ToString(x)};
@@ -417,7 +418,7 @@ BOOST_AUTO_TEST_CASE(unicodepath)
// the ANSI CreateDirectoryA call and the code page isn't UTF8.
// It will succeed if created with CreateDirectoryW.
fs::path ph = m_args.GetDataDirBase() / "test_runner_₿_🏃_20191128_104644";
- CDBWrapper dbw({.path = ph, .cache_bytes = 1 << 20});
+ CDBWrapper dbw({.path = ph, .cache_bytes = 1_MiB});
fs::path lockPath = ph / "LOCK";
BOOST_CHECK(fs::exists(lockPath));
diff --git a/src/test/fuzz/block_index.cpp b/src/test/fuzz/block_index.cpp
index c2d9f30f..903d28d1 100644
--- a/src/test/fuzz/block_index.cpp
+++ b/src/test/fuzz/block_index.cpp
@@ -10,6 +10,7 @@
#include <test/fuzz/util.h>
#include <test/util/setup_common.h>
#include <txdb.h>
+#include <util/byte_units.h>
#include <validation.h>
using kernel::CBlockFileInfo;
@@ -58,7 +59,7 @@ FUZZ_TARGET(block_index, .init = init_block_index)
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
auto block_index = kernel::BlockTreeDB(DBParams{
.path = "", // Memory only.
- .cache_bytes = 1 << 20, // 1MB.
+ .cache_bytes = 1_MiB,
.memory_only = true,
});
diff --git a/src/test/fuzz/cuckoocache.cpp b/src/test/fuzz/cuckoocache.cpp
index 65468899..55da81ff 100644
--- a/src/test/fuzz/cuckoocache.cpp
+++ b/src/test/fuzz/cuckoocache.cpp
@@ -8,6 +8,7 @@
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <test/util/setup_common.h>
+#include <util/byte_units.h>
#include <cstdint>
#include <string>
@@ -33,7 +34,7 @@ FUZZ_TARGET(cuckoocache)
CuckooCache::cache<int, RandomHasher> cuckoo_cache{};
if (fuzzed_data_provider.ConsumeBool()) {
const size_t megabytes = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 16);
- cuckoo_cache.setup_bytes(megabytes << 20);
+ cuckoo_cache.setup_bytes(megabytes * 1_MiB);
} else {
cuckoo_cache.setup(fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(0, 4096));
}
diff --git a/src/test/fuzz/poolresource.cpp b/src/test/fuzz/poolresource.cpp
index 9217af1f..2b2b33bf 100644
--- a/src/test/fuzz/poolresource.cpp
+++ b/src/test/fuzz/poolresource.cpp
@@ -9,6 +9,7 @@
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <test/util/poolresourcetester.h>
+#include <util/byte_units.h>
#include <cstdint>
#include <tuple>
@@ -61,7 +62,7 @@ public:
void
Allocate()
{
- if (m_total_allocated > 0x1000000) return;
+ if (m_total_allocated > 16_MiB) return;
size_t alignment_bits = m_provider.ConsumeIntegralInRange<size_t>(0, 7);
size_t alignment = size_t{1} << alignment_bits;
size_t size_bits = m_provider.ConsumeIntegralInRange<size_t>(0, 16 - alignment_bits);
diff --git a/src/test/fuzz/script_parsing.cpp b/src/test/fuzz/script_parsing.cpp
index 1f32130d..183a89d4 100644
--- a/src/test/fuzz/script_parsing.cpp
+++ b/src/test/fuzz/script_parsing.cpp
@@ -5,6 +5,7 @@
#include <script/parsing.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
+#include <util/byte_units.h>
#include <util/string.h>
using util::Split;
@@ -13,7 +14,7 @@ FUZZ_TARGET(script_parsing)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const size_t query_size = fuzzed_data_provider.ConsumeIntegral<size_t>();
- const std::string query = fuzzed_data_provider.ConsumeBytesAsString(std::min<size_t>(query_size, 1024 * 1024));
+ const std::string query = fuzzed_data_provider.ConsumeBytesAsString(std::min<size_t>(query_size, 1_MiB));
const std::string span_str = fuzzed_data_provider.ConsumeRemainingBytesAsString();
const std::span<const char> const_span{span_str};
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index 35947996..46711e08 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -7,6 +7,7 @@
#include <index/txindex.h>
#include <interfaces/chain.h>
#include <test/util/setup_common.h>
+#include <util/byte_units.h>
#include <validation.h>
#include <boost/test/unit_test.hpp>
@@ -15,7 +16,7 @@ BOOST_AUTO_TEST_SUITE(txindex_tests)
BOOST_FIXTURE_TEST_CASE(txindex_initial_sync, TestChain100Setup)
{
- TxIndex txindex(interfaces::MakeChain(m_node), 1 << 20, true);
+ TxIndex txindex(interfaces::MakeChain(m_node), 1_MiB, true);
BOOST_REQUIRE(txindex.Init());
CTransactionRef tx_disk;
diff --git a/src/test/util/chainstate.h b/src/test/util/chainstate.h
index 3ceed569..db11d565 100644
--- a/src/test/util/chainstate.h
+++ b/src/test/util/chainstate.h
@@ -11,6 +11,7 @@
#include <node/utxo_snapshot.h>
#include <rpc/blockchain.h>
#include <test/util/setup_common.h>
+#include <util/byte_units.h>
#include <util/fs.h>
#include <validation.h>
@@ -81,8 +82,8 @@ CreateAndActivateUTXOSnapshot(
Chainstate& chain = node.chainman->ActiveChainstate();
Assert(chain.LoadGenesisBlock());
// These cache values will be corrected shortly in `MaybeRebalanceCaches`.
- chain.InitCoinsDB(1 << 20, /*in_memory=*/true, /*should_wipe=*/false);
- chain.InitCoinsCache(1 << 20);
+ chain.InitCoinsDB(1_MiB, /*in_memory=*/true, /*should_wipe=*/false);
+ chain.InitCoinsCache(1_MiB);
chain.CoinsTip().SetBestBlock(gen_hash);
chain.LoadChainTip();
node.chainman->MaybeRebalanceCaches();
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp
index 796a9deb..a407d7d3 100644
--- a/src/test/util_tests.cpp
+++ b/src/test/util_tests.cpp
@@ -1633,7 +1633,7 @@ BOOST_AUTO_TEST_CASE(util_ParseByteUnits)
BOOST_CHECK_EQUAL(ParseByteUnits("1K", noop).value(), 1ULL << 10);
BOOST_CHECK_EQUAL(ParseByteUnits("2m", noop).value(), 2'000'000ULL);
- BOOST_CHECK_EQUAL(ParseByteUnits("2M", noop).value(), 2ULL << 20);
+ BOOST_CHECK_EQUAL(ParseByteUnits("2M", noop).value(), 2_MiB);
BOOST_CHECK_EQUAL(ParseByteUnits("3g", noop).value(), 3'000'000'000ULL);
BOOST_CHECK_EQUAL(ParseByteUnits("3G", noop).value(), 3_GiB);
@@ -1657,7 +1657,7 @@ BOOST_AUTO_TEST_CASE(util_ParseByteUnits)
BOOST_CHECK(!ParseByteUnits("+123m", noop));
// zero padding
- BOOST_CHECK_EQUAL(ParseByteUnits("020M", noop).value(), 20ULL << 20);
+ BOOST_CHECK_EQUAL(ParseByteUnits("020M", noop).value(), 20_MiB);
// fractions not allowed
BOOST_CHECK(!ParseByteUnits("0.5T", noop));
@@ -1831,8 +1831,34 @@ BOOST_AUTO_TEST_CASE(mib_string_literal_test)
{
// Basic equivalences and simple arithmetic operations
BOOST_CHECK_EQUAL(0_MiB, 0);
+ BOOST_CHECK_EQUAL(1_MiB, 1 << 20);
BOOST_CHECK_EQUAL(1_MiB, 1024 * 1024);
+ BOOST_CHECK_EQUAL(1_MiB, 0x100000U);
+ BOOST_CHECK_EQUAL(1_MiB, 1048576U);
+ BOOST_CHECK_EQUAL(2ULL * 1_MiB, 2ULL << 20);
+ BOOST_CHECK_EQUAL((3_MiB + 123) / double(1_MiB), (3_MiB + 123) / 1024.0 / 1024.0);
+
+ // Specific codebase values
+ BOOST_CHECK_EQUAL(4_MiB, 1 << 22);
+ BOOST_CHECK_EQUAL(8_MiB, 1 << 23);
+ BOOST_CHECK_EQUAL(16_MiB, 0x1000000U);
+ BOOST_CHECK_EQUAL(16_MiB, 1 << 24);
+ BOOST_CHECK_EQUAL(32_MiB, 0x2000000U);
+ BOOST_CHECK_EQUAL(32_MiB, 32U << 20);
+ BOOST_CHECK_EQUAL(50_MiB / 1_MiB, 50U);
+ BOOST_CHECK_EQUAL(50_MiB, 52428800U);
+ BOOST_CHECK_EQUAL(128_MiB, 0x8000000U);
+ BOOST_CHECK_EQUAL(550_MiB, 550ULL * 1024 * 1024);
+
+ // Overflow handling
constexpr auto max_mib{std::numeric_limits<size_t>::max() >> 20};
+ if constexpr (SIZE_MAX == UINT32_MAX) {
+ BOOST_CHECK_EQUAL(max_mib, 4095U);
+ BOOST_CHECK_EQUAL(4095_MiB, size_t{4095} << 20);
+ BOOST_CHECK_EXCEPTION(4096_MiB, std::overflow_error, HasReason("MiB value too large for size_t byte conversion"));
+ } else {
+ BOOST_CHECK_EQUAL(4096_MiB, size_t{4096} << 20);
+ }
BOOST_CHECK_EXCEPTION(operator""_MiB(max_mib + 1), std::overflow_error, HasReason("MiB value too large for size_t byte conversion"));
}
diff --git a/src/test/validation_chainstate_tests.cpp b/src/test/validation_chainstate_tests.cpp
index cb3a04ef..38a04d8e 100644
--- a/src/test/validation_chainstate_tests.cpp
+++ b/src/test/validation_chainstate_tests.cpp
@@ -16,6 +16,7 @@
#include <test/util/random.h>
#include <test/util/setup_common.h>
#include <uint256.h>
+#include <util/byte_units.h>
#include <util/check.h>
#include <validation.h>
@@ -33,8 +34,8 @@ BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
CTxMemPool& mempool = *Assert(m_node.mempool);
Chainstate& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(&mempool));
c1.InitCoinsDB(
- /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
- WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23));
+ /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
+ WITH_LOCK(::cs_main, c1.InitCoinsCache(8_MiB));
BOOST_REQUIRE(c1.LoadGenesisBlock()); // Need at least one block loaded to be able to flush caches
// Add a coin to the in-memory cache, upsize once, then downsize.
@@ -49,16 +50,16 @@ BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
c1.ResizeCoinsCaches(
- 1 << 24, // upsizing the coinsview cache
- 1 << 22 // downsizing the coinsdb cache
+ 16_MiB, // upsizing the coinsview cache
+ 4_MiB // downsizing the coinsdb cache
);
// View should still have the coin cached, since we haven't destructed the cache on upsize.
BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
c1.ResizeCoinsCaches(
- 1 << 22, // downsizing the coinsview cache
- 1 << 23 // upsizing the coinsdb cache
+ 4_MiB, // downsizing the coinsview cache
+ 8_MiB // upsizing the coinsdb cache
);
// The view cache should be empty since we had to destruct to downsize.
diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp
index 67c90a00..9818b51e 100644
--- a/src/test/validation_chainstatemanager_tests.cpp
+++ b/src/test/validation_chainstatemanager_tests.cpp
@@ -18,6 +18,7 @@
#include <test/util/setup_common.h>
#include <test/util/validation.h>
#include <uint256.h>
+#include <util/byte_units.h>
#include <util/result.h>
#include <util/vector.h>
#include <validation.h>
@@ -72,10 +73,10 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager, TestChain100Setup)
const uint256 snapshot_blockhash = active_tip->GetBlockHash();
Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, snapshot_blockhash)))};
c2.InitCoinsDB(
- /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
+ /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
{
LOCK(::cs_main);
- c2.InitCoinsCache(1 << 23);
+ c2.InitCoinsCache(8_MiB);
c2.CoinsTip().SetBestBlock(active_tip->GetBlockHash());
for (const auto& cs : manager.m_chainstates) {
cs->ClearBlockIndexCandidates();
@@ -133,7 +134,7 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
chainstates.push_back(&c1);
{
LOCK(::cs_main);
- c1.InitCoinsCache(1 << 23);
+ c1.InitCoinsCache(8_MiB);
manager.MaybeRebalanceCaches();
}
@@ -146,7 +147,7 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, *snapshot_base->phashBlock)))};
chainstates.push_back(&c2);
c2.InitCoinsDB(
- /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
+ /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
// Reset IBD state so IsInitialBlockDownload() returns true and causes
// MaybeRebalanceCaches() to prioritize the snapshot chainstate, giving it
@@ -159,7 +160,7 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
{
LOCK(::cs_main);
- c2.InitCoinsCache(1 << 23);
+ c2.InitCoinsCache(8_MiB);
manager.MaybeRebalanceCaches();
}
diff --git a/src/txdb.cpp b/src/txdb.cpp
index a098faa4..a41dfd16 100644
--- a/src/txdb.cpp
+++ b/src/txdb.cpp
@@ -12,6 +12,7 @@
#include <random.h>
#include <serialize.h>
#include <uint256.h>
+#include <util/byte_units.h>
#include <util/log.h>
#include <util/vector.h>
@@ -146,7 +147,7 @@ void CCoinsViewDB::BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block
count++;
it = cursor.NextAndMaybeErase(*it);
if (batch.ApproximateSize() > m_options.batch_write_bytes) {
- LogDebug(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.ApproximateSize() * (1.0 / 1048576.0));
+ LogDebug(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.ApproximateSize() / double(1_MiB));
m_db->WriteBatch(batch);
batch.Clear();
@@ -164,7 +165,7 @@ void CCoinsViewDB::BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block
batch.Erase(DB_HEAD_BLOCKS);
batch.Write(DB_BEST_BLOCK, block_hash);
- LogDebug(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.ApproximateSize() * (1.0 / 1048576.0));
+ LogDebug(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.ApproximateSize() / double(1_MiB));
m_db->WriteBatch(batch);
LogDebug(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...", (unsigned int)dirty_count, (unsigned int)count);
}
diff --git a/src/util/fs_helpers.cpp b/src/util/fs_helpers.cpp
index 8e08e66d..a41bf65a 100644
--- a/src/util/fs_helpers.cpp
+++ b/src/util/fs_helpers.cpp
@@ -8,6 +8,7 @@
#include <util/fs_helpers.h>
#include <sync.h>
+#include <util/byte_units.h> // IWYU pragma: keep
#include <util/fs.h>
#include <util/log.h>
#include <util/syserror.h>
@@ -87,7 +88,7 @@ void ReleaseDirectoryLocks()
bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
{
- constexpr uint64_t min_disk_space = 52428800; // 50 MiB
+ constexpr uint64_t min_disk_space{50_MiB};
uint64_t free_bytes_available = fs::space(dir).available;
return free_bytes_available >= min_disk_space + additional_bytes;
diff --git a/src/validation.cpp b/src/validation.cpp
index a2b93233..8762416f 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -48,6 +48,7 @@
#include <txmempool.h>
#include <uint256.h>
#include <undo.h>
+#include <util/byte_units.h>
#include <util/check.h>
#include <util/fs.h>
#include <util/fs_helpers.h>
@@ -2870,7 +2871,7 @@ static void UpdateTipLog(
log(tip->nChainWork.getdouble()) / log(2.0), tip->m_chain_tx_count,
FormatISO8601DateTime(tip->GetBlockTime()),
background_validation ? chainman.GetBackgroundVerificationProgress(*tip) : chainman.GuessVerificationProgress(tip),
- coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
+ coins_tip.DynamicMemoryUsage() / double(1_MiB),
coins_tip.GetCacheSize(),
!warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
}
@@ -5459,9 +5460,9 @@ bool Chainstate::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
CoinsDB().ResizeCache(coinsdb_size);
LogInfo("[%s] resized coinsdb cache to %.1f MiB",
- this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
+ this->ToString(), coinsdb_size / double(1_MiB));
LogInfo("[%s] resized coinstip cache to %.1f MiB",
- this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
+ this->ToString(), coinstip_size / double(1_MiB));
BlockValidationState state;
bool ret;
diff --git a/src/validation.h b/src/validation.h
index cee0dd72..e0f5e80c 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -84,7 +84,7 @@ static constexpr int DEFAULT_CHECKLEVEL{3};
// full block file chunks, we need the high water mark which triggers the prune to be
// one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
// Setting the target to >= 550 MiB will make it likely we can respect the target.
-static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
+static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES{550_MiB};
/** Maximum number of dedicated script-checking threads allowed */
static constexpr int MAX_SCRIPTCHECK_THREADS{15};
Why this scored 20/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.