Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

backport: Use std::unique_ptr (C++11) where possible (bitcoin #11043) #1165

Open
wants to merge 14 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions src/httprpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
/* Pre-base64-encoded authentication token */
static std::string strRPCUserColonPass;
/* Stored RPC timer interface (for unregistration) */
static HTTPRPCTimerInterface* httpRPCTimerInterface = nullptr;
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;

static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
{
Expand Down Expand Up @@ -239,8 +239,8 @@ bool StartHTTPRPC()
RegisterHTTPHandler("/wallet/", false, HTTPReq_JSONRPC);
#endif
assert(EventBase());
httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());
RPCSetTimerInterface(httpRPCTimerInterface);
httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(EventBase());
RPCSetTimerInterface(httpRPCTimerInterface.get());
return true;
}

Expand All @@ -254,8 +254,7 @@ void StopHTTPRPC()
LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
UnregisterHTTPHandler("/", true);
if (httpRPCTimerInterface) {
RPCUnsetTimerInterface(httpRPCTimerInterface);
delete httpRPCTimerInterface;
httpRPCTimerInterface = nullptr;
RPCUnsetTimerInterface(httpRPCTimerInterface.get());
httpRPCTimerInterface.reset();
}
}
38 changes: 15 additions & 23 deletions src/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ class CCoinsViewErrorCatcher final : public CCoinsViewBacked
// Writes do not need similar protection, as failure to write is handled by the caller.
};

static CCoinsViewErrorCatcher *pcoinscatcher = nullptr;
static std::unique_ptr<CCoinsViewErrorCatcher> pcoinscatcher;
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;

void Interrupt(boost::thread_group& threadGroup)
Expand Down Expand Up @@ -251,17 +251,6 @@ void PrepareShutdown()
if (pcoinsTip != nullptr) {
FlushStateToDisk();
}
delete pcoinsTip;
pcoinsTip = nullptr;

delete pcoinscatcher;
pcoinscatcher = nullptr;

delete pcoinsdbview;
pcoinsdbview = nullptr;

delete pblocktree;
pblocktree = nullptr;

/** RVN START */
delete passets;
Expand Down Expand Up @@ -319,6 +308,10 @@ void PrepareShutdown()
pDistributeSnapshotDb = nullptr;

/** RVN END */
pcoinsTip.reset();
pcoinscatcher.reset();
pcoinsdbview.reset();
pblocktree.reset();
}
#ifdef ENABLE_WALLET
StopWallets();
Expand Down Expand Up @@ -1536,11 +1529,11 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pcoinscatcher;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReset, dbMaxFileSize);
pcoinsTip.reset();
pcoinsdbview.reset();
pcoinscatcher.reset();
pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));


/** RVN START */
{
Expand Down Expand Up @@ -1623,7 +1616,6 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
}
/** RVN END */

if (fReset) {
pblocktree->WriteReindexing(true);
//If we're reindexing in prune mode, wipe away unusable block files and all undo data files
Expand Down Expand Up @@ -1691,8 +1683,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// At this point we're either in reindex or we've loaded a useful
// block tree into mapBlockIndex!

pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState);
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState));
pcoinscatcher.reset(new CCoinsViewErrorCatcher(pcoinsdbview.get()));

// If necessary, upgrade from older database format.
// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
Expand All @@ -1702,13 +1694,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}

// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!ReplayBlocks(chainparams, pcoinsdbview)) {
if (!ReplayBlocks(chainparams, pcoinsdbview.get())) {
strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
break;
}

// The on-disk coinsdb is now in a good state, create the cache
pcoinsTip = new CCoinsViewCache(pcoinscatcher);
pcoinsTip.reset(new CCoinsViewCache(pcoinscatcher.get()));

bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull();
if (!is_coinsview_empty) {
Expand Down Expand Up @@ -1750,7 +1742,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
}

if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview.get(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
strLoadError = _("Corrupted block database detected");
break;
Expand Down
25 changes: 8 additions & 17 deletions src/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1549,22 +1549,20 @@ void ThreadMapPort()

void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = nullptr;
static std::unique_ptr<boost::thread> upnp_thread;

if (fUseUPnP)
{
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
upnp_thread.reset(new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)));
}
else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = nullptr;
upnp_thread.reset();
}
}

Expand Down Expand Up @@ -2254,8 +2252,6 @@ CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSe
nLastNodeId = 0;
nSendBufferMaxSize = 0;
nReceiveFloodSize = 0;
semOutbound = nullptr;
semAddnode = nullptr;
flagInterruptMsgProc = false;
SetTryNewOutboundPeer(false);

Expand Down Expand Up @@ -2367,11 +2363,11 @@ bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)

if (semOutbound == nullptr) {
// initialize semaphore
semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
semOutbound = MakeUnique<CSemaphore>(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
}
if (semAddnode == nullptr) {
// initialize semaphore
semAddnode = new CSemaphore(nMaxAddnode);
semAddnode = MakeUnique<CSemaphore>(nMaxAddnode);
}

//
Expand Down Expand Up @@ -2502,10 +2498,8 @@ void CConnman::Stop()
vNodes.clear();
vNodesDisconnected.clear();
vhListenSocket.clear();
delete semOutbound;
semOutbound = nullptr;
delete semAddnode;
semAddnode = nullptr;
semOutbound.reset();
semAddnode.reset();
}

void CConnman::DeleteNode(CNode* pnode)
Expand Down Expand Up @@ -2791,7 +2785,7 @@ CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn
nNextInvSend = 0;
fRelayTxes = false;
fSentAddr = false;
pfilter = new CBloomFilter();
pfilter = MakeUnique<CBloomFilter>();
timeLastMempoolReq = 0;
nLastBlockTime = 0;
nLastTXTime = 0;
Expand Down Expand Up @@ -2824,9 +2818,6 @@ CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn
CNode::~CNode()
{
CloseSocket(hSocket);

if (pfilter)
delete pfilter;
}

void CNode::AskFor(const CInv& inv)
Expand Down
6 changes: 3 additions & 3 deletions src/net.h
Original file line number Diff line number Diff line change
Expand Up @@ -402,8 +402,8 @@ class CConnman
/** Services this instance offers */
ServiceFlags nLocalServices;

CSemaphore *semOutbound;
CSemaphore *semAddnode;
std::unique_ptr<CSemaphore> semOutbound;
std::unique_ptr<CSemaphore> semAddnode;
int nMaxConnections;
int nMaxOutbound;
int nMaxAddnode;
Expand Down Expand Up @@ -658,7 +658,7 @@ class CNode
bool fSentAddr;
CSemaphoreGrant grantOutbound;
CCriticalSection cs_filter;
CBloomFilter* pfilter;
std::unique_ptr<CBloomFilter> pfilter;
std::atomic<int> nRefCount;

const uint64_t nKeyedNetGroup;
Expand Down
10 changes: 4 additions & 6 deletions src/net_processing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2192,7 +2192,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr

if (!AlreadyHave(inv) &&
AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
mempool.check(pcoinsTip);
mempool.check(pcoinsTip.get());
RelayTransaction(tx, connman);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
vWorkQueue.emplace_back(inv.hash, i);
Expand Down Expand Up @@ -2259,7 +2259,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
recentRejects->insert(orphanHash);
}
}
mempool.check(pcoinsTip);
mempool.check(pcoinsTip.get());
}
}

Expand Down Expand Up @@ -2851,8 +2851,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
else
{
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter(filter);
pfrom->pfilter.reset(new CBloomFilter(filter));
pfrom->pfilter->UpdateEmptyFull();
pfrom->fRelayTxes = true;
}
Expand Down Expand Up @@ -2888,8 +2887,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
{
LOCK(pfrom->cs_filter);
if (pfrom->GetLocalServices() & NODE_BLOOM) {
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter();
pfrom->pfilter.reset(new CBloomFilter());
}
pfrom->fRelayTxes = true;
}
Expand Down
24 changes: 9 additions & 15 deletions src/policy/fees.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -549,16 +549,13 @@ CBlockPolicyEstimator::CBlockPolicyEstimator()
bucketMap[INF_FEERATE] = bucketIndex;
assert(bucketMap.size() == buckets.size());

feeStats = new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE);
shortStats = new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE);
longStats = new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE);
feeStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
shortStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
longStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
}

CBlockPolicyEstimator::~CBlockPolicyEstimator()
{
delete feeStats;
delete shortStats;
delete longStats;
}

void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, bool validFeeEstimate)
Expand Down Expand Up @@ -691,16 +688,16 @@ CFeeRate CBlockPolicyEstimator::estimateRawFee(int confTarget, double successThr
double sufficientTxs = SUFFICIENT_FEETXS;
switch (horizon) {
case FeeEstimateHorizon::SHORT_HALFLIFE: {
stats = shortStats;
stats = shortStats.get();
sufficientTxs = SUFFICIENT_TXS_SHORT;
break;
}
case FeeEstimateHorizon::MED_HALFLIFE: {
stats = feeStats;
stats = feeStats.get();
break;
}
case FeeEstimateHorizon::LONG_HALFLIFE: {
stats = longStats;
stats = longStats.get();
break;
}
default: {
Expand Down Expand Up @@ -1003,12 +1000,9 @@ bool CBlockPolicyEstimator::Read(CAutoFile& filein)
}

// Destroy old TxConfirmStats and point to new ones that already reference buckets and bucketMap
delete feeStats;
delete shortStats;
delete longStats;
feeStats = fileFeeStats.release();
shortStats = fileShortStats.release();
longStats = fileLongStats.release();
feeStats = std::move(fileFeeStats);
shortStats = std::move(fileShortStats);
longStats = std::move(fileLongStats);

nBestSeenHeight = nFileBestSeenHeight;
historicalFirst = nFileHistoricalFirst;
Expand Down
6 changes: 3 additions & 3 deletions src/policy/fees.h
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,9 @@ class CBlockPolicyEstimator
std::map<uint256, TxStatsInfo> mapMemPoolTxs;

/** Classes to track historical data on transaction confirmations */
TxConfirmStats* feeStats;
TxConfirmStats* shortStats;
TxConfirmStats* longStats;
std::unique_ptr<TxConfirmStats> feeStats;
std::unique_ptr<TxConfirmStats> shortStats;
std::unique_ptr<TxConfirmStats> longStats;

unsigned int trackedTxs;
unsigned int untrackedTxs;
Expand Down
3 changes: 0 additions & 3 deletions src/qt/test/rpcnestedtests.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ class RPCNestedTests : public QObject

private Q_SLOTS:
void rpcNestedTests();

private:
CCoinsViewDB *pcoinsdbview;
};

#endif // RAVEN_QT_TEST_RPC_NESTED_TESTS_H
4 changes: 2 additions & 2 deletions src/rpc/assets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
void CheckRestrictedAssetTransferInputs(const CWalletTx& transaction, const std::string& asset_name) {
// Do a validity check before commiting the transaction
if (IsAssetNameAnRestricted(asset_name)) {
if (pcoinsTip && passets) {
if (pcoinsTip.get() && passets) {
for (auto input : transaction.tx->vin) {
const COutPoint &prevout = input.prevout;
const Coin &coin = pcoinsTip->AccessCoin(prevout);
Expand Down Expand Up @@ -1802,7 +1802,7 @@ UniValue getcacheinfo(const JSONRPCRequest& request)
if (!currentActiveAssetCache)
throw JSONRPCError(RPC_VERIFY_ERROR, "asset cache is null");

if (!pcoinsTip)
if (!pcoinsTip.get())
throw JSONRPCError(RPC_VERIFY_ERROR, "coins tip cache is null");

if (!passetsCache)
Expand Down
6 changes: 3 additions & 3 deletions src/rpc/blockchain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1206,7 +1206,7 @@ UniValue gettxoutsetinfo(const JSONRPCRequest& request)

CCoinsStats stats;
FlushStateToDisk();
if (GetUTXOStats(pcoinsdbview, stats)) {
if (GetUTXOStats(pcoinsdbview.get(), stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
Expand Down Expand Up @@ -1274,7 +1274,7 @@ UniValue gettxout(const JSONRPCRequest& request)
Coin coin;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip, mempool);
CCoinsViewMemPool view(pcoinsTip.get(), mempool);
if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
return NullUniValue;
}
Expand Down Expand Up @@ -1326,7 +1326,7 @@ UniValue verifychain(const JSONRPCRequest& request)
if (!request.params[1].isNull())
nCheckDepth = request.params[1].get_int();

return CVerifyDB().VerifyDB(GetParams(), pcoinsTip, nCheckLevel, nCheckDepth);
return CVerifyDB().VerifyDB(GetParams(), pcoinsTip.get(), nCheckLevel, nCheckDepth);
}

/** Implementation of IsSuperMajority with better feedback */
Expand Down
Loading