Merge bitcoin/bitcoin#36451: refactor: Use NotNull for CreateNewBlock and pimpls
What changed, and why it matters
This is a code cleanup change that makes the type system express 'this pointer can never be null' for several internal objects and for block templates. It removes redundant null checks and adds helper functions to create such non-null pointers. There is no security vulnerability being fixed here, and no behavior change to the running program.
No security action required. Treat as normal code-quality refactor during review/merge.
Security signals we found
No security-relevant bug is patched
Change is purely a type-system refactor
Removes dead null-check error paths rather than adding safety checks
No input validation, cryptography, consensus, or networking logic is modified
Evidence from the diff
The commit refactors Bitcoin Core to use the existing util::NotNull wrapper (and new NotNullUniquePtr/NotNullSharedPtr aliases plus MakeNotNullUnique/MakeNotNullShared helpers) for pimpl-style implementation pointers and for CreateNewBlock/CreateNewTemplate return values. It converts std::unique_ptr members in AddrMan, CDBBatch/CDBIterator, MuSig2SecNonce, TxDownloadManager, TxReconciliationTracker, TxRequestTracker, ValidationSignals, and test globals to NotNullUniquePtr. It also changes BlockAssembler::CreateNewBlock and BlockTemplateManager::CreateNewTemplate to return NotNullUniquePtr
Changed components
src/util/not_null.hsrc/node/miner.cpp/hsrc/node/block_template_manager.cpp/hsrc/node/interfaces.cppsrc/rpc/mining.cppsrc/addrman.hsrc/dbwrapper.cpp/hsrc/musig.hsrc/net.cppsrc/node/txdownloadman.hsrc/node/txreconciliation.hsrc/policy/fees/mempool_estimator.cppsrc/txmempool.hsrc/txrequest.hsrc/validation.cppsrc/validationinterface.cpp/htests in src/test/Inspect captured patch +78 / −52
### src/addrman.h
@@ -8,6 +8,7 @@
#include <netaddress.h>
#include <protocol.h>
+#include <util/not_null.h>
#include <util/time.h>
#include <cstddef>
@@ -109,7 +110,7 @@ struct AddressPosition {
class AddrMan
{
protected:
- const std::unique_ptr<AddrManImpl> m_impl;
+ const util::NotNullUniquePtr<AddrManImpl> m_impl;
public:
explicit AddrMan(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio);
### src/dbwrapper.cpp
@@ -395,15 +395,16 @@ struct CDBIterator::IteratorImpl {
explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
};
-CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent),
- m_impl_iter(std::move(_piter))
+CDBIterator::CDBIterator(const CDBWrapper& _parent, util::NotNullUniquePtr<IteratorImpl> _piter)
+ : parent(_parent),
+ m_impl_iter(std::move(_piter))
{
m_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
}
CDBIterator* CDBWrapper::NewIterator()
{
- return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
+ return new CDBIterator{*this, util::MakeNotNullUnique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
}
void CDBIterator::SeekImpl(std::span<const std::byte> key)
### src/dbwrapper.h
@@ -94,7 +94,7 @@ class CDBBatch
const CDBWrapper &parent;
struct WriteBatchImpl;
- const std::unique_ptr<WriteBatchImpl> m_impl_batch;
+ const util::NotNullUniquePtr<WriteBatchImpl> m_impl_batch;
DataStream m_key_scratch{};
DataStream m_value_scratch{};
@@ -137,7 +137,7 @@ class CDBIterator
private:
const CDBWrapper &parent;
- const std::unique_ptr<IteratorImpl> m_impl_iter;
+ const util::NotNullUniquePtr<IteratorImpl> m_impl_iter;
DataStream m_scratch{};
void SeekImpl(std::span<const std::byte> key);
@@ -150,7 +150,7 @@ class CDBIterator
* @param[in] _parent Parent CDBWrapper instance.
* @param[in] _piter The original leveldb iterator.
*/
- CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter);
+ CDBIterator(const CDBWrapper& _parent, util::NotNullUniquePtr<IteratorImpl> _piter);
~CDBIterator();
bool Valid() const;
### src/musig.h
@@ -6,6 +6,7 @@
#define BITCOIN_MUSIG_H
#include <pubkey.h>
+#include <util/not_null.h>
#include <optional>
#include <vector>
@@ -40,7 +41,7 @@ CExtPubKey CreateMuSig2SyntheticXpub(const CPubKey& pubkey);
class MuSig2SecNonce
{
private:
- std::unique_ptr<MuSig2SecNonceImpl> m_impl;
+ util::NotNullUniquePtr<MuSig2SecNonceImpl> m_impl;
public:
MuSig2SecNonce();
### src/net.cpp
@@ -4143,9 +4143,9 @@ ServiceFlags CConnman::GetLocalServices() const
static util::NotNullUniquePtr<Transport> MakeTransport(NodeId id, bool use_v2transport, bool inbound) noexcept
{
if (use_v2transport) {
- return util::NotNull{std::make_unique<V2Transport>(id, /*initiating=*/!inbound)};
+ return util::MakeNotNullUnique<V2Transport>(id, /*initiating=*/!inbound);
} else {
- return util::NotNull{std::make_unique<V1Transport>(id)};
+ return util::MakeNotNullUnique<V1Transport>(id);
}
}
### src/node/block_template_manager.cpp
@@ -40,7 +40,7 @@ BlockTemplateManager::BlockTemplateManager(CTxMemPool& mempool, ChainstateManage
{
}
-std::unique_ptr<CBlockTemplate> BlockTemplateManager::CreateNewTemplate(const BlockCreateOptions& options)
+util::NotNullUniquePtr<CBlockTemplate> BlockTemplateManager::CreateNewTemplate(const BlockCreateOptions& options)
{
return BlockAssembler{
m_chainman.ActiveChainstate(),
@@ -105,7 +105,7 @@ void BlockTemplateManager::InterruptWait(bool& interrupt_wait)
}
std::unique_ptr<CBlockTemplate> BlockTemplateManager::WaitAndCreateNewBlock(
- const std::unique_ptr<CBlockTemplate>& block_template,
+ const CBlockTemplate& block_template,
const BlockWaitOptions& wait_options,
const BlockCreateOptions& create_options,
bool& interrupt_wait)
@@ -132,7 +132,7 @@ std::unique_ptr<CBlockTemplate> BlockTemplateManager::WaitAndCreateNewBlock(
// We assume tip_block is set, because this is an instance
// method on BlockTemplate and no template could have been
// generated before a tip exists.
- tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
+ tip_changed = Assume(tip_block) && tip_block != block_template.block.hashPrevBlock;
return tip_changed || m_chainman.m_interrupt || interrupt_wait;
});
if (interrupt_wait) {
@@ -172,7 +172,7 @@ std::unique_ptr<CBlockTemplate> BlockTemplateManager::WaitAndCreateNewBlock(
// Calculate the original template total fees if we haven't already
if (current_fees == -1) {
- current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0});
+ current_fees = std::accumulate(block_template.vTxFees.begin(), block_template.vTxFees.end(), CAmount{0});
}
// Check if fees increased enough to return the new template
### src/node/block_template_manager.h
@@ -6,6 +6,7 @@
#define BITCOIN_NODE_BLOCK_TEMPLATE_MANAGER_H
#include <node/mining_types.h>
+#include <util/not_null.h>
#include <util/time.h>
#include <memory>
@@ -47,7 +48,7 @@ class BlockTemplateManager
const BlockCreateOptions& BlockCreateArgs() const { return m_block_create_args; }
/** Create a fresh block template, applying init-time defaults to any unset options. */
- std::unique_ptr<CBlockTemplate> CreateNewTemplate(const BlockCreateOptions& options);
+ util::NotNullUniquePtr<CBlockTemplate> CreateNewTemplate(const BlockCreateOptions& options);
/** Submit a block via ProcessNewBlock and capture validation state.
* @return whether the block was accepted as a new valid block. */
@@ -96,7 +97,7 @@ class BlockTemplateManager
/** Return a new block template when fees rise to a certain threshold or
* after a new tip; return nullptr if timeout is reached. */
std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(
- const std::unique_ptr<CBlockTemplate>& block_template,
+ const CBlockTemplate& block_template,
const BlockWaitOptions& wait_options,
const BlockCreateOptions& create_options,
bool& interrupt_wait);
### src/node/interfaces.cpp
@@ -63,6 +63,7 @@
#include <util/check.h>
#include <util/expected.h>
#include <util/fees.h>
+#include <util/not_null.h>
#include <util/result.h>
#include <util/signalinterrupt.h>
#include <util/string.h>
@@ -876,12 +877,11 @@ class BlockTemplateImpl : public BlockTemplate
{
public:
explicit BlockTemplateImpl(BlockCreateOptions create_options,
- std::unique_ptr<CBlockTemplate> block_template,
+ util::NotNullUniquePtr<CBlockTemplate> block_template,
const NodeContext& node) : m_create_options(std::move(create_options)),
m_block_template(std::move(block_template)),
m_node(node)
{
- assert(m_block_template);
}
CBlockHeader getBlockHeader() override
@@ -924,8 +924,8 @@ class BlockTemplateImpl : public BlockTemplate
std::unique_ptr<BlockTemplate> waitNext(BlockWaitOptions options) override
{
auto new_template = block_template_manager().WaitAndCreateNewBlock(
- m_block_template, options, m_create_options, m_interrupt_wait);
- if (new_template) return std::make_unique<BlockTemplateImpl>(m_create_options, std::move(new_template), m_node);
+ *m_block_template, options, m_create_options, m_interrupt_wait);
+ if (new_template) return std::make_unique<BlockTemplateImpl>(m_create_options, util::NotNull{std::move(new_template)}, m_node);
return nullptr;
}
@@ -936,7 +936,7 @@ class BlockTemplateImpl : public BlockTemplate
const BlockCreateOptions m_create_options;
- const std::unique_ptr<CBlockTemplate> m_block_template;
+ const util::NotNullUniquePtr<CBlockTemplate> m_block_template;
bool m_interrupt_wait{false};
node::BlockTemplateManager& block_template_manager() { return *Assert(m_node.block_template_manager); }
### src/node/miner.cpp
@@ -123,13 +123,13 @@ void BlockAssembler::resetBlock()
nFees = 0;
}
-std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
+util::NotNullUniquePtr<CBlockTemplate> BlockAssembler::CreateNewBlock()
{
const auto time_start{SteadyClock::now()};
resetBlock();
- pblocktemplate.reset(new CBlockTemplate());
+ pblocktemplate = std::make_unique<CBlockTemplate>();
CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction. It is skipped by the
@@ -240,7 +240,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
Ticks<MillisecondsDouble>(time_2 - time_1),
Ticks<MillisecondsDouble>(time_2 - time_start));
- return std::move(pblocktemplate);
+ return util::NotNull{std::move(pblocktemplate)};
}
bool BlockAssembler::TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const
### src/node/miner.h
@@ -13,6 +13,7 @@
#include <threadsafety.h>
#include <txmempool.h>
#include <util/feefrac.h>
+#include <util/not_null.h>
#include <cstdint>
#include <memory>
@@ -73,7 +74,7 @@ class BlockAssembler
BlockCreateOptions create_options);
/** Construct a new block template */
- std::unique_ptr<CBlockTemplate> CreateNewBlock();
+ util::NotNullUniquePtr<CBlockTemplate> CreateNewBlock();
/** The number of transactions in the last assembled block (excluding coinbase transaction) */
inline static std::optional<int64_t> m_last_block_num_txs{};
### src/node/txdownloadman.h
@@ -8,6 +8,7 @@
#include <net.h>
#include <node/txorphanage.h>
#include <policy/packages.h>
+#include <util/not_null.h>
#include <cstdint>
#include <memory>
@@ -113,7 +114,7 @@ struct RejectedTxTodo
* external mutex.
*/
class TxDownloadManager {
- const std::unique_ptr<TxDownloadManagerImpl> m_impl;
+ const util::NotNullUniquePtr<TxDownloadManagerImpl> m_impl;
public:
explicit TxDownloadManager(const TxDownloadOptions& options);
### src/node/txreconciliation.h
@@ -7,6 +7,7 @@
#include <net.h>
#include <sync.h>
+#include <util/not_null.h>
#include <memory>
#include <tuple>
@@ -52,7 +53,7 @@ class TxReconciliationTracker
{
private:
class Impl;
- const std::unique_ptr<Impl> m_impl;
+ const util::NotNullUniquePtr<Impl> m_impl;
public:
explicit TxReconciliationTracker(uint32_t recon_version);
### src/policy/fees/mempool_estimator.cpp
@@ -398,7 +398,6 @@ util::Expected<FeeRateEstimation, FeeRateEstimationError> MemPoolFeeRateEstimato
node::BlockCreateOptions options;
options.test_block_validity = false;
const auto blocktemplate = WITH_LOCK(::cs_main, return (node::BlockAssembler{m_chainman.CurrentChainstate(), &m_mempool, options}).CreateNewBlock());
- if (!blocktemplate) return EstimationError(strprintf("%s: Failed to create block template for fee rate estimation", FeeRateEstimatorTypeToString(estimator_type)));
// Sort again because the rounding up when converting from weight to vsize may cause slight misorder.
std::sort(blocktemplate->m_package_feerates.begin(), blocktemplate->m_package_feerates.end(), [](const auto& a, const auto& b) { return ByRatio{a} > ByRatio{b}; });
const auto percentiles = CalculateMaxWeightPercentiles(blocktemplate->m_package_feerates);
### src/rpc/mining.cpp
@@ -195,8 +195,7 @@ static UniValue generateBlocks(ChainstateManager& chainman, node::BlockTemplateM
{
UniValue blockHashes(UniValue::VARR);
while (nGenerate > 0 && !chainman.m_interrupt) {
- std::unique_ptr<node::CBlockTemplate> block_template{block_template_manager.CreateNewTemplate({.coinbase_output_script = coinbase_output_script})};
- CHECK_NONFATAL(block_template);
+ auto block_template{block_template_manager.CreateNewTemplate({.coinbase_output_script = coinbase_output_script})};
std::shared_ptr<const CBlock> block_out;
if (!GenerateBlock(chainman, CBlock{block_template->block}, nMaxTries, block_out, /*process_new_block=*/true)) {
@@ -407,8 +406,7 @@ static RPCMethod generateblock()
{
LOCK(chainman.GetMutex());
{
- std::unique_ptr<node::CBlockTemplate> block_template{block_template_manager.CreateNewTemplate({.use_mempool = false, .coinbase_output_script = coinbase_output_script})};
- CHECK_NONFATAL(block_template);
+ auto block_template{block_template_manager.CreateNewTemplate({.use_mempool = false, .coinbase_output_script = coinbase_output_script})};
block = block_template->block;
}
### src/test/coinsviewoverlay_tests.cpp
@@ -25,7 +25,7 @@ namespace {
util::NotNullSharedPtr<ThreadPool> MakeStartedThreadPool()
{
- util::NotNull pool{std::make_shared<ThreadPool>("fetch_test")};
+ auto pool{util::MakeNotNullShared<ThreadPool>("fetch_test")};
pool->Start(DEFAULT_PREVOUTFETCH_THREADS);
return pool;
}
@@ -287,7 +287,7 @@ BOOST_AUTO_TEST_CASE(fetch_unstarted_thread_pool)
CCoinsViewDB db{{.path = "", .cache_bytes = 1_MiB, .memory_only = true}, {}};
CCoinsViewCache main_cache{&db};
PopulateView(block, main_cache);
- util::NotNull thread_pool{std::make_shared<ThreadPool>("fetch_none")};
+ auto thread_pool{util::MakeNotNullShared<ThreadPool>("fetch_none")};
CoinsViewOverlay view{&main_cache, thread_pool};
const auto reset_guard{view.StartFetching(block)};
CheckCache(block, view);
@@ -301,7 +301,7 @@ BOOST_AUTO_TEST_CASE(fetch_interrupted_thread_pool_uses_normal_lookup)
CCoinsViewCache main_cache{&db};
PopulateView(block, main_cache);
- util::NotNull thread_pool{std::make_shared<ThreadPool>("fetch_intr")};
+ auto thread_pool{util::MakeNotNullShared<ThreadPool>("fetch_intr")};
thread_pool->Start(DEFAULT_PREVOUTFETCH_THREADS);
thread_pool->Interrupt();
CoinsViewOverlay view{&main_cache, thread_pool};
### src/test/fuzz/coins_view.cpp
@@ -83,7 +83,7 @@ class MutationGuardCoinsViewCache final : public CCoinsViewCache
// Reuse a single global thread pool across fuzz iterations. Creating and destroying a pool every
// iteration leaks memory, since iterations can run faster than the OS can tear down the threads.
-util::NotNull g_thread_pool{std::make_shared<ThreadPool>("view_fuzz")};
+auto g_thread_pool{util::MakeNotNullShared<ThreadPool>("view_fuzz")};
void StartPoolIfNeeded()
{
### src/test/fuzz/coinscache_sim.cpp
@@ -206,7 +206,7 @@ struct OverlayFetchScope
// Reuse a single global thread pool across fuzz iterations. Creating and destroying a pool every
// iteration leaks memory, since iterations can run faster than the OS can tear down the threads.
-util::NotNull g_thread_pool{std::make_shared<ThreadPool>("cache_fuzz")};
+auto g_thread_pool{util::MakeNotNullShared<ThreadPool>("cache_fuzz")};
void StartPoolIfNeeded()
{
### src/test/fuzz/util/check_globals.h
@@ -5,6 +5,8 @@
#ifndef BITCOIN_TEST_FUZZ_UTIL_CHECK_GLOBALS_H
#define BITCOIN_TEST_FUZZ_UTIL_CHECK_GLOBALS_H
+#include <util/not_null.h>
+
#include <atomic>
#include <memory>
#include <optional>
@@ -16,7 +18,7 @@ struct CheckGlobalsImpl;
struct CheckGlobals {
CheckGlobals();
~CheckGlobals();
- std::unique_ptr<CheckGlobalsImpl> m_impl;
+ util::NotNullUniquePtr<CheckGlobalsImpl> m_impl;
};
#endif // BITCOIN_TEST_FUZZ_UTIL_CHECK_GLOBALS_H
### src/test/miner_tests.cpp
@@ -957,7 +957,6 @@ BOOST_AUTO_TEST_CASE(block_template_manager)
BlockCreateOptions options;
options.use_mempool = false;
auto block_template = block_template_manager.CreateNewTemplate(options);
- BOOST_REQUIRE(block_template);
const CBlock& block{block_template->block};
// Without the mempool the template holds only the coinbase, and the per-tx
// fee/sigops vectors exclude it.
### src/test/peerman_tests.cpp
@@ -34,7 +34,6 @@ static void mineBlock(node::NodeContext& node, FakeNodeClock& clock, std::chrono
clock.set(block_time); // update time so the block is created with it
auto& block_template_manager{*Assert(node.block_template_manager)};
auto block_template{block_template_manager.CreateNewTemplate({})};
- BOOST_REQUIRE(block_template);
CBlock block{block_template->block};
while (!CheckProofOfWork(block.GetHash(), block.nBits, node.chainman->GetConsensus())) ++block.nNonce;
block.fChecked = true; // little speedup
### src/test/util/mining.cpp
@@ -93,7 +93,7 @@ bool BuildChain(const NodeContext& node, const CBlockIndex* pindex,
.use_mempool = false,
.coinbase_output_script = coinbase_script_pub_key,
})};
- CBlock block{Assert(block_template)->block};
+ CBlock block{block_template->block};
// The template is built on the active tip, so repoint it at pindex and
// redo the fields that depend on the predecessor.
@@ -162,7 +162,7 @@ std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node,
{
auto& block_template_manager = *Assert(node.block_template_manager);
auto block_template = block_template_manager.CreateNewTemplate(assembler_options);
- auto block = std::make_shared<CBlock>(Assert(block_template)->block);
+ auto block = std::make_shared<CBlock>(block_template->block);
LOCK(cs_main);
block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1;
### src/test/util/setup_common.cpp
@@ -462,7 +462,6 @@ CBlock TestChain100Setup::CreateBlock(
.use_mempool = false,
.coinbase_output_script = scriptPubKey,
})};
- Assert(block_template);
CBlock block{block_template->block};
Assert(block.vtx.size() == 1);
### src/test/util_not_null_tests.cpp
@@ -41,6 +41,8 @@ concept NotNullType = requires { typename util::NotNull<T>; };
BOOST_AUTO_TEST_CASE(check_ctor_ref)
{
+ static_assert(NotNullType<std::shared_ptr<int>>);
+
static_assert(!NotNullType<std::shared_ptr<int>&>);
static_assert(!NotNullType<int*&>);
}
@@ -77,6 +79,9 @@ BOOST_AUTO_TEST_CASE(check_ctor_conv)
// NNPtr from NNUniqPtr may throw:
static_assert(!std::is_nothrow_constructible_v<NNPtr, NNUniqPtr&&>);
static_assert(std::is_constructible_v<NNPtr, NNUniqPtr&&>);
+ // NNUniqPtr -> NNPtr is implicit, just like the underlying conversion:
+ static_assert(std::convertible_to<NNUniqPtr&&, NNPtr>);
+ static_assert(std::convertible_to<UniqPtr&&, Ptr>);
// Extraction is implicit:
static_assert(std::convertible_to<NNUniqPtr&&, UniqPtr>);
@@ -163,6 +168,9 @@ BOOST_AUTO_TEST_CASE(check_derived)
util::NotNull p{std::make_shared<MyDerived>()};
util::NotNull q{std::make_shared<MyBase>()};
+ // Conversion is implicit:
+ static_assert(std::convertible_to<const decltype(p)&, decltype(q)>);
+ static_assert(std::is_assignable_v<decltype(q)&, const decltype(p)&>);
q = p;
const bool same_ptr{q == p};
BOOST_CHECK(same_ptr);
### src/test/validation_block_tests.cpp
@@ -85,7 +85,6 @@ std::shared_ptr<CBlock> MinerTestingSetup::Block(const uint256& prev_hash)
auto block_template{block_template_manager.CreateNewTemplate({
.coinbase_output_script = CScript{} << i++ << OP_TRUE,
})};
- BOOST_REQUIRE(block_template);
auto pblock = std::make_shared<CBlock>(block_template->block);
pblock->hashPrevBlock = prev_hash;
pblock->nTime = ++time;
@@ -355,7 +354,6 @@ BOOST_AUTO_TEST_CASE(witness_commitment_index)
auto block_template{block_template_manager.CreateNewTemplate({
.coinbase_output_script = pubKey,
})};
- BOOST_REQUIRE(block_template);
CBlock pblock{block_template->block};
CTxOut witness;
### src/txmempool.h
@@ -727,7 +727,7 @@ class CTxMemPool
{
Assume(!m_have_changeset);
m_have_changeset = true;
- return util::NotNull{std::make_unique<ChangeSet>(this)};
+ return util::MakeNotNullUnique<ChangeSet>(this);
}
bool m_have_changeset GUARDED_BY(cs){false};
### src/txrequest.h
@@ -8,6 +8,7 @@
#include <primitives/transaction.h>
#include <net.h>
#include <uint256.h>
+#include <util/not_null.h>
#include <chrono>
#include <cstdint>
@@ -100,7 +101,7 @@
class TxRequestTracker {
// Avoid littering this header file with implementation details.
class Impl;
- const std::unique_ptr<Impl> m_impl;
+ const util::NotNullUniquePtr<Impl> m_impl;
public:
//! Construct a TxRequestTracker.
### src/util/not_null.h
@@ -25,7 +25,7 @@ namespace util {
/// used. So instead of passing an existing pointer into NotNull, it is
/// recommended to use the type when creating the smart pointer. E.g.:
///
-/// util::NotNull p{std::make_shared<Thing>()};
+/// auto p{util::MakeNotNullShared<Thing>()};
///
/// This makes it obvious that a pointer really is not null and that the
/// constructor will not fail.
@@ -119,9 +119,23 @@ NotNull(T) -> NotNull<T>;
template <typename T, typename Deleter = std::default_delete<T>>
using NotNullUniquePtr = NotNull<std::unique_ptr<T, Deleter>>;
+/// Like std::make_unique, but returns a NotNullUniquePtr.
+template <typename T, typename... Args>
+NotNullUniquePtr<T> MakeNotNullUnique(Args&&... args)
+{
+ return NotNull{std::make_unique<T>(std::forward<Args>(args)...)};
+}
+
template <typename T>
using NotNullSharedPtr = NotNull<std::shared_ptr<T>>;
+/// Like std::make_shared, but returns a NotNullSharedPtr.
+template <typename T, typename... Args>
+NotNullSharedPtr<T> MakeNotNullShared(Args&&... args)
+{
+ return NotNull{std::make_shared<T>(std::forward<Args>(args)...)};
+}
+
} // namespace util
template <class T>
### src/validation.cpp
@@ -1845,7 +1845,7 @@ void CoinsViews::InitCache(int32_t prevoutfetch_threads)
{
AssertLockHeld(::cs_main);
m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
- util::NotNull thread_pool{std::make_shared<ThreadPool>("prevout")};
+ auto thread_pool{util::MakeNotNullShared<ThreadPool>("prevout")};
if (prevoutfetch_threads > 0) {
thread_pool->Start(prevoutfetch_threads);
LogInfo("Block input prevout fetching uses %d additional threads", prevoutfetch_threads);
### src/validationinterface.cpp
@@ -95,7 +95,7 @@ class ValidationSignalsImpl
};
ValidationSignals::ValidationSignals(std::unique_ptr<util::TaskRunnerInterface> task_runner)
- : m_internals{std::make_unique<ValidationSignalsImpl>(std::move(task_runner))} {}
+ : m_internals{util::MakeNotNullUnique<ValidationSignalsImpl>(std::move(task_runner))} {}
ValidationSignals::~ValidationSignals() = default;
### src/validationinterface.h
@@ -10,6 +10,7 @@
#include <primitives/transaction.h>
#include <sync.h>
#include <uint256.h>
+#include <util/not_null.h>
#include <cstddef>
#include <cstdint>
@@ -166,9 +167,10 @@ class CValidationInterface {
};
class ValidationSignalsImpl;
-class ValidationSignals {
+class ValidationSignals
+{
private:
- std::unique_ptr<ValidationSignalsImpl> m_internals;
+ util::NotNullUniquePtr<ValidationSignalsImpl> m_internals;
public:
// The task runner will block validation if it calls its insert method'sWhy this scored 19/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.