Merge #10483: scripted-diff: Use the C++11 keyword nullptr to denote the pointer literal instead of the macro NULL

90d4d89 scripted-diff: Use the C++11 keyword nullptr to denote the pointer literal instead of the macro NULL (practicalswift)

Pull request description:

  Since C++11 the macro `NULL` may be:
  * an integer literal with value zero, or
  * a prvalue of type `std::nullptr_t`

  By using the C++11 keyword `nullptr` we are guaranteed a prvalue of type `std::nullptr_t`.

  For a more thorough discussion, see "A name for the null pointer: nullptr" (Sutter &
  Stroustrup), http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf

  With this patch applied there are no `NULL` macro usages left in the repo:

  ```
  $ git grep NULL -- "*.cpp" "*.h" | egrep -v '(/univalue/|/secp256k1/|/leveldb/|_NULL|NULLDUMMY|torcontrol.*NULL|NULL cert)' | wc -l
  0
  ```

  The road towards `nullptr` (C++11) is split into two PRs:
  * `NULL` → `nullptr` is handled in PR #10483 (scripted, this PR)
  * `0` → `nullptr` is handled in PR #10645 (manual)

Tree-SHA512: 3c395d66f2ad724a8e6fed74b93634de8bfc0c0eafac94e64e5194c939499fefd6e68f047de3083ad0b4eff37df9a8a3a76349aa17d55eabbd8e0412f140a297
This commit is contained in:
Wladimir J. van der Laan 2017-08-14 16:20:49 +02:00
commit ce74799a3c
No known key found for this signature in database
GPG key ID: 1E4AED62986CD25D
104 changed files with 563 additions and 563 deletions

View file

@ -69,13 +69,13 @@ CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId)
{ {
std::map<CNetAddr, int>::iterator it = mapAddr.find(addr); std::map<CNetAddr, int>::iterator it = mapAddr.find(addr);
if (it == mapAddr.end()) if (it == mapAddr.end())
return NULL; return nullptr;
if (pnId) if (pnId)
*pnId = (*it).second; *pnId = (*it).second;
std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second); std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
if (it2 != mapInfo.end()) if (it2 != mapInfo.end())
return &(*it2).second; return &(*it2).second;
return NULL; return nullptr;
} }
CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId) CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId)

View file

@ -220,11 +220,11 @@ protected:
FastRandomContext insecure_rand; FastRandomContext insecure_rand;
//! Find an entry. //! Find an entry.
CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL); CAddrInfo* Find(const CNetAddr& addr, int *pnId = nullptr);
//! find an entry, creating it if necessary. //! find an entry, creating it if necessary.
//! nTime and nServices of the found node are updated, if necessary. //! nTime and nServices of the found node are updated, if necessary.
CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL); CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = nullptr);
//! Swap two elements in vRandom. //! Swap two elements in vRandom.
void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2); void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);

View file

@ -283,7 +283,7 @@ public:
* complexities of the sign bit and using base 256 are probably an * complexities of the sign bit and using base 256 are probably an
* implementation accident. * implementation accident.
*/ */
arith_uint256& SetCompact(uint32_t nCompact, bool *pfNegative = NULL, bool *pfOverflow = NULL); arith_uint256& SetCompact(uint32_t nCompact, bool *pfNegative = nullptr, bool *pfOverflow = nullptr);
uint32_t GetCompact(bool fNegative = false) const; uint32_t GetCompact(bool fNegative = false) const;
friend uint256 ArithToUint256(const arith_uint256 &); friend uint256 ArithToUint256(const arith_uint256 &);

View file

@ -37,7 +37,7 @@ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
while (*psz && !isspace(*psz)) { while (*psz && !isspace(*psz)) {
// Decode base58 character // Decode base58 character
const char* ch = strchr(pszBase58, *psz); const char* ch = strchr(pszBase58, *psz);
if (ch == NULL) if (ch == nullptr)
return false; return false;
// Apply "b256 = b256 * 58 + ch". // Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58; int carry = ch - pszBase58;

View file

@ -26,7 +26,7 @@
/** /**
* Encode a byte sequence as a base58-encoded string. * Encode a byte sequence as a base58-encoded string.
* pbegin and pend cannot be NULL, unless both are. * pbegin and pend cannot be nullptr, unless both are.
*/ */
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend); std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend);
@ -38,7 +38,7 @@ std::string EncodeBase58(const std::vector<unsigned char>& vch);
/** /**
* Decode a base58-encoded string (psz) into a byte vector (vchRet). * Decode a base58-encoded string (psz) into a byte vector (vchRet).
* return true if decoding is successful. * return true if decoding is successful.
* psz cannot be NULL. * psz cannot be nullptr.
*/ */
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet); bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet);

View file

@ -17,7 +17,7 @@ benchmark::BenchRunner::BenchmarkMap &benchmark::BenchRunner::benchmarks() {
static double gettimedouble(void) { static double gettimedouble(void) {
struct timeval tv; struct timeval tv;
gettimeofday(&tv, NULL); gettimeofday(&tv, nullptr);
return tv.tv_usec * 0.000001 + tv.tv_sec; return tv.tv_usec * 0.000001 + tv.tv_sec;
} }

View file

@ -161,8 +161,8 @@ static void http_request_done(struct evhttp_request *req, void *ctx)
{ {
HTTPReply *reply = static_cast<HTTPReply*>(ctx); HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) { if (req == nullptr) {
/* If req is NULL, it means an error occurred while connecting: the /* If req is nullptr, it means an error occurred while connecting: the
* error code will have been passed to http_error_cb. * error code will have been passed to http_error_cb.
*/ */
reply->status = 0; reply->status = 0;
@ -210,7 +210,7 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
HTTPReply response; HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response); raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL) if (req == nullptr)
throw std::runtime_error("create http request failed"); throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb); evhttp_request_set_error_cb(req.get(), http_error_cb);
@ -370,7 +370,7 @@ int CommandLineRPC(int argc, char *argv[])
nRet = EXIT_FAILURE; nRet = EXIT_FAILURE;
} }
catch (...) { catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()"); PrintExceptionContinue(nullptr, "CommandLineRPC()");
throw; throw;
} }
@ -397,7 +397,7 @@ int main(int argc, char* argv[])
PrintExceptionContinue(&e, "AppInitRPC()"); PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE; return EXIT_FAILURE;
} catch (...) { } catch (...) {
PrintExceptionContinue(NULL, "AppInitRPC()"); PrintExceptionContinue(nullptr, "AppInitRPC()");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -408,7 +408,7 @@ int main(int argc, char* argv[])
catch (const std::exception& e) { catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()"); PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) { } catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()"); PrintExceptionContinue(nullptr, "CommandLineRPC()");
} }
return ret; return ret;
} }

View file

@ -822,7 +822,7 @@ static int CommandLineRawTx(int argc, char* argv[])
nRet = EXIT_FAILURE; nRet = EXIT_FAILURE;
} }
catch (...) { catch (...) {
PrintExceptionContinue(NULL, "CommandLineRawTx()"); PrintExceptionContinue(nullptr, "CommandLineRawTx()");
throw; throw;
} }
@ -845,7 +845,7 @@ int main(int argc, char* argv[])
PrintExceptionContinue(&e, "AppInitRawTx()"); PrintExceptionContinue(&e, "AppInitRawTx()");
return EXIT_FAILURE; return EXIT_FAILURE;
} catch (...) { } catch (...) {
PrintExceptionContinue(NULL, "AppInitRawTx()"); PrintExceptionContinue(nullptr, "AppInitRawTx()");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -856,7 +856,7 @@ int main(int argc, char* argv[])
catch (const std::exception& e) { catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRawTx()"); PrintExceptionContinue(&e, "CommandLineRawTx()");
} catch (...) { } catch (...) {
PrintExceptionContinue(NULL, "CommandLineRawTx()"); PrintExceptionContinue(nullptr, "CommandLineRawTx()");
} }
return ret; return ret;
} }

View file

@ -170,7 +170,7 @@ bool AppInit(int argc, char* argv[])
catch (const std::exception& e) { catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInit()"); PrintExceptionContinue(&e, "AppInit()");
} catch (...) { } catch (...) {
PrintExceptionContinue(NULL, "AppInit()"); PrintExceptionContinue(nullptr, "AppInit()");
} }
if (!fRet) if (!fRet)

View file

@ -9,7 +9,7 @@
* CChain implementation * CChain implementation
*/ */
void CChain::SetTip(CBlockIndex *pindex) { void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == NULL) { if (pindex == nullptr) {
vChain.clear(); vChain.clear();
return; return;
} }
@ -49,8 +49,8 @@ CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
} }
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex == NULL) { if (pindex == nullptr) {
return NULL; return nullptr;
} }
if (pindex->nHeight > Height()) if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height()); pindex = pindex->GetAncestor(Height());
@ -63,7 +63,7 @@ CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const
{ {
std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime,
[](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; });
return (lower == vChain.end() ? NULL : *lower); return (lower == vChain.end() ? nullptr : *lower);
} }
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
@ -83,14 +83,14 @@ int static inline GetSkipHeight(int height) {
CBlockIndex* CBlockIndex::GetAncestor(int height) CBlockIndex* CBlockIndex::GetAncestor(int height)
{ {
if (height > nHeight || height < 0) if (height > nHeight || height < 0)
return NULL; return nullptr;
CBlockIndex* pindexWalk = this; CBlockIndex* pindexWalk = this;
int heightWalk = nHeight; int heightWalk = nHeight;
while (heightWalk > height) { while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk); int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1); int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != NULL && if (pindexWalk->pskip != nullptr &&
(heightSkip == height || (heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 && (heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height)))) { heightSkipPrev >= height)))) {
@ -150,7 +150,7 @@ int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& fr
} }
/** Find the last common ancestor two blocks have. /** Find the last common ancestor two blocks have.
* Both pa and pb must be non-NULL. */ * Both pa and pb must be non-nullptr. */
const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) {
if (pa->nHeight > pb->nHeight) { if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight); pa = pa->GetAncestor(pb->nHeight);

View file

@ -221,9 +221,9 @@ public:
void SetNull() void SetNull()
{ {
phashBlock = NULL; phashBlock = nullptr;
pprev = NULL; pprev = nullptr;
pskip = NULL; pskip = nullptr;
nHeight = 0; nHeight = 0;
nFile = 0; nFile = 0;
nDataPos = 0; nDataPos = 0;
@ -437,20 +437,20 @@ private:
std::vector<CBlockIndex*> vChain; std::vector<CBlockIndex*> vChain;
public: public:
/** Returns the index entry for the genesis block of this chain, or NULL if none. */ /** Returns the index entry for the genesis block of this chain, or nullptr if none. */
CBlockIndex *Genesis() const { CBlockIndex *Genesis() const {
return vChain.size() > 0 ? vChain[0] : NULL; return vChain.size() > 0 ? vChain[0] : nullptr;
} }
/** Returns the index entry for the tip of this chain, or NULL if none. */ /** Returns the index entry for the tip of this chain, or nullptr if none. */
CBlockIndex *Tip() const { CBlockIndex *Tip() const {
return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL; return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
} }
/** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */ /** Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */
CBlockIndex *operator[](int nHeight) const { CBlockIndex *operator[](int nHeight) const {
if (nHeight < 0 || nHeight >= (int)vChain.size()) if (nHeight < 0 || nHeight >= (int)vChain.size())
return NULL; return nullptr;
return vChain[nHeight]; return vChain[nHeight];
} }
@ -465,12 +465,12 @@ public:
return (*this)[pindex->nHeight] == pindex; return (*this)[pindex->nHeight] == pindex;
} }
/** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */ /** Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip. */
CBlockIndex *Next(const CBlockIndex *pindex) const { CBlockIndex *Next(const CBlockIndex *pindex) const {
if (Contains(pindex)) if (Contains(pindex))
return (*this)[pindex->nHeight + 1]; return (*this)[pindex->nHeight + 1];
else else
return NULL; return nullptr;
} }
/** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
@ -482,7 +482,7 @@ public:
void SetTip(CBlockIndex *pindex); void SetTip(CBlockIndex *pindex);
/** Return a CBlockLocator that refers to a block in this chain (by default the tip). */ /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const; CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const;
/** Find the last common block between this chain and a block index entry. */ /** Find the last common block between this chain and a block index entry. */
const CBlockIndex *FindFork(const CBlockIndex *pindex) const; const CBlockIndex *FindFork(const CBlockIndex *pindex) const;

View file

@ -26,7 +26,7 @@ namespace Checkpoints {
if (t != mapBlockIndex.end()) if (t != mapBlockIndex.end())
return t->second; return t->second;
} }
return NULL; return nullptr;
} }
} // namespace Checkpoints } // namespace Checkpoints

View file

@ -183,15 +183,15 @@ public:
CCheckQueueControl& operator=(const CCheckQueueControl&) = delete; CCheckQueueControl& operator=(const CCheckQueueControl&) = delete;
explicit CCheckQueueControl(CCheckQueue<T> * const pqueueIn) : pqueue(pqueueIn), fDone(false) explicit CCheckQueueControl(CCheckQueue<T> * const pqueueIn) : pqueue(pqueueIn), fDone(false)
{ {
// passed queue is supposed to be unused, or NULL // passed queue is supposed to be unused, or nullptr
if (pqueue != NULL) { if (pqueue != nullptr) {
ENTER_CRITICAL_SECTION(pqueue->ControlMutex); ENTER_CRITICAL_SECTION(pqueue->ControlMutex);
} }
} }
bool Wait() bool Wait()
{ {
if (pqueue == NULL) if (pqueue == nullptr)
return true; return true;
bool fRet = pqueue->Wait(); bool fRet = pqueue->Wait();
fDone = true; fDone = true;
@ -200,7 +200,7 @@ public:
void Add(std::vector<T>& vChecks) void Add(std::vector<T>& vChecks)
{ {
if (pqueue != NULL) if (pqueue != nullptr)
pqueue->Add(vChecks); pqueue->Add(vChecks);
} }
@ -208,7 +208,7 @@ public:
{ {
if (!fDone) if (!fDone)
Wait(); Wait();
if (pqueue != NULL) { if (pqueue != nullptr) {
LEAVE_CRITICAL_SECTION(pqueue->ControlMutex); LEAVE_CRITICAL_SECTION(pqueue->ControlMutex);
} }
} }

View file

@ -132,13 +132,13 @@ static void MerkleComputation(const std::vector<uint256>& leaves, uint256* proot
uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated) { uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated) {
uint256 hash; uint256 hash;
MerkleComputation(leaves, &hash, mutated, -1, NULL); MerkleComputation(leaves, &hash, mutated, -1, nullptr);
return hash; return hash;
} }
std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position) { std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position) {
std::vector<uint256> ret; std::vector<uint256> ret;
MerkleComputation(leaves, NULL, NULL, position, &ret); MerkleComputation(leaves, nullptr, nullptr, position, &ret);
return ret; return ret;
} }

View file

@ -12,7 +12,7 @@
#include "primitives/block.h" #include "primitives/block.h"
#include "uint256.h" #include "uint256.h"
uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated = NULL); uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated = nullptr);
std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position); std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position);
uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint256>& branch, uint32_t position); uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint256>& branch, uint32_t position);
@ -20,13 +20,13 @@ uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint2
* Compute the Merkle root of the transactions in a block. * Compute the Merkle root of the transactions in a block.
* *mutated is set to true if a duplicated subtree was found. * *mutated is set to true if a duplicated subtree was found.
*/ */
uint256 BlockMerkleRoot(const CBlock& block, bool* mutated = NULL); uint256 BlockMerkleRoot(const CBlock& block, bool* mutated = nullptr);
/* /*
* Compute the Merkle root of the witness transactions in a block. * Compute the Merkle root of the witness transactions in a block.
* *mutated is set to true if a duplicated subtree was found. * *mutated is set to true if a duplicated subtree was found.
*/ */
uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated = NULL); uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated = nullptr);
/* /*
* Compute the Merkle branch for the tree of transactions in a block, for a * Compute the Merkle branch for the tree of transactions in a block, for a

View file

@ -102,7 +102,7 @@ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDeco
// this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
// the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
// checks in CheckSignatureEncoding. // checks in CheckSignatureEncoding.
if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, NULL)) { if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) {
const unsigned char chSigHashType = vch.back(); const unsigned char chSigHashType = vch.back();
if (mapSigHashTypes.count(chSigHashType)) { if (mapSigHashTypes.count(chSigHashType)) {
strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]";

View file

@ -75,7 +75,7 @@ void ChaCha20::Output(unsigned char* c, size_t bytes)
{ {
uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
uint32_t j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15; uint32_t j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15;
unsigned char *ctarget = NULL; unsigned char *ctarget = nullptr;
unsigned char tmp[64]; unsigned char tmp[64];
unsigned int i; unsigned int i;

View file

@ -92,7 +92,7 @@ static leveldb::Options GetOptions(size_t nCacheSize)
CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate) CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate)
{ {
penv = NULL; penv = nullptr;
readoptions.verify_checksums = true; readoptions.verify_checksums = true;
iteroptions.verify_checksums = true; iteroptions.verify_checksums = true;
iteroptions.fill_cache = false; iteroptions.fill_cache = false;
@ -144,15 +144,15 @@ CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bo
CDBWrapper::~CDBWrapper() CDBWrapper::~CDBWrapper()
{ {
delete pdb; delete pdb;
pdb = NULL; pdb = nullptr;
delete options.filter_policy; delete options.filter_policy;
options.filter_policy = NULL; options.filter_policy = nullptr;
delete options.info_log; delete options.info_log;
options.info_log = NULL; options.info_log = nullptr;
delete options.block_cache; delete options.block_cache;
options.block_cache = NULL; options.block_cache = nullptr;
delete penv; delete penv;
options.env = NULL; options.env = nullptr;
} }
bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync) bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)

View file

@ -177,7 +177,7 @@ class CDBWrapper
{ {
friend const std::vector<unsigned char>& dbwrapper_private::GetObfuscateKey(const CDBWrapper &w); friend const std::vector<unsigned char>& dbwrapper_private::GetObfuscateKey(const CDBWrapper &w);
private: private:
//! custom environment this database is using (may be NULL in case of default environment) //! custom environment this database is using (may be nullptr in case of default environment)
leveldb::Env* penv; leveldb::Env* penv;
//! database options used //! database options used

View file

@ -292,7 +292,7 @@ static void http_request_cb(struct evhttp_request* req, void* arg)
static void http_reject_request_cb(struct evhttp_request* req, void*) static void http_reject_request_cb(struct evhttp_request* req, void*)
{ {
LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n"); LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL); evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
} }
/** Event dispatcher thread */ /** Event dispatcher thread */
@ -334,7 +334,7 @@ static bool HTTPBindAddresses(struct evhttp* http)
// Bind addresses // Bind addresses
for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) { for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second); LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second); evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
if (bind_handle) { if (bind_handle) {
boundSockets.push_back(bind_handle); boundSockets.push_back(bind_handle);
} else { } else {
@ -404,7 +404,7 @@ bool InitHTTPServer()
evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE); evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
evhttp_set_max_body_size(http, MAX_SIZE); evhttp_set_max_body_size(http, MAX_SIZE);
evhttp_set_gencb(http, http_request_cb, NULL); evhttp_set_gencb(http, http_request_cb, nullptr);
if (!HTTPBindAddresses(http)) { if (!HTTPBindAddresses(http)) {
LogPrintf("Unable to bind any endpoint for RPC server\n"); LogPrintf("Unable to bind any endpoint for RPC server\n");
@ -464,7 +464,7 @@ void InterruptHTTPServer()
evhttp_del_accept_socket(eventHTTP, socket); evhttp_del_accept_socket(eventHTTP, socket);
} }
// Reject requests on current connections // Reject requests on current connections
evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL); evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
} }
if (workQueue) if (workQueue)
workQueue->Interrupt(); workQueue->Interrupt();
@ -530,7 +530,7 @@ HTTPEvent::~HTTPEvent()
} }
void HTTPEvent::trigger(struct timeval* tv) void HTTPEvent::trigger(struct timeval* tv)
{ {
if (tv == NULL) if (tv == nullptr)
event_active(ev, 0, 0); // immediately trigger event in main thread event_active(ev, 0, 0); // immediately trigger event in main thread
else else
evtimer_add(ev, tv); // trigger after timeval passed evtimer_add(ev, tv); // trigger after timeval passed
@ -573,7 +573,7 @@ std::string HTTPRequest::ReadBody()
* abstraction to consume the evbuffer on the fly in the parsing algorithm. * abstraction to consume the evbuffer on the fly in the parsing algorithm.
*/ */
const char* data = (const char*)evbuffer_pullup(buf, size); const char* data = (const char*)evbuffer_pullup(buf, size);
if (!data) // returns NULL in case of empty buffer if (!data) // returns nullptr in case of empty buffer
return ""; return "";
std::string rv(data, size); std::string rv(data, size);
evbuffer_drain(buf, size); evbuffer_drain(buf, size);
@ -600,7 +600,7 @@ void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
assert(evb); assert(evb);
evbuffer_add(evb, strReply.data(), strReply.size()); evbuffer_add(evb, strReply.data(), strReply.size());
HTTPEvent* ev = new HTTPEvent(eventBase, true, HTTPEvent* ev = new HTTPEvent(eventBase, true,
std::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL)); std::bind(evhttp_send_reply, req, nStatus, (const char*)nullptr, (struct evbuffer *)nullptr));
ev->trigger(0); ev->trigger(0);
replySent = true; replySent = true;
req = 0; // transferred back to main thread req = 0; // transferred back to main thread
@ -669,7 +669,7 @@ void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
std::string urlDecode(const std::string &urlEncoded) { std::string urlDecode(const std::string &urlEncoded) {
std::string res; std::string res;
if (!urlEncoded.empty()) { if (!urlEncoded.empty()) {
char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, NULL); char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, nullptr);
if (decoded) { if (decoded) {
res = std::string(decoded); res = std::string(decoded);
free(decoded); free(decoded);

View file

@ -76,7 +76,7 @@ std::unique_ptr<CConnman> g_connman;
std::unique_ptr<PeerLogicValidation> peerLogic; std::unique_ptr<PeerLogicValidation> peerLogic;
#if ENABLE_ZMQ #if ENABLE_ZMQ
static CZMQNotificationInterface* pzmqNotificationInterface = NULL; static CZMQNotificationInterface* pzmqNotificationInterface = nullptr;
#endif #endif
#ifdef WIN32 #ifdef WIN32
@ -153,7 +153,7 @@ public:
// Writes do not need similar protection, as failure to write is handled by the caller. // Writes do not need similar protection, as failure to write is handled by the caller.
}; };
static CCoinsViewErrorCatcher *pcoinscatcher = NULL; static CCoinsViewErrorCatcher *pcoinscatcher = nullptr;
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle; static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
void Interrupt(boost::thread_group& threadGroup) void Interrupt(boost::thread_group& threadGroup)
@ -232,17 +232,17 @@ void Shutdown()
{ {
LOCK(cs_main); LOCK(cs_main);
if (pcoinsTip != NULL) { if (pcoinsTip != nullptr) {
FlushStateToDisk(); FlushStateToDisk();
} }
delete pcoinsTip; delete pcoinsTip;
pcoinsTip = NULL; pcoinsTip = nullptr;
delete pcoinscatcher; delete pcoinscatcher;
pcoinscatcher = NULL; pcoinscatcher = nullptr;
delete pcoinsdbview; delete pcoinsdbview;
pcoinsdbview = NULL; pcoinsdbview = nullptr;
delete pblocktree; delete pblocktree;
pblocktree = NULL; pblocktree = nullptr;
} }
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
for (CWalletRef pwallet : vpwallets) { for (CWalletRef pwallet : vpwallets) {
@ -254,7 +254,7 @@ void Shutdown()
if (pzmqNotificationInterface) { if (pzmqNotificationInterface) {
UnregisterValidationInterface(pzmqNotificationInterface); UnregisterValidationInterface(pzmqNotificationInterface);
delete pzmqNotificationInterface; delete pzmqNotificationInterface;
pzmqNotificationInterface = NULL; pzmqNotificationInterface = nullptr;
} }
#endif #endif
@ -300,7 +300,7 @@ static void registerSignalHandler(int signal, void(*handler)(int))
sa.sa_handler = handler; sa.sa_handler = handler;
sigemptyset(&sa.sa_mask); sigemptyset(&sa.sa_mask);
sa.sa_flags = 0; sa.sa_flags = 0;
sigaction(signal, &sa, NULL); sigaction(signal, &sa, nullptr);
} }
#endif #endif
@ -558,7 +558,7 @@ static CConditionVariable condvar_GenesisWait;
static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex) static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
{ {
if (pBlockIndex != NULL) { if (pBlockIndex != nullptr) {
{ {
boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait); boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
fHaveGenesis = true; fHaveGenesis = true;
@ -843,7 +843,7 @@ bool AppInitBasicSetup()
#ifdef _MSC_VER #ifdef _MSC_VER
// Turn off Microsoft heap dump noise // Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
// Disable confusing "helpful" text message on abort, Ctrl-C // Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif #endif
@ -858,7 +858,7 @@ bool AppInitBasicSetup()
#endif #endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); if (setProcDEPPol != nullptr) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif #endif
if (!SetupNetworking()) if (!SetupNetworking())
@ -1477,7 +1477,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
strLoadError = _("Error initializing block database"); strLoadError = _("Error initializing block database");
break; break;
} }
assert(chainActive.Tip() != NULL); assert(chainActive.Tip() != nullptr);
} }
if (!fReset) { if (!fReset) {
@ -1604,7 +1604,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// Either install a handler to notify us when genesis activates, or set fHaveGenesis directly. // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
// No locking, as this happens before any background thread is started. // No locking, as this happens before any background thread is started.
if (chainActive.Tip() == NULL) { if (chainActive.Tip() == nullptr) {
uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait); uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
} else { } else {
fHaveGenesis = true; fHaveGenesis = true;

View file

@ -13,7 +13,7 @@
#include <secp256k1.h> #include <secp256k1.h>
#include <secp256k1_recovery.h> #include <secp256k1_recovery.h>
static secp256k1_context* secp256k1_context_sign = NULL; static secp256k1_context* secp256k1_context_sign = nullptr;
/** These functions are taken from the libsecp256k1 distribution and are very ugly. */ /** These functions are taken from the libsecp256k1 distribution and are very ugly. */
static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) { static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) {
@ -165,7 +165,7 @@ bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, uint32_
unsigned char extra_entropy[32] = {0}; unsigned char extra_entropy[32] = {0};
WriteLE32(extra_entropy, test_case); WriteLE32(extra_entropy, test_case);
secp256k1_ecdsa_signature sig; secp256k1_ecdsa_signature sig;
int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, test_case ? extra_entropy : NULL); int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, test_case ? extra_entropy : nullptr);
assert(ret); assert(ret);
secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, (unsigned char*)vchSig.data(), &nSigLen, &sig); secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, (unsigned char*)vchSig.data(), &nSigLen, &sig);
vchSig.resize(nSigLen); vchSig.resize(nSigLen);
@ -192,7 +192,7 @@ bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig)
vchSig.resize(65); vchSig.resize(65);
int rec = -1; int rec = -1;
secp256k1_ecdsa_recoverable_signature sig; secp256k1_ecdsa_recoverable_signature sig;
int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, NULL); int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
assert(ret); assert(ret);
secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, (unsigned char*)&vchSig[1], &rec, &sig); secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, (unsigned char*)&vchSig[1], &rec, &sig);
assert(ret); assert(ret);
@ -289,10 +289,10 @@ bool ECC_InitSanityCheck() {
} }
void ECC_Start() { void ECC_Start() {
assert(secp256k1_context_sign == NULL); assert(secp256k1_context_sign == nullptr);
secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
assert(ctx != NULL); assert(ctx != nullptr);
{ {
// Pass in a random blinding seed to the secp256k1 context. // Pass in a random blinding seed to the secp256k1 context.
@ -307,7 +307,7 @@ void ECC_Start() {
void ECC_Stop() { void ECC_Stop() {
secp256k1_context *ctx = secp256k1_context_sign; secp256k1_context *ctx = secp256k1_context_sign;
secp256k1_context_sign = NULL; secp256k1_context_sign = nullptr;
if (ctx) { if (ctx) {
secp256k1_context_destroy(ctx); secp256k1_context_destroy(ctx);

View file

@ -306,7 +306,7 @@ CNode* CConnman::FindNode(const CNetAddr& ip)
for (CNode* pnode : vNodes) for (CNode* pnode : vNodes)
if ((CNetAddr)pnode->addr == ip) if ((CNetAddr)pnode->addr == ip)
return (pnode); return (pnode);
return NULL; return nullptr;
} }
CNode* CConnman::FindNode(const CSubNet& subNet) CNode* CConnman::FindNode(const CSubNet& subNet)
@ -315,7 +315,7 @@ CNode* CConnman::FindNode(const CSubNet& subNet)
for (CNode* pnode : vNodes) for (CNode* pnode : vNodes)
if (subNet.Match((CNetAddr)pnode->addr)) if (subNet.Match((CNetAddr)pnode->addr))
return (pnode); return (pnode);
return NULL; return nullptr;
} }
CNode* CConnman::FindNode(const std::string& addrName) CNode* CConnman::FindNode(const std::string& addrName)
@ -326,7 +326,7 @@ CNode* CConnman::FindNode(const std::string& addrName)
return (pnode); return (pnode);
} }
} }
return NULL; return nullptr;
} }
CNode* CConnman::FindNode(const CService& addr) CNode* CConnman::FindNode(const CService& addr)
@ -335,7 +335,7 @@ CNode* CConnman::FindNode(const CService& addr)
for (CNode* pnode : vNodes) for (CNode* pnode : vNodes)
if ((CService)pnode->addr == addr) if ((CService)pnode->addr == addr)
return (pnode); return (pnode);
return NULL; return nullptr;
} }
bool CConnman::CheckIncomingNonce(uint64_t nonce) bool CConnman::CheckIncomingNonce(uint64_t nonce)
@ -366,16 +366,16 @@ static CAddress GetBindAddress(SOCKET sock)
CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure) CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure)
{ {
if (pszDest == NULL) { if (pszDest == nullptr) {
if (IsLocal(addrConnect)) if (IsLocal(addrConnect))
return NULL; return nullptr;
// Look for an existing connection // Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect); CNode* pnode = FindNode((CService)addrConnect);
if (pnode) if (pnode)
{ {
LogPrintf("Failed to open new connection, already connected\n"); LogPrintf("Failed to open new connection, already connected\n");
return NULL; return nullptr;
} }
} }
@ -393,7 +393,7 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
if (!IsSelectableSocket(hSocket)) { if (!IsSelectableSocket(hSocket)) {
LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
CloseSocket(hSocket); CloseSocket(hSocket);
return NULL; return nullptr;
} }
if (pszDest && addrConnect.IsValid()) { if (pszDest && addrConnect.IsValid()) {
@ -408,7 +408,7 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
pnode->MaybeSetAddrName(std::string(pszDest)); pnode->MaybeSetAddrName(std::string(pszDest));
CloseSocket(hSocket); CloseSocket(hSocket);
LogPrintf("Failed to open new connection, already connected\n"); LogPrintf("Failed to open new connection, already connected\n");
return NULL; return nullptr;
} }
} }
@ -429,7 +429,7 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
addrman.Attempt(addrConnect, fCountFailure); addrman.Attempt(addrConnect, fCountFailure);
} }
return NULL; return nullptr;
} }
void CConnman::DumpBanlist() void CConnman::DumpBanlist()
@ -966,7 +966,7 @@ bool CConnman::AttemptToEvictConnection()
NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime, NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime,
node->nLastBlockTime, node->nLastTXTime, node->nLastBlockTime, node->nLastTXTime,
(node->nServices & nRelevantServices) == nRelevantServices, (node->nServices & nRelevantServices) == nRelevantServices,
node->fRelayTxes, node->pfilter != NULL, node->addr, node->nKeyedNetGroup}; node->fRelayTxes, node->pfilter != nullptr, node->addr, node->nKeyedNetGroup};
vEvictionCandidates.push_back(candidate); vEvictionCandidates.push_back(candidate);
} }
} }
@ -1524,7 +1524,7 @@ void ThreadMapPort()
void MapPort(bool fUseUPnP) void MapPort(bool fUseUPnP)
{ {
static boost::thread* upnp_thread = NULL; static boost::thread* upnp_thread = nullptr;
if (fUseUPnP) if (fUseUPnP)
{ {
@ -1539,7 +1539,7 @@ void MapPort(bool fUseUPnP)
upnp_thread->interrupt(); upnp_thread->interrupt();
upnp_thread->join(); upnp_thread->join();
delete upnp_thread; delete upnp_thread;
upnp_thread = NULL; upnp_thread = nullptr;
} }
} }
@ -1685,7 +1685,7 @@ void CConnman::ThreadOpenConnections()
for (const std::string& strAddr : gArgs.GetArgs("-connect")) for (const std::string& strAddr : gArgs.GetArgs("-connect"))
{ {
CAddress addr(CService(), NODE_NONE); CAddress addr(CService(), NODE_NONE);
OpenNetworkConnection(addr, false, NULL, strAddr.c_str()); OpenNetworkConnection(addr, false, nullptr, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++) for (int i = 0; i < 10 && i < nLoop; i++)
{ {
if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
@ -1841,7 +1841,7 @@ void CConnman::ThreadOpenConnections()
LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString()); LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
} }
OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, NULL, false, fFeeler); OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler);
} }
} }
} }
@ -2153,9 +2153,9 @@ void Discover(boost::thread_group& threadGroup)
struct ifaddrs* myaddrs; struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0) if (getifaddrs(&myaddrs) == 0)
{ {
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
{ {
if (ifa->ifa_addr == NULL) continue; if (ifa->ifa_addr == nullptr) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
@ -2208,8 +2208,8 @@ CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSe
nLastNodeId = 0; nLastNodeId = 0;
nSendBufferMaxSize = 0; nSendBufferMaxSize = 0;
nReceiveFloodSize = 0; nReceiveFloodSize = 0;
semOutbound = NULL; semOutbound = nullptr;
semAddnode = NULL; semAddnode = nullptr;
flagInterruptMsgProc = false; flagInterruptMsgProc = false;
Options connOptions; Options connOptions;
@ -2312,11 +2312,11 @@ bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
fAddressesInitialized = true; fAddressesInitialized = true;
if (semOutbound == NULL) { if (semOutbound == nullptr) {
// initialize semaphore // initialize semaphore
semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections)); semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
} }
if (semAddnode == NULL) { if (semAddnode == nullptr) {
// initialize semaphore // initialize semaphore
semAddnode = new CSemaphore(nMaxAddnode); semAddnode = new CSemaphore(nMaxAddnode);
} }
@ -2434,9 +2434,9 @@ void CConnman::Stop()
vNodesDisconnected.clear(); vNodesDisconnected.clear();
vhListenSocket.clear(); vhListenSocket.clear();
delete semOutbound; delete semOutbound;
semOutbound = NULL; semOutbound = nullptr;
delete semAddnode; delete semAddnode;
semAddnode = NULL; semAddnode = nullptr;
} }
void CConnman::DeleteNode(CNode* pnode) void CConnman::DeleteNode(CNode* pnode)

View file

@ -170,7 +170,7 @@ public:
void Interrupt(); void Interrupt();
bool GetNetworkActive() const { return fNetworkActive; }; bool GetNetworkActive() const { return fNetworkActive; };
void SetNetworkActive(bool active); void SetNetworkActive(bool active);
bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false, bool fFeeler = false, bool fAddnode = false); bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool fAddnode = false);
bool CheckIncomingNonce(uint64_t nonce); bool CheckIncomingNonce(uint64_t nonce);
bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func); bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
@ -470,7 +470,7 @@ bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
bool RemoveLocal(const CService& addr); bool RemoveLocal(const CService& addr);
bool SeenLocal(const CService& addr); bool SeenLocal(const CService& addr);
bool IsLocal(const CService& addr); bool IsLocal(const CService& addr);
bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL); bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
bool IsReachable(enum Network net); bool IsReachable(enum Network net);
bool IsReachable(const CNetAddr &addr); bool IsReachable(const CNetAddr &addr);
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices); CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);

View file

@ -202,10 +202,10 @@ struct CNodeState {
fCurrentlyConnected = false; fCurrentlyConnected = false;
nMisbehavior = 0; nMisbehavior = 0;
fShouldBan = false; fShouldBan = false;
pindexBestKnownBlock = NULL; pindexBestKnownBlock = nullptr;
hashLastUnknownBlock.SetNull(); hashLastUnknownBlock.SetNull();
pindexLastCommonBlock = NULL; pindexLastCommonBlock = nullptr;
pindexBestHeaderSent = NULL; pindexBestHeaderSent = nullptr;
nUnconnectingHeaders = 0; nUnconnectingHeaders = 0;
fSyncStarted = false; fSyncStarted = false;
nHeadersSyncTimeout = 0; nHeadersSyncTimeout = 0;
@ -230,7 +230,7 @@ std::map<NodeId, CNodeState> mapNodeState;
CNodeState *State(NodeId pnode) { CNodeState *State(NodeId pnode) {
std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode); std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end()) if (it == mapNodeState.end())
return NULL; return nullptr;
return &it->second; return &it->second;
} }
@ -336,9 +336,9 @@ bool MarkBlockAsReceived(const uint256& hash) {
// Requires cs_main. // Requires cs_main.
// returns false, still setting pit, if the block was already in flight from the same peer // returns false, still setting pit, if the block was already in flight from the same peer
// pit will only be valid as long as the same cs_main lock is being held // pit will only be valid as long as the same cs_main lock is being held
bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = NULL, std::list<QueuedBlock>::iterator** pit = NULL) { bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) {
CNodeState *state = State(nodeid); CNodeState *state = State(nodeid);
assert(state != NULL); assert(state != nullptr);
// Short-circuit most stuff in case its from the same node // Short-circuit most stuff in case its from the same node
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
@ -353,14 +353,14 @@ bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex*
MarkBlockAsReceived(hash); MarkBlockAsReceived(hash);
std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
{hash, pindex, pindex != NULL, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : NULL)}); {hash, pindex, pindex != nullptr, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : nullptr)});
state->nBlocksInFlight++; state->nBlocksInFlight++;
state->nBlocksInFlightValidHeaders += it->fValidatedHeaders; state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
if (state->nBlocksInFlight == 1) { if (state->nBlocksInFlight == 1) {
// We're starting a block download (batch) from this peer. // We're starting a block download (batch) from this peer.
state->nDownloadingSince = GetTimeMicros(); state->nDownloadingSince = GetTimeMicros();
} }
if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) { if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) {
nPeersWithValidatedDownloads++; nPeersWithValidatedDownloads++;
} }
itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first; itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
@ -372,12 +372,12 @@ bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex*
/** Check whether the last unknown block a peer advertised is not yet known. */ /** Check whether the last unknown block a peer advertised is not yet known. */
void ProcessBlockAvailability(NodeId nodeid) { void ProcessBlockAvailability(NodeId nodeid) {
CNodeState *state = State(nodeid); CNodeState *state = State(nodeid);
assert(state != NULL); assert(state != nullptr);
if (!state->hashLastUnknownBlock.IsNull()) { if (!state->hashLastUnknownBlock.IsNull()) {
BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) { if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) if (state->pindexBestKnownBlock == nullptr || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = itOld->second; state->pindexBestKnownBlock = itOld->second;
state->hashLastUnknownBlock.SetNull(); state->hashLastUnknownBlock.SetNull();
} }
@ -387,14 +387,14 @@ void ProcessBlockAvailability(NodeId nodeid) {
/** Update tracking information about which blocks a peer is assumed to have. */ /** Update tracking information about which blocks a peer is assumed to have. */
void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
CNodeState *state = State(nodeid); CNodeState *state = State(nodeid);
assert(state != NULL); assert(state != nullptr);
ProcessBlockAvailability(nodeid); ProcessBlockAvailability(nodeid);
BlockMap::iterator it = mapBlockIndex.find(hash); BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
// An actually better block was announced. // An actually better block was announced.
if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) if (state->pindexBestKnownBlock == nullptr || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = it->second; state->pindexBestKnownBlock = it->second;
} else { } else {
// An unknown block was announced; just assume that the latest one is the best one. // An unknown block was announced; just assume that the latest one is the best one.
@ -461,17 +461,17 @@ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<con
vBlocks.reserve(vBlocks.size() + count); vBlocks.reserve(vBlocks.size() + count);
CNodeState *state = State(nodeid); CNodeState *state = State(nodeid);
assert(state != NULL); assert(state != nullptr);
// Make sure pindexBestKnownBlock is up to date, we'll need it. // Make sure pindexBestKnownBlock is up to date, we'll need it.
ProcessBlockAvailability(nodeid); ProcessBlockAvailability(nodeid);
if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < UintToArith256(consensusParams.nMinimumChainWork)) { if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < UintToArith256(consensusParams.nMinimumChainWork)) {
// This peer has nothing interesting. // This peer has nothing interesting.
return; return;
} }
if (state->pindexLastCommonBlock == NULL) { if (state->pindexLastCommonBlock == nullptr) {
// Bootstrap quickly by guessing a parent of our best tip is the forking point. // Bootstrap quickly by guessing a parent of our best tip is the forking point.
// Guessing wrong in either direction is not a problem. // Guessing wrong in either direction is not a problem.
state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
@ -546,7 +546,7 @@ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<con
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) { bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
LOCK(cs_main); LOCK(cs_main);
CNodeState *state = State(nodeid); CNodeState *state = State(nodeid);
if (state == NULL) if (state == nullptr)
return false; return false;
stats.nMisbehavior = state->nMisbehavior; stats.nMisbehavior = state->nMisbehavior;
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
@ -700,7 +700,7 @@ void Misbehaving(NodeId pnode, int howmuch)
return; return;
CNodeState *state = State(pnode); CNodeState *state = State(pnode);
if (state == NULL) if (state == nullptr)
return; return;
state->nMisbehavior += howmuch; state->nMisbehavior += howmuch;
@ -1006,7 +1006,7 @@ void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParam
// To prevent fingerprinting attacks, only send blocks outside of the active // To prevent fingerprinting attacks, only send blocks outside of the active
// chain if they are valid, and no more than a month older (both in time, and in // chain if they are valid, and no more than a month older (both in time, and in
// best equivalent proof of work) than the best header chain we know about. // best equivalent proof of work) than the best header chain we know about.
send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) && send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
(pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
(GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth); (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
if (!send) { if (!send) {
@ -1017,7 +1017,7 @@ void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParam
// disconnect node in case we have reached the outbound limit for serving historical blocks // disconnect node in case we have reached the outbound limit for serving historical blocks
// never disconnect whitelisted nodes // never disconnect whitelisted nodes
static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
if (send && connman.OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted) if (send && connman.OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
{ {
LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId()); LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
@ -1734,7 +1734,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
} }
CNodeState *nodestate = State(pfrom->GetId()); CNodeState *nodestate = State(pfrom->GetId());
const CBlockIndex* pindex = NULL; const CBlockIndex* pindex = nullptr;
if (locator.IsNull()) if (locator.IsNull())
{ {
// If locator is null, return the hashStop block // If locator is null, return the hashStop block
@ -1761,7 +1761,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break; break;
} }
// pindex can be NULL either if we sent chainActive.Tip() OR // pindex can be nullptr either if we sent chainActive.Tip() OR
// if our peer has chainActive.Tip() (and thus we are sending an empty // if our peer has chainActive.Tip() (and thus we are sending an empty
// headers message). In both cases it's safe to update // headers message). In both cases it's safe to update
// pindexBestHeaderSent to be our tip. // pindexBestHeaderSent to be our tip.
@ -1980,7 +1980,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
} }
} }
const CBlockIndex *pindex = NULL; const CBlockIndex *pindex = nullptr;
CValidationState state; CValidationState state;
if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) { if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
int nDoS; int nDoS;
@ -2052,7 +2052,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
if (pindex->nHeight <= chainActive.Height() + 2) { if (pindex->nHeight <= chainActive.Height() + 2) {
if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
(fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) { (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
std::list<QueuedBlock>::iterator* queuedBlockIt = NULL; std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) { if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
if (!(*queuedBlockIt)->partialBlock) if (!(*queuedBlockIt)->partialBlock)
(*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool)); (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
@ -2257,7 +2257,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
return true; return true;
} }
const CBlockIndex *pindexLast = NULL; const CBlockIndex *pindexLast = nullptr;
{ {
LOCK(cs_main); LOCK(cs_main);
CNodeState *nodestate = State(pfrom->GetId()); CNodeState *nodestate = State(pfrom->GetId());
@ -2766,7 +2766,7 @@ bool ProcessMessages(CNode* pfrom, CConnman& connman, const std::atomic<bool>& i
catch (const std::exception& e) { catch (const std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()"); PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) { } catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()"); PrintExceptionContinue(nullptr, "ProcessMessages()");
} }
if (!fRet) { if (!fRet) {
@ -2881,7 +2881,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
} }
// Start block sync // Start block sync
if (pindexBestHeader == NULL) if (pindexBestHeader == nullptr)
pindexBestHeader = chainActive.Tip(); pindexBestHeader = chainActive.Tip();
bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do. bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) { if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
@ -2929,7 +2929,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
bool fRevertToInv = ((!state.fPreferHeaders && bool fRevertToInv = ((!state.fPreferHeaders &&
(!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) || (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE); pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
const CBlockIndex *pBestIndex = NULL; // last header queued for delivery const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
if (!fRevertToInv) { if (!fRevertToInv) {
@ -2946,7 +2946,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
fRevertToInv = true; fRevertToInv = true;
break; break;
} }
if (pBestIndex != NULL && pindex->pprev != pBestIndex) { if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
// This means that the list of blocks to announce don't // This means that the list of blocks to announce don't
// connect to each other. // connect to each other.
// This shouldn't really be possible to hit during // This shouldn't really be possible to hit during
@ -2967,7 +2967,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
vHeaders.push_back(pindex->GetBlockHeader()); vHeaders.push_back(pindex->GetBlockHeader());
} else if (PeerHasHeader(&state, pindex)) { } else if (PeerHasHeader(&state, pindex)) {
continue; // keep looking for the first new block continue; // keep looking for the first new block
} else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) { } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
// Peer doesn't have this header but they do have the prior one. // Peer doesn't have this header but they do have the prior one.
// Start sending headers. // Start sending headers.
fFoundStartingHeader = true; fFoundStartingHeader = true;

View file

@ -271,7 +271,7 @@ std::string CNetAddr::ToStringIP() const
socklen_t socklen = sizeof(sockaddr); socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) { if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = ""; char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST)) if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), nullptr, 0, NI_NUMERICHOST))
return std::string(name); return std::string(name);
} }
if (IsIPv4()) if (IsIPv4())
@ -407,7 +407,7 @@ static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1; static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr *addr) int static GetExtNetwork(const CNetAddr *addr)
{ {
if (addr == NULL) if (addr == nullptr)
return NET_UNKNOWN; return NET_UNKNOWN;
if (addr->IsRFC4380()) if (addr->IsRFC4380())
return NET_TEREDO; return NET_TEREDO;

View file

@ -80,7 +80,7 @@ class CNetAddr
uint64_t GetHash() const; uint64_t GetHash() const;
bool GetInAddr(struct in_addr* pipv4Addr) const; bool GetInAddr(struct in_addr* pipv4Addr) const;
std::vector<unsigned char> GetGroup() const; std::vector<unsigned char> GetGroup() const;
int GetReachabilityFrom(const CNetAddr *paddrPartner = NULL) const; int GetReachabilityFrom(const CNetAddr *paddrPartner = nullptr) const;
CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0); CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
bool GetIn6Addr(struct in6_addr* pipv6Addr) const; bool GetIn6Addr(struct in6_addr* pipv6Addr) const;

View file

@ -81,13 +81,13 @@ bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsign
#else #else
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST; aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif #endif
struct addrinfo *aiRes = NULL; struct addrinfo *aiRes = nullptr;
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes); int nErr = getaddrinfo(pszName, nullptr, &aiHint, &aiRes);
if (nErr) if (nErr)
return false; return false;
struct addrinfo *aiTrav = aiRes; struct addrinfo *aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
{ {
CNetAddr resolved; CNetAddr resolved;
if (aiTrav->ai_family == AF_INET) if (aiTrav->ai_family == AF_INET)
@ -227,7 +227,7 @@ static IntrRecvError InterruptibleRecv(char* data, size_t len, int timeout, cons
fd_set fdset; fd_set fdset;
FD_ZERO(&fdset); FD_ZERO(&fdset);
FD_SET(hSocket, &fdset); FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval); int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval);
if (nRet == SOCKET_ERROR) { if (nRet == SOCKET_ERROR) {
return IntrRecvError::NetworkError; return IntrRecvError::NetworkError;
} }
@ -439,7 +439,7 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
fd_set fdset; fd_set fdset;
FD_ZERO(&fdset); FD_ZERO(&fdset);
FD_SET(hSocket, &fdset); FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout); int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout);
if (nRet == 0) if (nRet == 0)
{ {
LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString()); LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString());
@ -642,8 +642,8 @@ std::string NetworkErrorString(int err)
char buf[256]; char buf[256];
buf[0] = 0; buf[0] = 0;
if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, sizeof(buf), NULL)) buf, sizeof(buf), nullptr))
{ {
return strprintf("%s (%d)", buf, err); return strprintf("%s (%d)", buf, err);
} }

View file

@ -12,7 +12,7 @@
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{ {
assert(pindexLast != NULL); assert(pindexLast != nullptr);
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Only change once per difficulty adjustment interval // Only change once per difficulty adjustment interval

View file

@ -448,7 +448,7 @@ public:
} }
if (!is_direct()) { if (!is_direct()) {
free(_union.indirect); free(_union.indirect);
_union.indirect = NULL; _union.indirect = nullptr;
} }
} }

View file

@ -10,7 +10,7 @@
namespace namespace
{ {
/* Global secp256k1_context object used for verification. */ /* Global secp256k1_context object used for verification. */
secp256k1_context* secp256k1_context_verify = NULL; secp256k1_context* secp256k1_context_verify = nullptr;
} // namespace } // namespace
/** This function is taken from the libsecp256k1 distribution and implements /** This function is taken from the libsecp256k1 distribution and implements
@ -274,7 +274,7 @@ bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const {
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, vchSig.data(), vchSig.size())) { if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, vchSig.data(), vchSig.size())) {
return false; return false;
} }
return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, NULL, &sig)); return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, nullptr, &sig));
} }
/* static */ int ECCVerifyHandle::refcount = 0; /* static */ int ECCVerifyHandle::refcount = 0;
@ -282,9 +282,9 @@ bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const {
ECCVerifyHandle::ECCVerifyHandle() ECCVerifyHandle::ECCVerifyHandle()
{ {
if (refcount == 0) { if (refcount == 0) {
assert(secp256k1_context_verify == NULL); assert(secp256k1_context_verify == nullptr);
secp256k1_context_verify = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); secp256k1_context_verify = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
assert(secp256k1_context_verify != NULL); assert(secp256k1_context_verify != nullptr);
} }
refcount++; refcount++;
} }
@ -293,8 +293,8 @@ ECCVerifyHandle::~ECCVerifyHandle()
{ {
refcount--; refcount--;
if (refcount == 0) { if (refcount == 0) {
assert(secp256k1_context_verify != NULL); assert(secp256k1_context_verify != nullptr);
secp256k1_context_destroy(secp256k1_context_verify); secp256k1_context_destroy(secp256k1_context_verify);
secp256k1_context_verify = NULL; secp256k1_context_verify = nullptr;
} }
} }

View file

@ -273,7 +273,7 @@ void AddressBookPage::on_exportButton_clicked()
// CSV is currently the only supported format // CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(this, QString filename = GUIUtil::getSaveFileName(this,
tr("Export Address List"), QString(), tr("Export Address List"), QString(),
tr("Comma separated file (*.csv)"), NULL); tr("Comma separated file (*.csv)"), nullptr);
if (filename.isNull()) if (filename.isNull())
return; return;

View file

@ -305,7 +305,7 @@ void BitcoinCore::initialize()
} catch (const std::exception& e) { } catch (const std::exception& e) {
handleRunawayException(&e); handleRunawayException(&e);
} catch (...) { } catch (...) {
handleRunawayException(NULL); handleRunawayException(nullptr);
} }
} }
@ -322,7 +322,7 @@ void BitcoinCore::shutdown()
} catch (const std::exception& e) { } catch (const std::exception& e) {
handleRunawayException(&e); handleRunawayException(&e);
} catch (...) { } catch (...) {
handleRunawayException(NULL); handleRunawayException(nullptr);
} }
} }
@ -383,7 +383,7 @@ void BitcoinApplication::createPaymentServer()
void BitcoinApplication::createOptionsModel(bool resetSettings) void BitcoinApplication::createOptionsModel(bool resetSettings)
{ {
optionsModel = new OptionsModel(NULL, resetSettings); optionsModel = new OptionsModel(nullptr, resetSettings);
} }
void BitcoinApplication::createWindow(const NetworkStyle *networkStyle) void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
@ -608,7 +608,7 @@ int main(int argc, char *argv[])
// but before showing splash screen. // but before showing splash screen.
if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
{ {
HelpMessageDialog help(NULL, IsArgSet("-version")); HelpMessageDialog help(nullptr, IsArgSet("-version"));
help.showOrPrint(); help.showOrPrint();
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
@ -723,7 +723,7 @@ int main(int argc, char *argv[])
PrintExceptionContinue(&e, "Runaway exception"); PrintExceptionContinue(&e, "Runaway exception");
app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); app.handleRunawayException(QString::fromStdString(GetWarnings("gui")));
} catch (...) { } catch (...) {
PrintExceptionContinue(NULL, "Runaway exception"); PrintExceptionContinue(nullptr, "Runaway exception");
app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); app.handleRunawayException(QString::fromStdString(GetWarnings("gui")));
} }
return rv; return rv;

View file

@ -479,7 +479,7 @@ void BitcoinGUI::setClientModel(ClientModel *_clientModel)
connect(_clientModel, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool))); connect(_clientModel, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
modalOverlay->setKnownBestHeight(_clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(_clientModel->getHeaderTipTime())); modalOverlay->setKnownBestHeight(_clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(_clientModel->getHeaderTipTime()));
setNumBlocks(_clientModel->getNumBlocks(), _clientModel->getLastBlockDate(), _clientModel->getVerificationProgress(NULL), false); setNumBlocks(_clientModel->getNumBlocks(), _clientModel->getLastBlockDate(), _clientModel->getVerificationProgress(nullptr), false);
connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool))); connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
// Receive and report messages from client model // Receive and report messages from client model
@ -922,7 +922,7 @@ void BitcoinGUI::message(const QString &title, const QString &message, unsigned
showNormalIfMinimized(); showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec(); int r = mBox.exec();
if (ret != NULL) if (ret != nullptr)
*ret = r == QMessageBox::Ok; *ret = r == QMessageBox::Ok;
} }
else else

View file

@ -168,7 +168,7 @@ public Q_SLOTS:
@see CClientUIInterface::MessageBoxFlags @see CClientUIInterface::MessageBoxFlags
@param[in] ret pointer to a bool that will be modified to whether Ok was clicked (modal only) @param[in] ret pointer to a bool that will be modified to whether Ok was clicked (modal only)
*/ */
void message(const QString &title, const QString &message, unsigned int style, bool *ret = NULL); void message(const QString &title, const QString &message, unsigned int style, bool *ret = nullptr);
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
/** Set the encryption status as shown in the UI. /** Set the encryption status as shown in the UI.

View file

@ -634,11 +634,11 @@ bool SetStartOnSystemStartup(bool fAutoStart)
if (fAutoStart) if (fAutoStart)
{ {
CoInitialize(NULL); CoInitialize(nullptr);
// Get a pointer to the IShellLink interface. // Get a pointer to the IShellLink interface.
IShellLink* psl = NULL; IShellLink* psl = nullptr;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
CLSCTX_INPROC_SERVER, IID_IShellLink, CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl)); reinterpret_cast<void**>(&psl));
@ -646,7 +646,7 @@ bool SetStartOnSystemStartup(bool fAutoStart)
{ {
// Get the current executable path // Get the current executable path
TCHAR pszExePath[MAX_PATH]; TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); GetModuleFileName(nullptr, pszExePath, sizeof(pszExePath));
// Start client minimized // Start client minimized
QString strArgs = "-min"; QString strArgs = "-min";
@ -674,7 +674,7 @@ bool SetStartOnSystemStartup(bool fAutoStart)
// Query IShellLink for the IPersistFile interface for // Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage. // saving the shortcut in persistent storage.
IPersistFile* ppf = NULL; IPersistFile* ppf = nullptr;
hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres)) if (SUCCEEDED(hres))
{ {
@ -781,21 +781,21 @@ LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{ {
// loop through the list of startup items and try to find the bitcoin app // loop through the list of startup items and try to find the bitcoin app
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, nullptr);
for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = NULL; CFURLRef currentItemURL = nullptr;
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
if(&LSSharedFileListItemCopyResolvedURL) if(&LSSharedFileListItemCopyResolvedURL)
currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, NULL); currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, nullptr);
#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100 #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
else else
LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr);
#endif #endif
#else #else
LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr);
#endif #endif
if(currentItemURL && CFEqual(currentItemURL, findUrl)) { if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
@ -807,13 +807,13 @@ LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef
CFRelease(currentItemURL); CFRelease(currentItemURL);
} }
} }
return NULL; return nullptr;
} }
bool GetStartOnSystemStartup() bool GetStartOnSystemStartup()
{ {
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
return !!foundItem; // return boolified object return !!foundItem; // return boolified object
} }
@ -821,12 +821,12 @@ bool GetStartOnSystemStartup()
bool SetStartOnSystemStartup(bool fAutoStart) bool SetStartOnSystemStartup(bool fAutoStart)
{ {
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
if(fAutoStart && !foundItem) { if(fAutoStart && !foundItem) {
// add bitcoin app to startup item list // add bitcoin app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, nullptr, nullptr, bitcoinAppUrl, nullptr, nullptr);
} }
else if(!fAutoStart && foundItem) { else if(!fAutoStart && foundItem) {
// remove item // remove item

View file

@ -44,7 +44,7 @@ void OpenURIDialog::accept()
void OpenURIDialog::on_selectFileButton_clicked() void OpenURIDialog::on_selectFileButton_clicked()
{ {
QString filename = GUIUtil::getOpenFileName(this, tr("Select payment request file to open"), "", "", NULL); QString filename = GUIUtil::getOpenFileName(this, tr("Select payment request file to open"), "", "", nullptr);
if(filename.isEmpty()) if(filename.isEmpty())
return; return;
QUrl fileUri = QUrl::fromLocalFile(filename); QUrl fileUri = QUrl::fromLocalFile(filename);

View file

@ -66,7 +66,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
// One day we'll support more PKI types, but just // One day we'll support more PKI types, but just
// x509 for now: // x509 for now:
const EVP_MD* digestAlgorithm = NULL; const EVP_MD* digestAlgorithm = nullptr;
if (paymentRequest.pki_type() == "x509+sha256") { if (paymentRequest.pki_type() == "x509+sha256") {
digestAlgorithm = EVP_sha256(); digestAlgorithm = EVP_sha256();
} }
@ -104,7 +104,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
} }
#endif #endif
const unsigned char *data = (const unsigned char *)certChain.certificate(i).data(); const unsigned char *data = (const unsigned char *)certChain.certificate(i).data();
X509 *cert = d2i_X509(NULL, &data, certChain.certificate(i).size()); X509 *cert = d2i_X509(nullptr, &data, certChain.certificate(i).size());
if (cert) if (cert)
certs.push_back(cert); certs.push_back(cert);
} }
@ -129,7 +129,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
return false; return false;
} }
char *website = NULL; char *website = nullptr;
bool fResult = true; bool fResult = true;
try try
{ {
@ -169,7 +169,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
#endif #endif
EVP_PKEY *pubkey = X509_get_pubkey(signing_cert); EVP_PKEY *pubkey = X509_get_pubkey(signing_cert);
EVP_MD_CTX_init(ctx); EVP_MD_CTX_init(ctx);
if (!EVP_VerifyInit_ex(ctx, digestAlgorithm, NULL) || if (!EVP_VerifyInit_ex(ctx, digestAlgorithm, nullptr) ||
!EVP_VerifyUpdate(ctx, data_to_verify.data(), data_to_verify.size()) || !EVP_VerifyUpdate(ctx, data_to_verify.data(), data_to_verify.size()) ||
!EVP_VerifyFinal(ctx, (const unsigned char*)paymentRequest.signature().data(), (unsigned int)paymentRequest.signature().size(), pubkey)) { !EVP_VerifyFinal(ctx, (const unsigned char*)paymentRequest.signature().data(), (unsigned int)paymentRequest.signature().size(), pubkey)) {
throw SSLVerifyError("Bad signature, invalid payment request."); throw SSLVerifyError("Bad signature, invalid payment request.");
@ -179,7 +179,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
#endif #endif
// OpenSSL API for getting human printable strings from certs is baroque. // OpenSSL API for getting human printable strings from certs is baroque.
int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, NULL, 0); int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, nullptr, 0);
website = new char[textlen + 1]; website = new char[textlen + 1];
if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) { if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) {
merchant = website; merchant = website;

View file

@ -274,7 +274,7 @@ bool PaymentServer::ipcSendCommandLine()
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
{ {
delete socket; delete socket;
socket = NULL; socket = nullptr;
return false; return false;
} }
@ -290,7 +290,7 @@ bool PaymentServer::ipcSendCommandLine()
socket->disconnectFromServer(); socket->disconnectFromServer();
delete socket; delete socket;
socket = NULL; socket = nullptr;
fResult = true; fResult = true;
} }
@ -364,7 +364,7 @@ void PaymentServer::initNetManager()
{ {
if (!optionsModel) if (!optionsModel)
return; return;
if (netManager != NULL) if (netManager != nullptr)
delete netManager; delete netManager;
// netManager is used to fetch paymentrequests given in bitcoin: URIs // netManager is used to fetch paymentrequests given in bitcoin: URIs

View file

@ -75,12 +75,12 @@ public:
PaymentServer(QObject* parent, bool startLocalServer = true); PaymentServer(QObject* parent, bool startLocalServer = true);
~PaymentServer(); ~PaymentServer();
// Load root certificate authorities. Pass NULL (default) // Load root certificate authorities. Pass nullptr (default)
// to read from the file specified in the -rootcertificates setting, // to read from the file specified in the -rootcertificates setting,
// or, if that's not set, to use the system default root certificates. // or, if that's not set, to use the system default root certificates.
// If you pass in a store, you should not X509_STORE_free it: it will be // If you pass in a store, you should not X509_STORE_free it: it will be
// freed either at exit or when another set of CAs are loaded. // freed either at exit or when another set of CAs are loaded.
static void LoadRootCAs(X509_STORE* store = NULL); static void LoadRootCAs(X509_STORE* store = nullptr);
// Return certificate store // Return certificate store
static X509_STORE* getCertStore(); static X509_STORE* getCertStore();

View file

@ -68,7 +68,7 @@ void QRImageWidget::saveImage()
{ {
if(!pixmap()) if(!pixmap())
return; return;
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), NULL); QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), nullptr);
if (!fn.isEmpty()) if (!fn.isEmpty())
{ {
exportImage().save(fn); exportImage().save(fn);

View file

@ -123,7 +123,7 @@ void RecentRequestsTableModel::updateAmountColumnTitle()
/** Gets title for amount column including current display unit if optionsModel reference available. */ /** Gets title for amount column including current display unit if optionsModel reference available. */
QString RecentRequestsTableModel::getAmountTitle() QString RecentRequestsTableModel::getAmountTitle()
{ {
return (this->walletModel->getOptionsModel() != NULL) ? tr("Requested") + " ("+BitcoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")" : ""; return (this->walletModel->getOptionsModel() != nullptr) ? tr("Requested") + " ("+BitcoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")" : "";
} }
QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const

View file

@ -60,7 +60,7 @@ const struct {
{"cmd-reply", ":/icons/tx_output"}, {"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"}, {"misc", ":/icons/tx_inout"},
{NULL, NULL} {nullptr, nullptr}
}; };
namespace { namespace {
@ -532,7 +532,7 @@ void RPCConsole::setClientModel(ClientModel *model)
setNumConnections(model->getNumConnections()); setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(NULL), false); setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(nullptr), false);
connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool))); connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
updateNetworkState(); updateNetworkState();
@ -982,7 +982,7 @@ void RPCConsole::peerLayoutChanged()
if (!clientModel || !clientModel->getPeerTableModel()) if (!clientModel || !clientModel->getPeerTableModel())
return; return;
const CNodeCombinedStats *stats = NULL; const CNodeCombinedStats *stats = nullptr;
bool fUnselect = false; bool fUnselect = false;
bool fReselect = false; bool fReselect = false;

View file

@ -36,8 +36,8 @@ public:
explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent); explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent);
~RPCConsole(); ~RPCConsole();
static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = NULL); static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr);
static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = NULL) { static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr) {
return RPCParseCommandLine(strResult, strCommand, true, pstrFilteredOut); return RPCParseCommandLine(strResult, strCommand, true, pstrFilteredOut);
} }

View file

@ -25,7 +25,7 @@ X509 *parse_b64der_cert(const char* cert_data)
std::vector<unsigned char> data = DecodeBase64(cert_data); std::vector<unsigned char> data = DecodeBase64(cert_data);
assert(data.size() > 0); assert(data.size() > 0);
const unsigned char* dptr = &data[0]; const unsigned char* dptr = &data[0];
X509 *cert = d2i_X509(NULL, &dptr, data.size()); X509 *cert = d2i_X509(nullptr, &dptr, data.size());
assert(cert); assert(cert);
return cert; return cert;
} }
@ -66,7 +66,7 @@ void PaymentServerTests::paymentServerTests()
{ {
SelectParams(CBaseChainParams::MAIN); SelectParams(CBaseChainParams::MAIN);
OptionsModel optionsModel; OptionsModel optionsModel;
PaymentServer* server = new PaymentServer(NULL, false); PaymentServer* server = new PaymentServer(nullptr, false);
X509_STORE* caStore = X509_STORE_new(); X509_STORE* caStore = X509_STORE_new();
X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64)); X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));
PaymentServer::LoadRootCAs(caStore); PaymentServer::LoadRootCAs(caStore);

View file

@ -167,7 +167,7 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx)
// Determine transaction status // Determine transaction status
// Find the block the tx is in // Find the block the tx is in
CBlockIndex* pindex = NULL; CBlockIndex* pindex = nullptr;
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock); BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end()) if (mi != mapBlockIndex.end())
pindex = (*mi).second; pindex = (*mi).second;

View file

@ -343,7 +343,7 @@ void TransactionView::exportClicked()
// CSV is currently the only supported format // CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(this, QString filename = GUIUtil::getSaveFileName(this,
tr("Export Transaction History"), QString(), tr("Export Transaction History"), QString(),
tr("Comma separated file (*.csv)"), NULL); tr("Comma separated file (*.csv)"), nullptr);
if (filename.isNull()) if (filename.isNull())
return; return;

View file

@ -129,7 +129,7 @@ public:
TransactionTableModel *getTransactionTableModel(); TransactionTableModel *getTransactionTableModel();
RecentRequestsTableModel *getRecentRequestsTableModel(); RecentRequestsTableModel *getRecentRequestsTableModel();
CAmount getBalance(const CCoinControl *coinControl = NULL) const; CAmount getBalance(const CCoinControl *coinControl = nullptr) const;
CAmount getUnconfirmedBalance() const; CAmount getUnconfirmedBalance() const;
CAmount getImmatureBalance() const; CAmount getImmatureBalance() const;
bool haveWatchOnly() const; bool haveWatchOnly() const;

View file

@ -246,7 +246,7 @@ void WalletView::backupWallet()
{ {
QString filename = GUIUtil::getSaveFileName(this, QString filename = GUIUtil::getSaveFileName(this,
tr("Backup Wallet"), QString(), tr("Backup Wallet"), QString(),
tr("Wallet Data (*.dat)"), NULL); tr("Wallet Data (*.dat)"), nullptr);
if (filename.isEmpty()) if (filename.isEmpty())
return; return;

View file

@ -57,7 +57,7 @@ void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, c
{ {
typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR); typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR);
PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate"); PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate");
if (shutdownBRCreate == NULL) { if (shutdownBRCreate == nullptr) {
qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed"; qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed";
return; return;
} }

View file

@ -155,7 +155,7 @@ static void RandAddSeedPerfmon()
const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data
while (true) { while (true) {
nSize = vData.size(); nSize = vData.size();
ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, vData.data(), &nSize); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, vData.data(), &nSize);
if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
break; break;
vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially
@ -203,7 +203,7 @@ void GetOSRand(unsigned char *ent32)
{ {
#if defined(WIN32) #if defined(WIN32)
HCRYPTPROV hProvider; HCRYPTPROV hProvider;
int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); int ret = CryptAcquireContextW(&hProvider, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if (!ret) { if (!ret) {
RandFailure(); RandFailure();
} }
@ -257,7 +257,7 @@ void GetOSRand(unsigned char *ent32)
int have = 0; int have = 0;
do { do {
size_t len = NUM_OS_RANDOM_BYTES - have; size_t len = NUM_OS_RANDOM_BYTES - have;
if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0) { if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, nullptr, 0) != 0) {
RandFailure(); RandFailure();
} }
have += len; have += len;

View file

@ -134,7 +134,7 @@ static bool rest_headers(HTTPRequest* req,
if (path.size() != 2) if (path.size() != 2)
return RESTERR(req, HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>."); return RESTERR(req, HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>.");
long count = strtol(path[0].c_str(), NULL, 10); long count = strtol(path[0].c_str(), nullptr, 10);
if (count < 1 || count > 2000) if (count < 1 || count > 2000)
return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]); return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
@ -148,8 +148,8 @@ static bool rest_headers(HTTPRequest* req,
{ {
LOCK(cs_main); LOCK(cs_main);
BlockMap::const_iterator it = mapBlockIndex.find(hash); BlockMap::const_iterator it = mapBlockIndex.find(hash);
const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : NULL; const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : nullptr;
while (pindex != NULL && chainActive.Contains(pindex)) { while (pindex != nullptr && chainActive.Contains(pindex)) {
headers.push_back(pindex); headers.push_back(pindex);
if (headers.size() == (unsigned long)count) if (headers.size() == (unsigned long)count)
break; break;
@ -209,7 +209,7 @@ static bool rest_block(HTTPRequest* req,
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
CBlock block; CBlock block;
CBlockIndex* pblockindex = NULL; CBlockIndex* pblockindex = nullptr;
{ {
LOCK(cs_main); LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0) if (mapBlockIndex.count(hash) == 0)

View file

@ -48,9 +48,9 @@ extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue&
double GetDifficulty(const CBlockIndex* blockindex) double GetDifficulty(const CBlockIndex* blockindex)
{ {
if (blockindex == NULL) if (blockindex == nullptr)
{ {
if (chainActive.Tip() == NULL) if (chainActive.Tip() == nullptr)
return 1.0; return 1.0;
else else
blockindex = chainActive.Tip(); blockindex = chainActive.Tip();

View file

@ -52,7 +52,7 @@ UniValue GetNetworkHashPS(int lookup, int height) {
if (height >= 0 && height < chainActive.Height()) if (height >= 0 && height < chainActive.Height())
pb = chainActive[height]; pb = chainActive[height];
if (pb == NULL || !pb->nHeight) if (pb == nullptr || !pb->nHeight)
return 0; return 0;
// If lookup is -1, then use blocks since last difficulty change. // If lookup is -1, then use blocks since last difficulty change.
@ -139,7 +139,7 @@ UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGen
continue; continue;
} }
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock); std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
if (!ProcessNewBlock(Params(), shared_pblock, true, NULL)) if (!ProcessNewBlock(Params(), shared_pblock, true, nullptr))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted"); throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight; ++nHeight;
blockHashes.push_back(pblock->GetHash().GetHex()); blockHashes.push_back(pblock->GetHash().GetHex());
@ -754,7 +754,7 @@ UniValue submitblock(const JSONRPCRequest& request)
submitblock_StateCatcher sc(block.GetHash()); submitblock_StateCatcher sc(block.GetHash());
RegisterValidationInterface(&sc); RegisterValidationInterface(&sc);
bool fAccepted = ProcessNewBlock(Params(), blockptr, true, NULL); bool fAccepted = ProcessNewBlock(Params(), blockptr, true, nullptr);
UnregisterValidationInterface(&sc); UnregisterValidationInterface(&sc);
if (fBlockPresent) { if (fBlockPresent) {
if (fAccepted && !sc.found) { if (fAccepted && !sc.found) {

View file

@ -78,7 +78,7 @@ UniValue getinfo(const JSONRPCRequest& request)
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
CWallet * const pwallet = GetWalletForJSONRPCRequest(request); CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL); LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
#else #else
LOCK(cs_main); LOCK(cs_main);
#endif #endif
@ -202,7 +202,7 @@ UniValue validateaddress(const JSONRPCRequest& request)
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
CWallet * const pwallet = GetWalletForJSONRPCRequest(request); CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL); LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
#else #else
LOCK(cs_main); LOCK(cs_main);
#endif #endif
@ -322,7 +322,7 @@ UniValue createmultisig(const JSONRPCRequest& request)
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
CWallet * const pwallet = GetWalletForJSONRPCRequest(request); CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
#else #else
CWallet * const pwallet = NULL; CWallet * const pwallet = nullptr;
#endif #endif
if (request.fHelp || request.params.size() < 2 || request.params.size() > 2) if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)

View file

@ -217,7 +217,7 @@ UniValue addnode(const JSONRPCRequest& request)
if (strCommand == "onetry") if (strCommand == "onetry")
{ {
CAddress addr; CAddress addr;
g_connman->OpenNetworkConnection(addr, false, NULL, strNode.c_str()); g_connman->OpenNetworkConnection(addr, false, nullptr, strNode.c_str());
return NullUniValue; return NullUniValue;
} }

View file

@ -208,7 +208,7 @@ UniValue gettxoutproof(const JSONRPCRequest& request)
LOCK(cs_main); LOCK(cs_main);
CBlockIndex* pblockindex = NULL; CBlockIndex* pblockindex = nullptr;
uint256 hashBlock; uint256 hashBlock;
if (!request.params[1].isNull()) if (!request.params[1].isNull())
@ -228,7 +228,7 @@ UniValue gettxoutproof(const JSONRPCRequest& request)
} }
} }
if (pblockindex == NULL) if (pblockindex == nullptr)
{ {
CTransactionRef tx; CTransactionRef tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull()) if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
@ -707,7 +707,7 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
); );
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL); LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
#else #else
LOCK(cs_main); LOCK(cs_main);
#endif #endif
@ -937,7 +937,7 @@ UniValue sendrawtransaction(const JSONRPCRequest& request)
CValidationState state; CValidationState state;
bool fMissingInputs; bool fMissingInputs;
bool fLimitFree = true; bool fLimitFree = true;
if (!AcceptToMemoryPool(mempool, state, std::move(tx), fLimitFree, &fMissingInputs, NULL, false, nMaxRawTxFee)) { if (!AcceptToMemoryPool(mempool, state, std::move(tx), fLimitFree, &fMissingInputs, nullptr, false, nMaxRawTxFee)) {
if (state.IsInvalid()) { if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason())); throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else { } else {

View file

@ -30,7 +30,7 @@ static bool fRPCInWarmup = true;
static std::string rpcWarmupStatus("RPC server started"); static std::string rpcWarmupStatus("RPC server started");
static CCriticalSection cs_rpcWarmup; static CCriticalSection cs_rpcWarmup;
/* Timer-creating functions */ /* Timer-creating functions */
static RPCTimerInterface* timerInterface = NULL; static RPCTimerInterface* timerInterface = nullptr;
/* Map of name to timer. */ /* Map of name to timer. */
static std::map<std::string, std::unique_ptr<RPCTimerBase> > deadlineTimers; static std::map<std::string, std::unique_ptr<RPCTimerBase> > deadlineTimers;
@ -291,7 +291,7 @@ const CRPCCommand *CRPCTable::operator[](const std::string &name) const
{ {
std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end()) if (it == mapCommands.end())
return NULL; return nullptr;
return (*it).second; return (*it).second;
} }
@ -537,7 +537,7 @@ void RPCSetTimerInterface(RPCTimerInterface *iface)
void RPCUnsetTimerInterface(RPCTimerInterface *iface) void RPCUnsetTimerInterface(RPCTimerInterface *iface)
{ {
if (timerInterface == iface) if (timerInterface == iface)
timerInterface = NULL; timerInterface = nullptr;
} }
void RPCRunLater(const std::string& name, std::function<void(void)> func, int64_t nSeconds) void RPCRunLater(const std::string& name, std::function<void(void)> func, int64_t nSeconds)

View file

@ -28,10 +28,10 @@ public:
if (nSize > m_remaining) if (nSize > m_remaining)
throw std::ios_base::failure(std::string(__func__) + ": end of data"); throw std::ios_base::failure(std::string(__func__) + ": end of data");
if (pch == NULL) if (pch == nullptr)
throw std::ios_base::failure(std::string(__func__) + ": bad destination buffer"); throw std::ios_base::failure(std::string(__func__) + ": bad destination buffer");
if (m_data == NULL) if (m_data == nullptr)
throw std::ios_base::failure(std::string(__func__) + ": bad source buffer"); throw std::ios_base::failure(std::string(__func__) + ": bad source buffer");
memcpy(pch, m_data, nSize); memcpy(pch, m_data, nSize);
@ -95,7 +95,7 @@ static int verify_script(const unsigned char *scriptPubKey, unsigned int scriptP
set_error(err, bitcoinconsensus_ERR_OK); set_error(err, bitcoinconsensus_ERR_OK);
PrecomputedTransactionData txdata(tx); PrecomputedTransactionData txdata(tx);
return VerifyScript(tx.vin[nIn].scriptSig, CScript(scriptPubKey, scriptPubKey + scriptPubKeyLen), &tx.vin[nIn].scriptWitness, flags, TransactionSignatureChecker(&tx, nIn, amount, txdata), NULL); return VerifyScript(tx.vin[nIn].scriptSig, CScript(scriptPubKey, scriptPubKey + scriptPubKeyLen), &tx.vin[nIn].scriptWitness, flags, TransactionSignatureChecker(&tx, nIn, amount, txdata), nullptr);
} catch (const std::exception&) { } catch (const std::exception&) {
return set_error(err, bitcoinconsensus_ERR_TX_DESERIALIZE); // Error deserializing return set_error(err, bitcoinconsensus_ERR_TX_DESERIALIZE); // Error deserializing
} }

View file

@ -63,7 +63,7 @@ enum
/// Returns 1 if the input nIn of the serialized transaction pointed to by /// Returns 1 if the input nIn of the serialized transaction pointed to by
/// txTo correctly spends the scriptPubKey pointed to by scriptPubKey under /// txTo correctly spends the scriptPubKey pointed to by scriptPubKey under
/// the additional constraints specified by flags. /// the additional constraints specified by flags.
/// If not NULL, err will contain an error/success code for the operation /// If not nullptr, err will contain an error/success code for the operation
EXPORT_SYMBOL int bitcoinconsensus_verify_script(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen, EXPORT_SYMBOL int bitcoinconsensus_verify_script(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen,
const unsigned char *txTo , unsigned int txToLen, const unsigned char *txTo , unsigned int txToLen,
unsigned int nIn, unsigned int flags, bitcoinconsensus_error* err); unsigned int nIn, unsigned int flags, bitcoinconsensus_error* err);

View file

@ -1407,7 +1407,7 @@ static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion,
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
{ {
static const CScriptWitness emptyWitness; static const CScriptWitness emptyWitness;
if (witness == NULL) { if (witness == nullptr) {
witness = &emptyWitness; witness = &emptyWitness;
} }
bool hadWitness = false; bool hadWitness = false;

View file

@ -123,7 +123,7 @@ enum SigVersion
SIGVERSION_WITNESS_V0 = 1, SIGVERSION_WITNESS_V0 = 1,
}; };
uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache = NULL); uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache = nullptr);
class BaseSignatureChecker class BaseSignatureChecker
{ {
@ -158,7 +158,7 @@ protected:
virtual bool VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const; virtual bool VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const;
public: public:
TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn) : txTo(txToIn), nIn(nInIn), amount(amountIn), txdata(NULL) {} TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn) : txTo(txToIn), nIn(nInIn), amount(amountIn), txdata(nullptr) {}
TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData& txdataIn) : txTo(txToIn), nIn(nInIn), amount(amountIn), txdata(&txdataIn) {} TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData& txdataIn) : txTo(txToIn), nIn(nInIn), amount(amountIn), txdata(&txdataIn) {}
bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override; bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override;
bool CheckLockTime(const CScriptNum& nLockTime) const override; bool CheckLockTime(const CScriptNum& nLockTime) const override;
@ -174,8 +174,8 @@ public:
MutableTransactionSignatureChecker(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn) : TransactionSignatureChecker(&txTo, nInIn, amountIn), txTo(*txToIn) {} MutableTransactionSignatureChecker(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn) : TransactionSignatureChecker(&txTo, nInIn, amountIn), txTo(*txToIn) {}
}; };
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* error = NULL); bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* error = nullptr);
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror = NULL); bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror = nullptr);
size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags); size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags);

View file

@ -498,7 +498,7 @@ public:
bool GetOp(iterator& pc, opcodetype& opcodeRet) bool GetOp(iterator& pc, opcodetype& opcodeRet)
{ {
const_iterator pc2 = pc; const_iterator pc2 = pc;
bool fRet = GetOp2(pc2, opcodeRet, NULL); bool fRet = GetOp2(pc2, opcodeRet, nullptr);
pc = begin() + (pc2 - begin()); pc = begin() + (pc2 - begin());
return fRet; return fRet;
} }
@ -510,7 +510,7 @@ public:
bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
{ {
return GetOp2(pc, opcodeRet, NULL); return GetOp2(pc, opcodeRet, nullptr);
} }
bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const

View file

@ -31,7 +31,7 @@ const char* GetTxnOutputType(txnouttype t)
case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash"; case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash";
case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash"; case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash";
} }
return NULL; return nullptr;
} }
/** /**

View file

@ -479,7 +479,7 @@ public:
{ {
if (file) { if (file) {
::fclose(file); ::fclose(file);
file = NULL; file = nullptr;
} }
} }
@ -487,7 +487,7 @@ public:
* @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller
* of this function to clean up the returned FILE*. * of this function to clean up the returned FILE*.
*/ */
FILE* release() { FILE* ret = file; file = NULL; return ret; } FILE* release() { FILE* ret = file; file = nullptr; return ret; }
/** Get wrapped FILE* without transfer of ownership. /** Get wrapped FILE* without transfer of ownership.
* @note Ownership of the FILE* will remain with this class. Use this only if the scope of the * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the
@ -495,9 +495,9 @@ public:
*/ */
FILE* Get() const { return file; } FILE* Get() const { return file; }
/** Return true if the wrapped FILE* is NULL, false otherwise. /** Return true if the wrapped FILE* is nullptr, false otherwise.
*/ */
bool IsNull() const { return (file == NULL); } bool IsNull() const { return (file == nullptr); }
// //
// Stream subset // Stream subset
@ -508,7 +508,7 @@ public:
void read(char* pch, size_t nSize) void read(char* pch, size_t nSize)
{ {
if (!file) if (!file)
throw std::ios_base::failure("CAutoFile::read: file handle is NULL"); throw std::ios_base::failure("CAutoFile::read: file handle is nullptr");
if (fread(pch, 1, nSize, file) != nSize) if (fread(pch, 1, nSize, file) != nSize)
throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed"); throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
} }
@ -516,7 +516,7 @@ public:
void ignore(size_t nSize) void ignore(size_t nSize)
{ {
if (!file) if (!file)
throw std::ios_base::failure("CAutoFile::ignore: file handle is NULL"); throw std::ios_base::failure("CAutoFile::ignore: file handle is nullptr");
unsigned char data[4096]; unsigned char data[4096];
while (nSize > 0) { while (nSize > 0) {
size_t nNow = std::min<size_t>(nSize, sizeof(data)); size_t nNow = std::min<size_t>(nSize, sizeof(data));
@ -529,7 +529,7 @@ public:
void write(const char* pch, size_t nSize) void write(const char* pch, size_t nSize)
{ {
if (!file) if (!file)
throw std::ios_base::failure("CAutoFile::write: file handle is NULL"); throw std::ios_base::failure("CAutoFile::write: file handle is nullptr");
if (fwrite(pch, 1, nSize, file) != nSize) if (fwrite(pch, 1, nSize, file) != nSize)
throw std::ios_base::failure("CAutoFile::write: write failed"); throw std::ios_base::failure("CAutoFile::write: write failed");
} }
@ -539,7 +539,7 @@ public:
{ {
// Serialize to this stream // Serialize to this stream
if (!file) if (!file)
throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL"); throw std::ios_base::failure("CAutoFile::operator<<: file handle is nullptr");
::Serialize(*this, obj); ::Serialize(*this, obj);
return (*this); return (*this);
} }
@ -549,7 +549,7 @@ public:
{ {
// Unserialize from this stream // Unserialize from this stream
if (!file) if (!file)
throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL"); throw std::ios_base::failure("CAutoFile::operator>>: file handle is nullptr");
::Unserialize(*this, obj); ::Unserialize(*this, obj);
return (*this); return (*this);
} }
@ -616,7 +616,7 @@ public:
{ {
if (src) { if (src) {
::fclose(src); ::fclose(src);
src = NULL; src = nullptr;
} }
} }

View file

@ -45,7 +45,7 @@ struct secure_allocator : public std::allocator<T> {
void deallocate(T* p, std::size_t n) void deallocate(T* p, std::size_t n)
{ {
if (p != NULL) { if (p != nullptr) {
memory_cleanse(p, sizeof(T) * n); memory_cleanse(p, sizeof(T) * n);
} }
LockedPoolManager::Instance().free(p); LockedPoolManager::Instance().free(p);

View file

@ -36,7 +36,7 @@ struct zero_after_free_allocator : public std::allocator<T> {
void deallocate(T* p, std::size_t n) void deallocate(T* p, std::size_t n)
{ {
if (p != NULL) if (p != nullptr)
memory_cleanse(p, sizeof(T) * n); memory_cleanse(p, sizeof(T) * n);
std::allocator<T>::deallocate(p, n); std::allocator<T>::deallocate(p, n);
} }

View file

@ -47,7 +47,7 @@ inline raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request
} }
inline raii_evhttp_connection obtain_evhttp_connection_base(struct event_base* base, std::string host, uint16_t port) { inline raii_evhttp_connection obtain_evhttp_connection_base(struct event_base* base, std::string host, uint16_t port) {
auto result = raii_evhttp_connection(evhttp_connection_base_new(base, NULL, host.c_str(), port)); auto result = raii_evhttp_connection(evhttp_connection_base_new(base, nullptr, host.c_str(), port));
if (!result.get()) if (!result.get())
throw std::runtime_error("create connection failed"); throw std::runtime_error("create connection failed");
return result; return result;

View file

@ -28,7 +28,7 @@
#include <algorithm> #include <algorithm>
LockedPoolManager* LockedPoolManager::_instance = NULL; LockedPoolManager* LockedPoolManager::_instance = nullptr;
std::once_flag LockedPoolManager::init_flag; std::once_flag LockedPoolManager::init_flag;
/*******************************************************************************/ /*******************************************************************************/
@ -87,7 +87,7 @@ template <class Iterator, class Pair> bool extend(Iterator it, const Pair& other
void Arena::free(void *ptr) void Arena::free(void *ptr)
{ {
// Freeing the NULL pointer is OK. // Freeing the nullptr pointer is OK.
if (ptr == nullptr) { if (ptr == nullptr) {
return; return;
} }

View file

@ -100,7 +100,7 @@ static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch,
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry) static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{ {
if (lockstack.get() == NULL) if (lockstack.get() == nullptr)
lockstack.reset(new LockStack); lockstack.reset(new LockStack);
boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex); boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);

View file

@ -265,7 +265,7 @@ public:
fHaveGrant = false; fHaveGrant = false;
} }
CSemaphoreGrant() : sem(NULL), fHaveGrant(false) {} CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {}
CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false) CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false)
{ {

View file

@ -38,12 +38,12 @@ public:
return (unsigned int)(state % nMax); return (unsigned int)(state % nMax);
} }
CAddrInfo* Find(const CNetAddr& addr, int* pnId = NULL) CAddrInfo* Find(const CNetAddr& addr, int* pnId = nullptr)
{ {
return CAddrMan::Find(addr, pnId); return CAddrMan::Find(addr, pnId);
} }
CAddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = NULL) CAddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = nullptr)
{ {
return CAddrMan::Create(addr, addrSource, pnId); return CAddrMan::Create(addr, addrSource, pnId);
} }
@ -340,7 +340,7 @@ BOOST_AUTO_TEST_CASE(addrman_delete)
addrman.Delete(nId); addrman.Delete(nId);
BOOST_CHECK_EQUAL(addrman.size(), 0); BOOST_CHECK_EQUAL(addrman.size(), 0);
CAddrInfo* info2 = addrman.Find(addr1); CAddrInfo* info2 = addrman.Find(addr1);
BOOST_CHECK(info2 == NULL); BOOST_CHECK(info2 == nullptr);
} }
BOOST_AUTO_TEST_CASE(addrman_getaddr) BOOST_AUTO_TEST_CASE(addrman_getaddr)

View file

@ -236,7 +236,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
pblock->nNonce = blockinfo[i].nonce; pblock->nNonce = blockinfo[i].nonce;
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock); std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
BOOST_CHECK(ProcessNewBlock(chainparams, shared_pblock, true, NULL)); BOOST_CHECK(ProcessNewBlock(chainparams, shared_pblock, true, nullptr));
pblock->hashPrevBlock = pblock->GetHash(); pblock->hashPrevBlock = pblock->GetHash();
} }

View file

@ -79,20 +79,20 @@ BOOST_AUTO_TEST_CASE(multisig_verify)
keys.assign(1,key[0]); keys.assign(1,key[0]);
keys.push_back(key[1]); keys.push_back(key[1]);
s = sign_multisig(a_and_b, keys, txTo[0], 0); s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK(VerifyScript(s, a_and_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err)); BOOST_CHECK(VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
keys.assign(1,key[i]); keys.assign(1,key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0); s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 1: %d", i)); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 1: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
keys.assign(1,key[1]); keys.assign(1,key[1]);
keys.push_back(key[i]); keys.push_back(key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0); s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 2: %d", i)); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 2: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
} }
@ -103,18 +103,18 @@ BOOST_AUTO_TEST_CASE(multisig_verify)
s = sign_multisig(a_or_b, keys, txTo[1], 0); s = sign_multisig(a_or_b, keys, txTo[1], 0);
if (i == 0 || i == 1) if (i == 0 || i == 1)
{ {
BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
} }
else else
{ {
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
} }
} }
s.clear(); s.clear();
s << OP_0 << OP_1; s << OP_0 << OP_1;
BOOST_CHECK(!VerifyScript(s, a_or_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err)); BOOST_CHECK(!VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err));
@ -126,12 +126,12 @@ BOOST_AUTO_TEST_CASE(multisig_verify)
s = sign_multisig(escrow, keys, txTo[2], 0); s = sign_multisig(escrow, keys, txTo[2], 0);
if (i < j && i < 3 && j < 3) if (i < j && i < 3 && j < 3)
{ {
BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, NULL, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 1: %d %d", i, j)); BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, nullptr, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 1: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
} }
else else
{ {
BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, NULL, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 2: %d %d", i, j)); BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, nullptr, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 2: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
} }
} }

View file

@ -66,7 +66,7 @@ BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
std::vector<CBlockIndex> blocks(10000); std::vector<CBlockIndex> blocks(10000);
for (int i = 0; i < 10000; i++) { for (int i = 0; i < 10000; i++) {
blocks[i].pprev = i ? &blocks[i - 1] : NULL; blocks[i].pprev = i ? &blocks[i - 1] : nullptr;
blocks[i].nHeight = i; blocks[i].nHeight = i;
blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing; blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing;
blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */ blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */

View file

@ -42,7 +42,7 @@ BOOST_AUTO_TEST_CASE(raii_event_creation)
{ {
event_set_mem_functions(tag_malloc, realloc, tag_free); event_set_mem_functions(tag_malloc, realloc, tag_free);
void* base_ptr = NULL; void* base_ptr = nullptr;
{ {
auto base = obtain_event_base(); auto base = obtain_event_base();
base_ptr = (void*)base.get(); base_ptr = (void*)base.get();
@ -50,10 +50,10 @@ BOOST_AUTO_TEST_CASE(raii_event_creation)
} }
BOOST_CHECK(tags[base_ptr] == 0); BOOST_CHECK(tags[base_ptr] == 0);
void* event_ptr = NULL; void* event_ptr = nullptr;
{ {
auto base = obtain_event_base(); auto base = obtain_event_base();
auto event = obtain_event(base.get(), -1, 0, NULL, NULL); auto event = obtain_event(base.get(), -1, 0, nullptr, nullptr);
base_ptr = (void*)base.get(); base_ptr = (void*)base.get();
event_ptr = (void*)event.get(); event_ptr = (void*)event.get();
@ -71,11 +71,11 @@ BOOST_AUTO_TEST_CASE(raii_event_order)
{ {
event_set_mem_functions(tag_malloc, realloc, tag_free); event_set_mem_functions(tag_malloc, realloc, tag_free);
void* base_ptr = NULL; void* base_ptr = nullptr;
void* event_ptr = NULL; void* event_ptr = nullptr;
{ {
auto base = obtain_event_base(); auto base = obtain_event_base();
auto event = obtain_event(base.get(), -1, 0, NULL, NULL); auto event = obtain_event(base.get(), -1, 0, nullptr, nullptr);
base_ptr = (void*)base.get(); base_ptr = (void*)base.get();
event_ptr = (void*)event.get(); event_ptr = (void*)event.get();

View file

@ -42,7 +42,7 @@ Verify(const CScript& scriptSig, const CScript& scriptPubKey, bool fStrict, Scri
txTo.vin[0].scriptSig = scriptSig; txTo.vin[0].scriptSig = scriptSig;
txTo.vout[0].nValue = 1; txTo.vout[0].nValue = 1;
return VerifyScript(scriptSig, scriptPubKey, NULL, fStrict ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, MutableTransactionSignatureChecker(&txTo, 0, txFrom.vout[0].nValue), &err); return VerifyScript(scriptSig, scriptPubKey, nullptr, fStrict ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, MutableTransactionSignatureChecker(&txTo, 0, txFrom.vout[0].nValue), &err);
} }

View file

@ -172,10 +172,10 @@ void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScript
int libconsensus_flags = flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_ALL; int libconsensus_flags = flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_ALL;
if (libconsensus_flags == flags) { if (libconsensus_flags == flags) {
if (flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS) { if (flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS) {
BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), txCredit.vout[0].nValue, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, NULL) == expect, message); BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), txCredit.vout[0].nValue, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expect, message);
} else { } else {
BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), 0, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, NULL) == expect, message); BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), 0, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expect, message);
BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, NULL) == expect,message); BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expect,message);
} }
} }
#endif #endif
@ -1064,18 +1064,18 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom12); CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom12);
CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12); CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12);
BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, NULL, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
txTo12.vout[0].nValue = 2; txTo12.vout[0].nValue = 2;
BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, NULL, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12); CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12);
BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, NULL, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12); CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12);
BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, NULL, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
} }
@ -1097,54 +1097,54 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
std::vector<CKey> keys; std::vector<CKey> keys;
keys.push_back(key1); keys.push_back(key2); keys.push_back(key1); keys.push_back(key2);
CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23); CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
keys.clear(); keys.clear();
keys.push_back(key1); keys.push_back(key3); keys.push_back(key1); keys.push_back(key3);
CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23); CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
keys.clear(); keys.clear();
keys.push_back(key2); keys.push_back(key3); keys.push_back(key2); keys.push_back(key3);
CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23); CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
keys.clear(); keys.clear();
keys.push_back(key2); keys.push_back(key2); // Can't re-use sig keys.push_back(key2); keys.push_back(key2); // Can't re-use sig
CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23); CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear(); keys.clear();
keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23); CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear(); keys.clear();
keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23); CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear(); keys.clear();
keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23); CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear(); keys.clear();
keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23); CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear(); // Must have signatures keys.clear(); // Must have signatures
CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23); CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, NULL, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
} }
@ -1265,7 +1265,7 @@ BOOST_AUTO_TEST_CASE(script_standard_push)
CScript script; CScript script;
script << i; script << i;
BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push."); BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push.");
BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, NULL, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data."); BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data.");
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
} }
@ -1274,7 +1274,7 @@ BOOST_AUTO_TEST_CASE(script_standard_push)
CScript script; CScript script;
script << data; script << data;
BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push."); BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push.");
BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, NULL, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data."); BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data.");
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
} }
} }

View file

@ -20,7 +20,7 @@ BOOST_AUTO_TEST_CASE(skiplist_test)
for (int i=0; i<SKIPLIST_LENGTH; i++) { for (int i=0; i<SKIPLIST_LENGTH; i++) {
vIndex[i].nHeight = i; vIndex[i].nHeight = i;
vIndex[i].pprev = (i == 0) ? NULL : &vIndex[i - 1]; vIndex[i].pprev = (i == 0) ? nullptr : &vIndex[i - 1];
vIndex[i].BuildSkip(); vIndex[i].BuildSkip();
} }
@ -29,7 +29,7 @@ BOOST_AUTO_TEST_CASE(skiplist_test)
BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]); BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]);
BOOST_CHECK(vIndex[i].pskip->nHeight < i); BOOST_CHECK(vIndex[i].pskip->nHeight < i);
} else { } else {
BOOST_CHECK(vIndex[i].pskip == NULL); BOOST_CHECK(vIndex[i].pskip == nullptr);
} }
} }
@ -51,11 +51,11 @@ BOOST_AUTO_TEST_CASE(getlocator_test)
for (unsigned int i=0; i<vBlocksMain.size(); i++) { for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height, so we can quickly check the distances. vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height, so we can quickly check the distances.
vBlocksMain[i].nHeight = i; vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : nullptr;
vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip(); vBlocksMain[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksMain[i].GetBlockHash()).GetLow64(), vBlocksMain[i].nHeight); BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksMain[i].GetBlockHash()).GetLow64(), vBlocksMain[i].nHeight);
BOOST_CHECK(vBlocksMain[i].pprev == NULL || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1); BOOST_CHECK(vBlocksMain[i].pprev == nullptr || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1);
} }
// Build a branch that splits off at block 49999, 50000 blocks long. // Build a branch that splits off at block 49999, 50000 blocks long.
@ -68,7 +68,7 @@ BOOST_AUTO_TEST_CASE(getlocator_test)
vBlocksSide[i].phashBlock = &vHashSide[i]; vBlocksSide[i].phashBlock = &vHashSide[i];
vBlocksSide[i].BuildSkip(); vBlocksSide[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksSide[i].GetBlockHash()).GetLow64(), vBlocksSide[i].nHeight); BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksSide[i].GetBlockHash()).GetLow64(), vBlocksSide[i].nHeight);
BOOST_CHECK(vBlocksSide[i].pprev == NULL || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1); BOOST_CHECK(vBlocksSide[i].pprev == nullptr || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1);
} }
// Build a CChain for the main branch. // Build a CChain for the main branch.
@ -106,7 +106,7 @@ BOOST_AUTO_TEST_CASE(findearliestatleast_test)
for (unsigned int i=0; i<vBlocksMain.size(); i++) { for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height
vBlocksMain[i].nHeight = i; vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : nullptr;
vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip(); vBlocksMain[i].BuildSkip();
if (i < 10) { if (i < 10) {
@ -138,7 +138,7 @@ BOOST_AUTO_TEST_CASE(findearliestatleast_test)
int64_t test_time = vBlocksMain[r].nTime; int64_t test_time = vBlocksMain[r].nTime;
CBlockIndex *ret = chain.FindEarliestAtLeast(test_time); CBlockIndex *ret = chain.FindEarliestAtLeast(test_time);
BOOST_CHECK(ret->nTimeMax >= test_time); BOOST_CHECK(ret->nTimeMax >= test_time);
BOOST_CHECK((ret->pprev==NULL) || ret->pprev->nTimeMax < test_time); BOOST_CHECK((ret->pprev==nullptr) || ret->pprev->nTimeMax < test_time);
BOOST_CHECK(vBlocksMain[r].GetAncestor(ret->nHeight) == ret); BOOST_CHECK(vBlocksMain[r].GetAncestor(ret->nHeight) == ret);
} }
} }

View file

@ -140,7 +140,7 @@ TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>&
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce; while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce;
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block); std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
ProcessNewBlock(chainparams, shared_pblock, true, NULL); ProcessNewBlock(chainparams, shared_pblock, true, nullptr);
CBlock result = block; CBlock result = block;
return result; return result;

View file

@ -29,7 +29,7 @@ ToMemPool(CMutableTransaction& tx)
LOCK(cs_main); LOCK(cs_main);
CValidationState state; CValidationState state;
return AcceptToMemoryPool(mempool, state, MakeTransactionRef(tx), false, NULL, NULL, true, 0); return AcceptToMemoryPool(mempool, state, MakeTransactionRef(tx), false, nullptr, nullptr, true, 0);
} }
BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup) BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup)

View file

@ -328,7 +328,7 @@ BOOST_AUTO_TEST_CASE(test_ParseInt32)
{ {
int32_t n; int32_t n;
// Valid values // Valid values
BOOST_CHECK(ParseInt32("1234", NULL)); BOOST_CHECK(ParseInt32("1234", nullptr));
BOOST_CHECK(ParseInt32("0", &n) && n == 0); BOOST_CHECK(ParseInt32("0", &n) && n == 0);
BOOST_CHECK(ParseInt32("1234", &n) && n == 1234); BOOST_CHECK(ParseInt32("1234", &n) && n == 1234);
BOOST_CHECK(ParseInt32("01234", &n) && n == 1234); // no octal BOOST_CHECK(ParseInt32("01234", &n) && n == 1234); // no octal
@ -347,17 +347,17 @@ BOOST_AUTO_TEST_CASE(test_ParseInt32)
std::string teststr(test_bytes, sizeof(test_bytes)); std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseInt32(teststr, &n)); // no embedded NULs BOOST_CHECK(!ParseInt32(teststr, &n)); // no embedded NULs
// Overflow and underflow // Overflow and underflow
BOOST_CHECK(!ParseInt32("-2147483649", NULL)); BOOST_CHECK(!ParseInt32("-2147483649", nullptr));
BOOST_CHECK(!ParseInt32("2147483648", NULL)); BOOST_CHECK(!ParseInt32("2147483648", nullptr));
BOOST_CHECK(!ParseInt32("-32482348723847471234", NULL)); BOOST_CHECK(!ParseInt32("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseInt32("32482348723847471234", NULL)); BOOST_CHECK(!ParseInt32("32482348723847471234", nullptr));
} }
BOOST_AUTO_TEST_CASE(test_ParseInt64) BOOST_AUTO_TEST_CASE(test_ParseInt64)
{ {
int64_t n; int64_t n;
// Valid values // Valid values
BOOST_CHECK(ParseInt64("1234", NULL)); BOOST_CHECK(ParseInt64("1234", nullptr));
BOOST_CHECK(ParseInt64("0", &n) && n == 0LL); BOOST_CHECK(ParseInt64("0", &n) && n == 0LL);
BOOST_CHECK(ParseInt64("1234", &n) && n == 1234LL); BOOST_CHECK(ParseInt64("1234", &n) && n == 1234LL);
BOOST_CHECK(ParseInt64("01234", &n) && n == 1234LL); // no octal BOOST_CHECK(ParseInt64("01234", &n) && n == 1234LL); // no octal
@ -377,17 +377,17 @@ BOOST_AUTO_TEST_CASE(test_ParseInt64)
std::string teststr(test_bytes, sizeof(test_bytes)); std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseInt64(teststr, &n)); // no embedded NULs BOOST_CHECK(!ParseInt64(teststr, &n)); // no embedded NULs
// Overflow and underflow // Overflow and underflow
BOOST_CHECK(!ParseInt64("-9223372036854775809", NULL)); BOOST_CHECK(!ParseInt64("-9223372036854775809", nullptr));
BOOST_CHECK(!ParseInt64("9223372036854775808", NULL)); BOOST_CHECK(!ParseInt64("9223372036854775808", nullptr));
BOOST_CHECK(!ParseInt64("-32482348723847471234", NULL)); BOOST_CHECK(!ParseInt64("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseInt64("32482348723847471234", NULL)); BOOST_CHECK(!ParseInt64("32482348723847471234", nullptr));
} }
BOOST_AUTO_TEST_CASE(test_ParseUInt32) BOOST_AUTO_TEST_CASE(test_ParseUInt32)
{ {
uint32_t n; uint32_t n;
// Valid values // Valid values
BOOST_CHECK(ParseUInt32("1234", NULL)); BOOST_CHECK(ParseUInt32("1234", nullptr));
BOOST_CHECK(ParseUInt32("0", &n) && n == 0); BOOST_CHECK(ParseUInt32("0", &n) && n == 0);
BOOST_CHECK(ParseUInt32("1234", &n) && n == 1234); BOOST_CHECK(ParseUInt32("1234", &n) && n == 1234);
BOOST_CHECK(ParseUInt32("01234", &n) && n == 1234); // no octal BOOST_CHECK(ParseUInt32("01234", &n) && n == 1234); // no octal
@ -410,15 +410,15 @@ BOOST_AUTO_TEST_CASE(test_ParseUInt32)
BOOST_CHECK(!ParseUInt32("-2147483648", &n)); BOOST_CHECK(!ParseUInt32("-2147483648", &n));
BOOST_CHECK(!ParseUInt32("4294967296", &n)); BOOST_CHECK(!ParseUInt32("4294967296", &n));
BOOST_CHECK(!ParseUInt32("-1234", &n)); BOOST_CHECK(!ParseUInt32("-1234", &n));
BOOST_CHECK(!ParseUInt32("-32482348723847471234", NULL)); BOOST_CHECK(!ParseUInt32("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseUInt32("32482348723847471234", NULL)); BOOST_CHECK(!ParseUInt32("32482348723847471234", nullptr));
} }
BOOST_AUTO_TEST_CASE(test_ParseUInt64) BOOST_AUTO_TEST_CASE(test_ParseUInt64)
{ {
uint64_t n; uint64_t n;
// Valid values // Valid values
BOOST_CHECK(ParseUInt64("1234", NULL)); BOOST_CHECK(ParseUInt64("1234", nullptr));
BOOST_CHECK(ParseUInt64("0", &n) && n == 0LL); BOOST_CHECK(ParseUInt64("0", &n) && n == 0LL);
BOOST_CHECK(ParseUInt64("1234", &n) && n == 1234LL); BOOST_CHECK(ParseUInt64("1234", &n) && n == 1234LL);
BOOST_CHECK(ParseUInt64("01234", &n) && n == 1234LL); // no octal BOOST_CHECK(ParseUInt64("01234", &n) && n == 1234LL); // no octal
@ -438,9 +438,9 @@ BOOST_AUTO_TEST_CASE(test_ParseUInt64)
std::string teststr(test_bytes, sizeof(test_bytes)); std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseUInt64(teststr, &n)); // no embedded NULs BOOST_CHECK(!ParseUInt64(teststr, &n)); // no embedded NULs
// Overflow and underflow // Overflow and underflow
BOOST_CHECK(!ParseUInt64("-9223372036854775809", NULL)); BOOST_CHECK(!ParseUInt64("-9223372036854775809", nullptr));
BOOST_CHECK(!ParseUInt64("18446744073709551616", NULL)); BOOST_CHECK(!ParseUInt64("18446744073709551616", nullptr));
BOOST_CHECK(!ParseUInt64("-32482348723847471234", NULL)); BOOST_CHECK(!ParseUInt64("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseUInt64("-2147483648", &n)); BOOST_CHECK(!ParseUInt64("-2147483648", &n));
BOOST_CHECK(!ParseUInt64("-9223372036854775808", &n)); BOOST_CHECK(!ParseUInt64("-9223372036854775808", &n));
BOOST_CHECK(!ParseUInt64("-1234", &n)); BOOST_CHECK(!ParseUInt64("-1234", &n));
@ -450,7 +450,7 @@ BOOST_AUTO_TEST_CASE(test_ParseDouble)
{ {
double n; double n;
// Valid values // Valid values
BOOST_CHECK(ParseDouble("1234", NULL)); BOOST_CHECK(ParseDouble("1234", nullptr));
BOOST_CHECK(ParseDouble("0", &n) && n == 0.0); BOOST_CHECK(ParseDouble("0", &n) && n == 0.0);
BOOST_CHECK(ParseDouble("1234", &n) && n == 1234.0); BOOST_CHECK(ParseDouble("1234", &n) && n == 1234.0);
BOOST_CHECK(ParseDouble("01234", &n) && n == 1234.0); // no octal BOOST_CHECK(ParseDouble("01234", &n) && n == 1234.0); // no octal
@ -470,8 +470,8 @@ BOOST_AUTO_TEST_CASE(test_ParseDouble)
std::string teststr(test_bytes, sizeof(test_bytes)); std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseDouble(teststr, &n)); // no embedded NULs BOOST_CHECK(!ParseDouble(teststr, &n)); // no embedded NULs
// Overflow and underflow // Overflow and underflow
BOOST_CHECK(!ParseDouble("-1e10000", NULL)); BOOST_CHECK(!ParseDouble("-1e10000", nullptr));
BOOST_CHECK(!ParseDouble("1e10000", NULL)); BOOST_CHECK(!ParseDouble("1e10000", nullptr));
} }
BOOST_AUTO_TEST_CASE(test_FormatParagraph) BOOST_AUTO_TEST_CASE(test_FormatParagraph)

View file

@ -69,7 +69,7 @@ public:
while (vpblock.size() < height) { while (vpblock.size() < height) {
CBlockIndex* pindex = new CBlockIndex(); CBlockIndex* pindex = new CBlockIndex();
pindex->nHeight = vpblock.size(); pindex->nHeight = vpblock.size();
pindex->pprev = vpblock.size() > 0 ? vpblock.back() : NULL; pindex->pprev = vpblock.size() > 0 ? vpblock.back() : nullptr;
pindex->nTime = nTime; pindex->nTime = nTime;
pindex->nVersion = nVersion; pindex->nVersion = nVersion;
pindex->BuildSkip(); pindex->BuildSkip();
@ -81,7 +81,7 @@ public:
VersionBitsTester& TestStateSinceHeight(int height) { VersionBitsTester& TestStateSinceHeight(int height) {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateSinceHeightFor(vpblock.empty() ? NULL : vpblock.back()) == height, strprintf("Test %i for StateSinceHeight", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateSinceHeightFor(vpblock.empty() ? nullptr : vpblock.back()) == height, strprintf("Test %i for StateSinceHeight", num));
} }
} }
num++; num++;
@ -91,7 +91,7 @@ public:
VersionBitsTester& TestDefined() { VersionBitsTester& TestDefined() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_DEFINED, strprintf("Test %i for DEFINED", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_DEFINED, strprintf("Test %i for DEFINED", num));
} }
} }
num++; num++;
@ -101,7 +101,7 @@ public:
VersionBitsTester& TestStarted() { VersionBitsTester& TestStarted() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_STARTED, strprintf("Test %i for STARTED", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_STARTED, strprintf("Test %i for STARTED", num));
} }
} }
num++; num++;
@ -111,7 +111,7 @@ public:
VersionBitsTester& TestLockedIn() { VersionBitsTester& TestLockedIn() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_LOCKED_IN, strprintf("Test %i for LOCKED_IN", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_LOCKED_IN, strprintf("Test %i for LOCKED_IN", num));
} }
} }
num++; num++;
@ -121,7 +121,7 @@ public:
VersionBitsTester& TestActive() { VersionBitsTester& TestActive() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE", num));
} }
} }
num++; num++;
@ -131,14 +131,14 @@ public:
VersionBitsTester& TestFailed() { VersionBitsTester& TestFailed() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_FAILED, strprintf("Test %i for FAILED", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_FAILED, strprintf("Test %i for FAILED", num));
} }
} }
num++; num++;
return *this; return *this;
} }
CBlockIndex * Tip() { return vpblock.size() ? vpblock.back() : NULL; } CBlockIndex * Tip() { return vpblock.size() ? vpblock.back() : nullptr; }
}; };
BOOST_FIXTURE_TEST_SUITE(versionbits_tests, TestingSetup) BOOST_FIXTURE_TEST_SUITE(versionbits_tests, TestingSetup)
@ -255,7 +255,7 @@ BOOST_AUTO_TEST_CASE(versionbits_computeblockversion)
// Before MedianTimePast of the chain has crossed nStartTime, the bit // Before MedianTimePast of the chain has crossed nStartTime, the bit
// should not be set. // should not be set.
CBlockIndex *lastBlock = NULL; CBlockIndex *lastBlock = nullptr;
lastBlock = firstChain.Mine(2016, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip(); lastBlock = firstChain.Mine(2016, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0); BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0);

View file

@ -138,8 +138,8 @@ void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
size_t n_read_out = 0; size_t n_read_out = 0;
char *line; char *line;
assert(input); assert(input);
// If there is not a whole line to read, evbuffer_readln returns NULL // If there is not a whole line to read, evbuffer_readln returns nullptr
while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != NULL) while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
{ {
std::string s(line, n_read_out); std::string s(line, n_read_out);
free(line); free(line);
@ -210,7 +210,7 @@ bool TorControlConnection::Connect(const std::string &target, const ConnectionCB
b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (!b_conn) if (!b_conn)
return false; return false;
bufferevent_setcb(b_conn, TorControlConnection::readcb, NULL, TorControlConnection::eventcb, this); bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
bufferevent_enable(b_conn, EV_READ|EV_WRITE); bufferevent_enable(b_conn, EV_READ|EV_WRITE);
this->connected = _connected; this->connected = _connected;
this->disconnected = _disconnected; this->disconnected = _disconnected;
@ -333,7 +333,7 @@ static std::map<std::string,std::string> ParseTorReplyMapping(const std::string
if (j == 3 && value[i] > '3') { if (j == 3 && value[i] > '3') {
j--; j--;
} }
escaped_value.push_back(strtol(value.substr(i, j).c_str(), NULL, 8)); escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
// Account for automatic incrementing at loop end // Account for automatic incrementing at loop end
i += j - 1; i += j - 1;
} else { } else {
@ -367,7 +367,7 @@ static std::map<std::string,std::string> ParseTorReplyMapping(const std::string
static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max()) static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
{ {
FILE *f = fsbridge::fopen(filename, "rb"); FILE *f = fsbridge::fopen(filename, "rb");
if (f == NULL) if (f == nullptr)
return std::make_pair(false,""); return std::make_pair(false,"");
std::string retval; std::string retval;
char buffer[128]; char buffer[128];
@ -393,7 +393,7 @@ static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size
static bool WriteBinaryFile(const fs::path &filename, const std::string &data) static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
{ {
FILE *f = fsbridge::fopen(filename, "wb"); FILE *f = fsbridge::fopen(filename, "wb");
if (f == NULL) if (f == nullptr)
return false; return false;
if (fwrite(data.data(), 1, data.size(), f) != data.size()) { if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
fclose(f); fclose(f);

View file

@ -45,7 +45,7 @@ struct LockPoints
// values are still valid even after a reorg. // values are still valid even after a reorg.
CBlockIndex* maxInputBlock; CBlockIndex* maxInputBlock;
LockPoints() : height(0), time(0), maxInputBlock(NULL) { } LockPoints() : height(0), time(0), maxInputBlock(nullptr) { }
}; };
class CTxMemPool; class CTxMemPool;
@ -592,7 +592,7 @@ public:
* pvNoSpendsRemaining, if set, will be populated with the list of outpoints * pvNoSpendsRemaining, if set, will be populated with the list of outpoints
* which are not in mempool which no longer have any spends in this mempool. * which are not in mempool which no longer have any spends in this mempool.
*/ */
void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=NULL); void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=nullptr);
/** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */ /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
int Expire(int64_t time); int Expire(int64_t time);

View file

@ -144,7 +144,7 @@ public:
// Securely erase the memory used by the PRNG // Securely erase the memory used by the PRNG
RAND_cleanup(); RAND_cleanup();
// Shutdown OpenSSL library multithreading support // Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL); CRYPTO_set_locking_callback(nullptr);
// Clear the set of locks now to maintain symmetry with the constructor. // Clear the set of locks now to maintain symmetry with the constructor.
ppmutexOpenSSL.reset(); ppmutexOpenSSL.reset();
} }
@ -173,8 +173,8 @@ static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
* the OS/libc. When the shutdown sequence is fully audited and * the OS/libc. When the shutdown sequence is fully audited and
* tested, explicit destruction of these objects can be implemented. * tested, explicit destruction of these objects can be implemented.
*/ */
static FILE* fileout = NULL; static FILE* fileout = nullptr;
static boost::mutex* mutexDebugLog = NULL; static boost::mutex* mutexDebugLog = nullptr;
static std::list<std::string>* vMsgsBeforeOpenLog; static std::list<std::string>* vMsgsBeforeOpenLog;
static int FileWriteStr(const std::string &str, FILE *fp) static int FileWriteStr(const std::string &str, FILE *fp)
@ -184,7 +184,7 @@ static int FileWriteStr(const std::string &str, FILE *fp)
static void DebugPrintInit() static void DebugPrintInit()
{ {
assert(mutexDebugLog == NULL); assert(mutexDebugLog == nullptr);
mutexDebugLog = new boost::mutex(); mutexDebugLog = new boost::mutex();
vMsgsBeforeOpenLog = new std::list<std::string>; vMsgsBeforeOpenLog = new std::list<std::string>;
} }
@ -194,12 +194,12 @@ void OpenDebugLog()
boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::call_once(&DebugPrintInit, debugPrintInitFlag);
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
assert(fileout == NULL); assert(fileout == nullptr);
assert(vMsgsBeforeOpenLog); assert(vMsgsBeforeOpenLog);
fs::path pathDebug = GetDataDir() / "debug.log"; fs::path pathDebug = GetDataDir() / "debug.log";
fileout = fsbridge::fopen(pathDebug, "a"); fileout = fsbridge::fopen(pathDebug, "a");
if (fileout) { if (fileout) {
setbuf(fileout, NULL); // unbuffered setbuf(fileout, nullptr); // unbuffered
// dump buffered messages from before we opened the log // dump buffered messages from before we opened the log
while (!vMsgsBeforeOpenLog->empty()) { while (!vMsgsBeforeOpenLog->empty()) {
FileWriteStr(vMsgsBeforeOpenLog->front(), fileout); FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
@ -208,7 +208,7 @@ void OpenDebugLog()
} }
delete vMsgsBeforeOpenLog; delete vMsgsBeforeOpenLog;
vMsgsBeforeOpenLog = NULL; vMsgsBeforeOpenLog = nullptr;
} }
struct CLogCategoryDesc struct CLogCategoryDesc
@ -344,7 +344,7 @@ int LogPrintStr(const std::string &str)
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// buffer if we haven't opened the log yet // buffer if we haven't opened the log yet
if (fileout == NULL) { if (fileout == nullptr) {
assert(vMsgsBeforeOpenLog); assert(vMsgsBeforeOpenLog);
ret = strTimestamped.length(); ret = strTimestamped.length();
vMsgsBeforeOpenLog->push_back(strTimestamped); vMsgsBeforeOpenLog->push_back(strTimestamped);
@ -355,8 +355,8 @@ int LogPrintStr(const std::string &str)
if (fReopenDebugLog) { if (fReopenDebugLog) {
fReopenDebugLog = false; fReopenDebugLog = false;
fs::path pathDebug = GetDataDir() / "debug.log"; fs::path pathDebug = GetDataDir() / "debug.log";
if (fsbridge::freopen(pathDebug,"a",fileout) != NULL) if (fsbridge::freopen(pathDebug,"a",fileout) != nullptr)
setbuf(fileout, NULL); // unbuffered setbuf(fileout, nullptr); // unbuffered
} }
ret = FileWriteStr(strTimestamped, fileout); ret = FileWriteStr(strTimestamped, fileout);
@ -503,7 +503,7 @@ static std::string FormatException(const std::exception* pex, const char* pszThr
{ {
#ifdef WIN32 #ifdef WIN32
char pszModule[MAX_PATH] = ""; char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
#else #else
const char* pszModule = "bitcoin"; const char* pszModule = "bitcoin";
#endif #endif
@ -534,7 +534,7 @@ fs::path GetDefaultDataDir()
#else #else
fs::path pathRet; fs::path pathRet;
char* pszHome = getenv("HOME"); char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0) if (pszHome == nullptr || strlen(pszHome) == 0)
pathRet = fs::path("/"); pathRet = fs::path("/");
else else
pathRet = fs::path(pszHome); pathRet = fs::path(pszHome);
@ -791,7 +791,7 @@ void ShrinkDebugFile()
fclose(file); fclose(file);
} }
} }
else if (file != NULL) else if (file != nullptr)
fclose(file); fclose(file);
} }
@ -800,7 +800,7 @@ fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
{ {
char pszPath[MAX_PATH] = ""; char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) if(SHGetSpecialFolderPathA(nullptr, pszPath, nFolder, fCreate))
{ {
return fs::path(pszPath); return fs::path(pszPath);
} }

View file

@ -358,7 +358,7 @@ template <typename Callable> void TraceThread(const char* name, Callable func)
throw; throw;
} }
catch (...) { catch (...) {
PrintExceptionContinue(NULL, name); PrintExceptionContinue(nullptr, name);
throw; throw;
} }
} }

View file

@ -452,7 +452,7 @@ bool ParseInt32(const std::string& str, int32_t *out)
{ {
if (!ParsePrechecks(str)) if (!ParsePrechecks(str))
return false; return false;
char *endp = NULL; char *endp = nullptr;
errno = 0; // strtol will not set errno if valid errno = 0; // strtol will not set errno if valid
long int n = strtol(str.c_str(), &endp, 10); long int n = strtol(str.c_str(), &endp, 10);
if(out) *out = (int32_t)n; if(out) *out = (int32_t)n;
@ -468,7 +468,7 @@ bool ParseInt64(const std::string& str, int64_t *out)
{ {
if (!ParsePrechecks(str)) if (!ParsePrechecks(str))
return false; return false;
char *endp = NULL; char *endp = nullptr;
errno = 0; // strtoll will not set errno if valid errno = 0; // strtoll will not set errno if valid
long long int n = strtoll(str.c_str(), &endp, 10); long long int n = strtoll(str.c_str(), &endp, 10);
if(out) *out = (int64_t)n; if(out) *out = (int64_t)n;
@ -485,7 +485,7 @@ bool ParseUInt32(const std::string& str, uint32_t *out)
return false; return false;
if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range
return false; return false;
char *endp = NULL; char *endp = nullptr;
errno = 0; // strtoul will not set errno if valid errno = 0; // strtoul will not set errno if valid
unsigned long int n = strtoul(str.c_str(), &endp, 10); unsigned long int n = strtoul(str.c_str(), &endp, 10);
if(out) *out = (uint32_t)n; if(out) *out = (uint32_t)n;
@ -502,7 +502,7 @@ bool ParseUInt64(const std::string& str, uint64_t *out)
return false; return false;
if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range
return false; return false;
char *endp = NULL; char *endp = nullptr;
errno = 0; // strtoull will not set errno if valid errno = 0; // strtoull will not set errno if valid
unsigned long long int n = strtoull(str.c_str(), &endp, 10); unsigned long long int n = strtoull(str.c_str(), &endp, 10);
if(out) *out = (uint64_t)n; if(out) *out = (uint64_t)n;
@ -583,7 +583,7 @@ int64_t atoi64(const char* psz)
#ifdef _MSC_VER #ifdef _MSC_VER
return _atoi64(psz); return _atoi64(psz);
#else #else
return strtoll(psz, NULL, 10); return strtoll(psz, nullptr, 10);
#endif #endif
} }
@ -592,7 +592,7 @@ int64_t atoi64(const std::string& str)
#ifdef _MSC_VER #ifdef _MSC_VER
return _atoi64(str.c_str()); return _atoi64(str.c_str());
#else #else
return strtoll(str.c_str(), NULL, 10); return strtoll(str.c_str(), nullptr, 10);
#endif #endif
} }

View file

@ -39,11 +39,11 @@ std::vector<unsigned char> ParseHex(const char* psz);
std::vector<unsigned char> ParseHex(const std::string& str); std::vector<unsigned char> ParseHex(const std::string& str);
signed char HexDigit(char c); signed char HexDigit(char c);
bool IsHex(const std::string& str); bool IsHex(const std::string& str);
std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = nullptr);
std::string DecodeBase64(const std::string& str); std::string DecodeBase64(const std::string& str);
std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const unsigned char* pch, size_t len);
std::string EncodeBase64(const std::string& str); std::string EncodeBase64(const std::string& str);
std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = nullptr);
std::string DecodeBase32(const std::string& str); std::string DecodeBase32(const std::string& str);
std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const unsigned char* pch, size_t len);
std::string EncodeBase32(const std::string& str); std::string EncodeBase32(const std::string& str);

View file

@ -21,7 +21,7 @@ int64_t GetTime()
int64_t mocktime = nMockTime.load(std::memory_order_relaxed); int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
if (mocktime) return mocktime; if (mocktime) return mocktime;
time_t now = time(NULL); time_t now = time(nullptr);
assert(now > 0); assert(now > 0);
return now; return now;
} }

View file

@ -61,7 +61,7 @@ CCriticalSection cs_main;
BlockMap mapBlockIndex; BlockMap mapBlockIndex;
CChain chainActive; CChain chainActive;
CBlockIndex *pindexBestHeader = NULL; CBlockIndex *pindexBestHeader = nullptr;
CWaitableCriticalSection csBestBlock; CWaitableCriticalSection csBestBlock;
CConditionVariable cvBlockChange; CConditionVariable cvBlockChange;
int nScriptCheckThreads = 0; int nScriptCheckThreads = 0;
@ -177,9 +177,9 @@ CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& loc
return chain.Genesis(); return chain.Genesis();
} }
CCoinsViewDB *pcoinsdbview = NULL; CCoinsViewDB *pcoinsdbview = nullptr;
CCoinsViewCache *pcoinsTip = NULL; CCoinsViewCache *pcoinsTip = nullptr;
CBlockTreeDB *pblocktree = NULL; CBlockTreeDB *pblocktree = nullptr;
enum FlushStateMode { enum FlushStateMode {
FLUSH_STATE_NONE, FLUSH_STATE_NONE,
@ -378,7 +378,7 @@ void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool f
while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) { while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
// ignore validation errors in resurrected transactions // ignore validation errors in resurrected transactions
CValidationState stateDummy; CValidationState stateDummy;
if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, NULL, NULL, true)) { if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, nullptr, nullptr, true)) {
// If the transaction doesn't make it in to the mempool, remove any // If the transaction doesn't make it in to the mempool, remove any
// transactions that depend on it (which would now be orphans). // transactions that depend on it (which would now be orphans).
mempool.removeRecursive(**it, MemPoolRemovalReason::REORG); mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
@ -899,7 +899,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
/** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */ /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow) bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
{ {
CBlockIndex *pindexSlow = NULL; CBlockIndex *pindexSlow = nullptr;
LOCK(cs_main); LOCK(cs_main);
@ -1045,7 +1045,7 @@ bool IsInitialBlockDownload()
return false; return false;
if (fImporting || fReindex) if (fImporting || fReindex)
return true; return true;
if (chainActive.Tip() == NULL) if (chainActive.Tip() == nullptr)
return true; return true;
if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork)) if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
return true; return true;
@ -1056,7 +1056,7 @@ bool IsInitialBlockDownload()
return false; return false;
} }
CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL; CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
static void AlertNotify(const std::string& strMessage) static void AlertNotify(const std::string& strMessage)
{ {
@ -1086,7 +1086,7 @@ static void CheckForkWarningConditions()
// If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it) // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
// of our head, drop it // of our head, drop it
if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72) if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
pindexBestForkTip = NULL; pindexBestForkTip = nullptr;
if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
{ {
@ -1226,7 +1226,7 @@ void InitScriptExecutionCache() {
* Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts) * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
* This does not modify the UTXO set. * This does not modify the UTXO set.
* *
* If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline. Any * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
* script checks which are not necessary (eg due to script execution cache hits) are, obviously, * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
* not pushed onto pvChecks/run. * not pushed onto pvChecks/run.
* *
@ -1633,7 +1633,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
assert(pindex); assert(pindex);
// pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
assert((pindex->phashBlock == NULL) || assert((pindex->phashBlock == nullptr) ||
(*pindex->phashBlock == block.GetHash())); (*pindex->phashBlock == block.GetHash()));
int64_t nTimeStart = GetTimeMicros(); int64_t nTimeStart = GetTimeMicros();
@ -1642,7 +1642,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state)); return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
// verify that the view's current state corresponds to the previous block // verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
assert(hashPrevBlock == view.GetBestBlock()); assert(hashPrevBlock == view.GetBestBlock());
// Special case for the genesis block, skipping connection of its transactions // Special case for the genesis block, skipping connection of its transactions
@ -1733,7 +1733,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
CBlockUndo blockundo; CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL); CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
std::vector<int> prevheights; std::vector<int> prevheights;
CAmount nFees = 0; CAmount nFees = 0;
@ -1787,7 +1787,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
std::vector<CScriptCheck> vChecks; std::vector<CScriptCheck> vChecks;
bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */ bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL)) if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
return error("ConnectBlock(): CheckInputs on %s failed with %s", return error("ConnectBlock(): CheckInputs on %s failed with %s",
tx.GetHash().ToString(), FormatStateMessage(state)); tx.GetHash().ToString(), FormatStateMessage(state));
control.Add(vChecks); control.Add(vChecks);
@ -2019,7 +2019,7 @@ void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
} }
} }
// Check the version of the last 100 blocks to see if we need to upgrade: // Check the version of the last 100 blocks to see if we need to upgrade:
for (int i = 0; i < 100 && pindex != NULL; i++) for (int i = 0; i < 100 && pindex != nullptr; i++)
{ {
int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus()); int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0) if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
@ -2052,7 +2052,7 @@ void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
* should make the mempool consistent again by calling UpdateMempoolForReorg. * should make the mempool consistent again by calling UpdateMempoolForReorg.
* with cs_main held. * with cs_main held.
* *
* If disconnectpool is NULL, then no disconnected transactions are added to * If disconnectpool is nullptr, then no disconnected transactions are added to
* disconnectpool (note that the caller is responsible for mempool consistency * disconnectpool (note that the caller is responsible for mempool consistency
* in any case). * in any case).
*/ */
@ -2108,7 +2108,7 @@ static int64_t nTimeChainState = 0;
static int64_t nTimePostConnect = 0; static int64_t nTimePostConnect = 0;
struct PerBlockConnectTrace { struct PerBlockConnectTrace {
CBlockIndex* pindex = NULL; CBlockIndex* pindex = nullptr;
std::shared_ptr<const CBlock> pblock; std::shared_ptr<const CBlock> pblock;
std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs; std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {} PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
@ -2173,7 +2173,7 @@ public:
}; };
/** /**
* Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk. * corresponding to pindexNew, to bypass loading it again from disk.
* *
* The block is added to connectTrace if connection succeeds. * The block is added to connectTrace if connection succeeds.
@ -2238,13 +2238,13 @@ bool static ConnectTip(CValidationState& state, const CChainParams& chainparams,
*/ */
static CBlockIndex* FindMostWorkChain() { static CBlockIndex* FindMostWorkChain() {
do { do {
CBlockIndex *pindexNew = NULL; CBlockIndex *pindexNew = nullptr;
// Find the best candidate header. // Find the best candidate header.
{ {
std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin(); std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
if (it == setBlockIndexCandidates.rend()) if (it == setBlockIndexCandidates.rend())
return NULL; return nullptr;
pindexNew = *it; pindexNew = *it;
} }
@ -2263,7 +2263,7 @@ static CBlockIndex* FindMostWorkChain() {
bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA); bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
if (fFailedChain || fMissingData) { if (fFailedChain || fMissingData) {
// Candidate chain is not usable (either invalid or missing data) // Candidate chain is not usable (either invalid or missing data)
if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)) if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindexNew; pindexBestInvalid = pindexNew;
CBlockIndex *pindexFailed = pindexNew; CBlockIndex *pindexFailed = pindexNew;
// Remove the entire chain from the set. // Remove the entire chain from the set.
@ -2304,7 +2304,7 @@ static void PruneBlockIndexCandidates() {
/** /**
* Try to make some progress towards making pindexMostWork the active block. * Try to make some progress towards making pindexMostWork the active block.
* pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork. * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
*/ */
static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
{ {
@ -2390,8 +2390,8 @@ static bool ActivateBestChainStep(CValidationState& state, const CChainParams& c
static void NotifyHeaderTip() { static void NotifyHeaderTip() {
bool fNotify = false; bool fNotify = false;
bool fInitialBlockDownload = false; bool fInitialBlockDownload = false;
static CBlockIndex* pindexHeaderOld = NULL; static CBlockIndex* pindexHeaderOld = nullptr;
CBlockIndex* pindexHeader = NULL; CBlockIndex* pindexHeader = nullptr;
{ {
LOCK(cs_main); LOCK(cs_main);
pindexHeader = pindexBestHeader; pindexHeader = pindexBestHeader;
@ -2410,7 +2410,7 @@ static void NotifyHeaderTip() {
/** /**
* Make the best chain active, in multiple steps. The result is either failure * Make the best chain active, in multiple steps. The result is either failure
* or an activated best chain. pblock is either NULL or a pointer to a block * or an activated best chain. pblock is either nullptr or a pointer to a block
* that is already loaded (to avoid loading it again from disk). * that is already loaded (to avoid loading it again from disk).
*/ */
bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) { bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
@ -2419,8 +2419,8 @@ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams,
// us in the middle of ProcessNewBlock - do not assume pblock is set // us in the middle of ProcessNewBlock - do not assume pblock is set
// sanely for performance or correctness! // sanely for performance or correctness!
CBlockIndex *pindexMostWork = NULL; CBlockIndex *pindexMostWork = nullptr;
CBlockIndex *pindexNewTip = NULL; CBlockIndex *pindexNewTip = nullptr;
int nStopAtHeight = GetArg("-stopatheight", DEFAULT_STOPATHEIGHT); int nStopAtHeight = GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
do { do {
boost::this_thread::interruption_point(); boost::this_thread::interruption_point();
@ -2434,12 +2434,12 @@ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams,
ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
CBlockIndex *pindexOldTip = chainActive.Tip(); CBlockIndex *pindexOldTip = chainActive.Tip();
if (pindexMostWork == NULL) { if (pindexMostWork == nullptr) {
pindexMostWork = FindMostWorkChain(); pindexMostWork = FindMostWorkChain();
} }
// Whether we have anything to do at all. // Whether we have anything to do at all.
if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip()) if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
return true; return true;
bool fInvalidFound = false; bool fInvalidFound = false;
@ -2449,7 +2449,7 @@ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams,
if (fInvalidFound) { if (fInvalidFound) {
// Wipe cache, we may need another branch now. // Wipe cache, we may need another branch now.
pindexMostWork = NULL; pindexMostWork = nullptr;
} }
pindexNewTip = chainActive.Tip(); pindexNewTip = chainActive.Tip();
pindexFork = chainActive.FindFork(pindexOldTip); pindexFork = chainActive.FindFork(pindexOldTip);
@ -2574,14 +2574,14 @@ bool ResetBlockFailureFlags(CBlockIndex *pindex) {
} }
if (it->second == pindexBestInvalid) { if (it->second == pindexBestInvalid) {
// Reset invalid block marker if it was pointing to one of those. // Reset invalid block marker if it was pointing to one of those.
pindexBestInvalid = NULL; pindexBestInvalid = nullptr;
} }
} }
it++; it++;
} }
// Remove the invalidity flag from all ancestors too. // Remove the invalidity flag from all ancestors too.
while (pindex != NULL) { while (pindex != nullptr) {
if (pindex->nStatus & BLOCK_FAILED_MASK) { if (pindex->nStatus & BLOCK_FAILED_MASK) {
pindex->nStatus &= ~BLOCK_FAILED_MASK; pindex->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(pindex); setDirtyBlockIndex.insert(pindex);
@ -2618,7 +2618,7 @@ static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime); pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew); pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
pindexNew->RaiseValidity(BLOCK_VALID_TREE); pindexNew->RaiseValidity(BLOCK_VALID_TREE);
if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork) if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
pindexBestHeader = pindexNew; pindexBestHeader = pindexNew;
setDirtyBlockIndex.insert(pindexNew); setDirtyBlockIndex.insert(pindexNew);
@ -2641,7 +2641,7 @@ static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& sta
pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS); pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
setDirtyBlockIndex.insert(pindexNew); setDirtyBlockIndex.insert(pindexNew);
if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
std::deque<CBlockIndex*> queue; std::deque<CBlockIndex*> queue;
queue.push_back(pindexNew); queue.push_back(pindexNew);
@ -2655,7 +2655,7 @@ static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& sta
LOCK(cs_nBlockSequenceId); LOCK(cs_nBlockSequenceId);
pindex->nSequenceId = nBlockSequenceId++; pindex->nSequenceId = nBlockSequenceId++;
} }
if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) { if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
setBlockIndexCandidates.insert(pindex); setBlockIndexCandidates.insert(pindex);
} }
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex); std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
@ -2875,7 +2875,7 @@ std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBloc
std::vector<unsigned char> ret(32, 0x00); std::vector<unsigned char> ret(32, 0x00);
if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) { if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
if (commitpos == -1) { if (commitpos == -1) {
uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL); uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin()); CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
CTxOut out; CTxOut out;
out.nValue = 0; out.nValue = 0;
@ -2902,7 +2902,7 @@ std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBloc
* set; UTXO-related validity checks are done in ConnectBlock(). */ * set; UTXO-related validity checks are done in ConnectBlock(). */
static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
{ {
assert(pindexPrev != NULL); assert(pindexPrev != nullptr);
const int nHeight = pindexPrev->nHeight + 1; const int nHeight = pindexPrev->nHeight + 1;
// Check proof of work // Check proof of work
@ -2941,7 +2941,7 @@ static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationSta
static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{ {
const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
// Start enforcing BIP113 (Median Time Past) using versionbits logic. // Start enforcing BIP113 (Median Time Past) using versionbits logic.
int nLockTimeFlags = 0; int nLockTimeFlags = 0;
@ -3026,7 +3026,7 @@ static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state
// Check for duplicate // Check for duplicate
uint256 hash = block.GetHash(); uint256 hash = block.GetHash();
BlockMap::iterator miSelf = mapBlockIndex.find(hash); BlockMap::iterator miSelf = mapBlockIndex.find(hash);
CBlockIndex *pindex = NULL; CBlockIndex *pindex = nullptr;
if (hash != chainparams.GetConsensus().hashGenesisBlock) { if (hash != chainparams.GetConsensus().hashGenesisBlock) {
if (miSelf != mapBlockIndex.end()) { if (miSelf != mapBlockIndex.end()) {
@ -3043,7 +3043,7 @@ static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state
return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
// Get prev block index // Get prev block index
CBlockIndex* pindexPrev = NULL; CBlockIndex* pindexPrev = nullptr;
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi == mapBlockIndex.end()) if (mi == mapBlockIndex.end())
return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found"); return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
@ -3053,7 +3053,7 @@ static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state
if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime())) if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
} }
if (pindex == NULL) if (pindex == nullptr)
pindex = AddToBlockIndex(block); pindex = AddToBlockIndex(block);
if (ppindex) if (ppindex)
@ -3070,7 +3070,7 @@ bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidatio
{ {
LOCK(cs_main); LOCK(cs_main);
for (const CBlockHeader& header : headers) { for (const CBlockHeader& header : headers) {
CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
if (!AcceptBlockHeader(header, state, chainparams, &pindex)) { if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
return false; return false;
} }
@ -3083,7 +3083,7 @@ bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidatio
return true; return true;
} }
/** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */ /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock) static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
{ {
const CBlock& block = *pblock; const CBlock& block = *pblock;
@ -3091,7 +3091,7 @@ static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidation
if (fNewBlock) *fNewBlock = false; if (fNewBlock) *fNewBlock = false;
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
CBlockIndex *pindexDummy = NULL; CBlockIndex *pindexDummy = nullptr;
CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy; CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
if (!AcceptBlockHeader(block, state, chainparams, &pindex)) if (!AcceptBlockHeader(block, state, chainparams, &pindex))
@ -3144,11 +3144,11 @@ static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidation
try { try {
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos; CDiskBlockPos blockPos;
if (dbp != NULL) if (dbp != nullptr)
blockPos = *dbp; blockPos = *dbp;
if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
return error("AcceptBlock(): FindBlockPos failed"); return error("AcceptBlock(): FindBlockPos failed");
if (dbp == NULL) if (dbp == nullptr)
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
AbortNode(state, "Failed to write block"); AbortNode(state, "Failed to write block");
if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus())) if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
@ -3166,7 +3166,7 @@ static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidation
bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock) bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
{ {
{ {
CBlockIndex *pindex = NULL; CBlockIndex *pindex = nullptr;
if (fNewBlock) *fNewBlock = false; if (fNewBlock) *fNewBlock = false;
CValidationState state; CValidationState state;
// Ensure that CheckBlock() passes before calling AcceptBlock, as // Ensure that CheckBlock() passes before calling AcceptBlock, as
@ -3177,7 +3177,7 @@ bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<cons
if (ret) { if (ret) {
// Store to disk // Store to disk
ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock); ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
} }
CheckBlockIndex(chainparams.GetConsensus()); CheckBlockIndex(chainparams.GetConsensus());
if (!ret) { if (!ret) {
@ -3281,7 +3281,7 @@ static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPr
assert(fPruneMode && nManualPruneHeight > 0); assert(fPruneMode && nManualPruneHeight > 0);
LOCK2(cs_main, cs_LastBlockFile); LOCK2(cs_main, cs_LastBlockFile);
if (chainActive.Tip() == NULL) if (chainActive.Tip() == nullptr)
return; return;
// last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip) // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
@ -3323,7 +3323,7 @@ void PruneBlockFilesManual(int nManualPruneHeight)
static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight) static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
{ {
LOCK2(cs_main, cs_LastBlockFile); LOCK2(cs_main, cs_LastBlockFile);
if (chainActive.Tip() == NULL || nPruneTarget == 0) { if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
return; return;
} }
if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) { if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
@ -3381,7 +3381,7 @@ bool CheckDiskSpace(uint64_t nAdditionalBytes)
static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
{ {
if (pos.IsNull()) if (pos.IsNull())
return NULL; return nullptr;
fs::path path = GetBlockPosFilename(pos, prefix); fs::path path = GetBlockPosFilename(pos, prefix);
fs::create_directories(path.parent_path()); fs::create_directories(path.parent_path());
FILE* file = fsbridge::fopen(path, "rb+"); FILE* file = fsbridge::fopen(path, "rb+");
@ -3389,13 +3389,13 @@ static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fRe
file = fsbridge::fopen(path, "wb+"); file = fsbridge::fopen(path, "wb+");
if (!file) { if (!file) {
LogPrintf("Unable to open file %s\n", path.string()); LogPrintf("Unable to open file %s\n", path.string());
return NULL; return nullptr;
} }
if (pos.nPos) { if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) { if (fseek(file, pos.nPos, SEEK_SET)) {
LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string()); LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
fclose(file); fclose(file);
return NULL; return nullptr;
} }
} }
return file; return file;
@ -3418,7 +3418,7 @@ fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
CBlockIndex * InsertBlockIndex(uint256 hash) CBlockIndex * InsertBlockIndex(uint256 hash)
{ {
if (hash.IsNull()) if (hash.IsNull())
return NULL; return nullptr;
// Return existing // Return existing
BlockMap::iterator mi = mapBlockIndex.find(hash); BlockMap::iterator mi = mapBlockIndex.find(hash);
@ -3470,13 +3470,13 @@ bool static LoadBlockIndexDB(const CChainParams& chainparams)
pindex->nChainTx = pindex->nTx; pindex->nChainTx = pindex->nTx;
} }
} }
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL)) if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
setBlockIndexCandidates.insert(pindex); setBlockIndexCandidates.insert(pindex);
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork)) if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindex; pindexBestInvalid = pindex;
if (pindex->pprev) if (pindex->pprev)
pindex->BuildSkip(); pindex->BuildSkip();
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
pindexBestHeader = pindex; pindexBestHeader = pindex;
} }
@ -3574,7 +3574,7 @@ CVerifyDB::~CVerifyDB()
bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth) bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
{ {
LOCK(cs_main); LOCK(cs_main);
if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL) if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
return true; return true;
// Verify blocks in the best chain // Verify blocks in the best chain
@ -3584,7 +3584,7 @@ bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview,
LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CCoinsViewCache coins(coinsview); CCoinsViewCache coins(coinsview);
CBlockIndex* pindexState = chainActive.Tip(); CBlockIndex* pindexState = chainActive.Tip();
CBlockIndex* pindexFailure = NULL; CBlockIndex* pindexFailure = nullptr;
int nGoodTransactions = 0; int nGoodTransactions = 0;
CValidationState state; CValidationState state;
int reportDone = 0; int reportDone = 0;
@ -3777,7 +3777,7 @@ bool RewindBlockIndex(const CChainParams& params)
// of the blockchain). // of the blockchain).
break; break;
} }
if (!DisconnectTip(state, params, NULL)) { if (!DisconnectTip(state, params, nullptr)) {
return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight); return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
} }
// Occasionally flush state to disk. // Occasionally flush state to disk.
@ -3826,7 +3826,7 @@ bool RewindBlockIndex(const CChainParams& params)
} }
} }
if (chainActive.Tip() != NULL) { if (chainActive.Tip() != nullptr) {
// We can't prune block index candidates based on our tip if we have // We can't prune block index candidates based on our tip if we have
// no tip due to chainActive being empty! // no tip due to chainActive being empty!
PruneBlockIndexCandidates(); PruneBlockIndexCandidates();
@ -3851,9 +3851,9 @@ void UnloadBlockIndex()
{ {
LOCK(cs_main); LOCK(cs_main);
setBlockIndexCandidates.clear(); setBlockIndexCandidates.clear();
chainActive.SetTip(NULL); chainActive.SetTip(nullptr);
pindexBestInvalid = NULL; pindexBestInvalid = nullptr;
pindexBestHeader = NULL; pindexBestHeader = nullptr;
mempool.clear(); mempool.clear();
mapBlocksUnlinked.clear(); mapBlocksUnlinked.clear();
vinfoBlockFile.clear(); vinfoBlockFile.clear();
@ -3989,7 +3989,7 @@ bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskB
if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) { if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
LOCK(cs_main); LOCK(cs_main);
CValidationState state; CValidationState state;
if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL)) if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
nLoaded++; nLoaded++;
if (state.IsError()) if (state.IsError())
break; break;
@ -4023,7 +4023,7 @@ bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskB
head.ToString()); head.ToString());
LOCK(cs_main); LOCK(cs_main);
CValidationState dummy; CValidationState dummy;
if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL)) if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
{ {
nLoaded++; nLoaded++;
queue.push_back(pblockrecursive->GetHash()); queue.push_back(pblockrecursive->GetHash());
@ -4070,35 +4070,35 @@ void static CheckBlockIndex(const Consensus::Params& consensusParams)
assert(forward.size() == mapBlockIndex.size()); assert(forward.size() == mapBlockIndex.size());
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL); std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
CBlockIndex *pindex = rangeGenesis.first->second; CBlockIndex *pindex = rangeGenesis.first->second;
rangeGenesis.first++; rangeGenesis.first++;
assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL. assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
// Iterate over the entire block tree, using depth-first search. // Iterate over the entire block tree, using depth-first search.
// Along the way, remember whether there are blocks on the path from genesis // Along the way, remember whether there are blocks on the path from genesis
// block being explored which are the first to have certain properties. // block being explored which are the first to have certain properties.
size_t nNodes = 0; size_t nNodes = 0;
int nHeight = 0; int nHeight = 0;
CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid. CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA. CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0. CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not). CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not). CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not). CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not). CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
while (pindex != NULL) { while (pindex != nullptr) {
nNodes++; nNodes++;
if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex; if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex; if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex; if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex; if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex; if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex; if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex; if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
// Begin: actual consistency checks. // Begin: actual consistency checks.
if (pindex->pprev == NULL) { if (pindex->pprev == nullptr) {
// Genesis block checks. // Genesis block checks.
assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match. assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block. assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
@ -4117,26 +4117,26 @@ void static CheckBlockIndex(const Consensus::Params& consensusParams)
if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA); if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent. assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
// All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set. // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned). assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0)); assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
assert(pindex->nHeight == nHeight); // nHeight must be consistent. assert(pindex->nHeight == nHeight); // nHeight must be consistent.
assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's. assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks. assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
if (pindexFirstInvalid == NULL) { if (pindexFirstInvalid == nullptr) {
// Checks for not-invalid blocks. // Checks for not-invalid blocks.
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents. assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
} }
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) { if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
if (pindexFirstInvalid == NULL) { if (pindexFirstInvalid == nullptr) {
// If this block sorts at least as good as the current tip and // If this block sorts at least as good as the current tip and
// is valid and we have all data for its parents, it must be in // is valid and we have all data for its parents, it must be in
// setBlockIndexCandidates. chainActive.Tip() must also be there // setBlockIndexCandidates. chainActive.Tip() must also be there
// even if some data has been pruned. // even if some data has been pruned.
if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) { if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
assert(setBlockIndexCandidates.count(pindex)); assert(setBlockIndexCandidates.count(pindex));
} }
// If some parent is missing, then it could be that this block was in // If some parent is missing, then it could be that this block was in
@ -4157,13 +4157,13 @@ void static CheckBlockIndex(const Consensus::Params& consensusParams)
} }
rangeUnlinked.first++; rangeUnlinked.first++;
} }
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) { if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
// If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked. // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
assert(foundInUnlinked); assert(foundInUnlinked);
} }
if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked. if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) { if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
// We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent. // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
assert(fHavePruned); // We must have pruned. assert(fHavePruned); // We must have pruned.
// This block may have entered mapBlocksUnlinked if: // This block may have entered mapBlocksUnlinked if:
@ -4175,7 +4175,7 @@ void static CheckBlockIndex(const Consensus::Params& consensusParams)
// So if this block is itself better than chainActive.Tip() and it wasn't in // So if this block is itself better than chainActive.Tip() and it wasn't in
// setBlockIndexCandidates, then it must be in mapBlocksUnlinked. // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) { if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
if (pindexFirstInvalid == NULL) { if (pindexFirstInvalid == nullptr) {
assert(foundInUnlinked); assert(foundInUnlinked);
} }
} }
@ -4196,13 +4196,13 @@ void static CheckBlockIndex(const Consensus::Params& consensusParams)
while (pindex) { while (pindex) {
// We are going to either move to a parent or a sibling of pindex. // We are going to either move to a parent or a sibling of pindex.
// If pindex was the first with a certain property, unset the corresponding variable. // If pindex was the first with a certain property, unset the corresponding variable.
if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL; if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
if (pindex == pindexFirstMissing) pindexFirstMissing = NULL; if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL; if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL; if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL; if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL; if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL; if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
// Find our parent. // Find our parent.
CBlockIndex* pindexPar = pindex->pprev; CBlockIndex* pindexPar = pindex->pprev;
// Find which child we just visited. // Find which child we just visited.
@ -4299,7 +4299,7 @@ bool LoadMempool(void)
CValidationState state; CValidationState state;
if (nTime + nExpiryTimeout > nNow) { if (nTime + nExpiryTimeout > nNow) {
LOCK(cs_main); LOCK(cs_main);
AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, true, NULL, nTime, NULL, false, 0); AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, true, nullptr, nTime, nullptr, false, 0);
if (state.IsValid()) { if (state.IsValid()) {
++count; ++count;
} else { } else {
@ -4375,10 +4375,10 @@ void DumpMempool(void)
//! Guess how far we are in the verification process at the given block index //! Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) { double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
if (pindex == NULL) if (pindex == nullptr)
return 0.0; return 0.0;
int64_t nNow = time(NULL); int64_t nNow = time(nullptr);
double fTxTotal; double fTxTotal;

View file

@ -246,7 +246,7 @@ bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<cons
* @param[in] chainparams The params for the chain we want to connect to * @param[in] chainparams The params for the chain we want to connect to
* @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers
*/ */
bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex=NULL); bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex=nullptr);
/** Check whether enough disk space is available for an incoming block */ /** Check whether enough disk space is available for an incoming block */
bool CheckDiskSpace(uint64_t nAdditionalBytes = 0); bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
@ -255,7 +255,7 @@ FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Translation to a filesystem path */ /** Translation to a filesystem path */
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix); fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
/** Import blocks from an external file */ /** Import blocks from an external file */
bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp = NULL); bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp = nullptr);
/** Ensures we have a genesis block in the block tree, possibly writing one to disk. */ /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
bool LoadGenesisBlock(const CChainParams& chainparams); bool LoadGenesisBlock(const CChainParams& chainparams);
/** Load the block tree and coins database from disk, /** Load the block tree and coins database from disk,
@ -300,7 +300,7 @@ void PruneBlockFilesManual(int nManualPruneHeight);
/** (try to) add transaction to memory pool /** (try to) add transaction to memory pool
* plTxnReplaced will be appended to with all transactions replaced from mempool **/ * plTxnReplaced will be appended to with all transactions replaced from mempool **/
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced = NULL, bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced = nullptr,
bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0); bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0);
/** Convert CValidationState to a human-readable message for logging */ /** Convert CValidationState to a human-readable message for logging */
@ -346,7 +346,7 @@ bool TestLockPointValidity(const LockPoints* lp);
* *
* See consensus/consensus.h for flag definitions. * See consensus/consensus.h for flag definitions.
*/ */
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp = NULL, bool useExistingLockPoints = false); bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false);
/** /**
* Closure representing one script verification * Closure representing one script verification

View file

@ -28,14 +28,14 @@ ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex*
int64_t nTimeTimeout = EndTime(params); int64_t nTimeTimeout = EndTime(params);
// A block's state is always the same as that of the first of its period, so it is computed based on a pindexPrev whose height equals a multiple of nPeriod - 1. // A block's state is always the same as that of the first of its period, so it is computed based on a pindexPrev whose height equals a multiple of nPeriod - 1.
if (pindexPrev != NULL) { if (pindexPrev != nullptr) {
pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod)); pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod));
} }
// Walk backwards in steps of nPeriod to find a pindexPrev whose information is known // Walk backwards in steps of nPeriod to find a pindexPrev whose information is known
std::vector<const CBlockIndex*> vToCompute; std::vector<const CBlockIndex*> vToCompute;
while (cache.count(pindexPrev) == 0) { while (cache.count(pindexPrev) == 0) {
if (pindexPrev == NULL) { if (pindexPrev == nullptr) {
// The genesis block is by definition defined. // The genesis block is by definition defined.
cache[pindexPrev] = THRESHOLD_DEFINED; cache[pindexPrev] = THRESHOLD_DEFINED;
break; break;
@ -112,7 +112,7 @@ BIP9Stats AbstractThresholdConditionChecker::GetStateStatisticsFor(const CBlockI
stats.period = Period(params); stats.period = Period(params);
stats.threshold = Threshold(params); stats.threshold = Threshold(params);
if (pindex == NULL) if (pindex == nullptr)
return stats; return stats;
// Find beginning of period // Find beginning of period
@ -150,12 +150,12 @@ int AbstractThresholdConditionChecker::GetStateSinceHeightFor(const CBlockIndex*
// right now pindexPrev points to the block prior to the block that we are computing for, thus: // right now pindexPrev points to the block prior to the block that we are computing for, thus:
// if we are computing for the last block of a period, then pindexPrev points to the second to last block of the period, and // if we are computing for the last block of a period, then pindexPrev points to the second to last block of the period, and
// if we are computing for the first block of a period, then pindexPrev points to the last block of the previous period. // if we are computing for the first block of a period, then pindexPrev points to the last block of the previous period.
// The parent of the genesis block is represented by NULL. // The parent of the genesis block is represented by nullptr.
pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod)); pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod));
const CBlockIndex* previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod); const CBlockIndex* previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod);
while (previousPeriodParent != NULL && GetStateFor(previousPeriodParent, params, cache) == initialState) { while (previousPeriodParent != nullptr && GetStateFor(previousPeriodParent, params, cache) == initialState) {
pindexPrev = previousPeriodParent; pindexPrev = previousPeriodParent;
previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod); previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod);
} }

View file

@ -27,7 +27,7 @@ enum ThresholdState {
// A map that gives the state for blocks whose height is a multiple of Period(). // A map that gives the state for blocks whose height is a multiple of Period().
// The map is indexed by the block's parent, however, so all keys in the map // The map is indexed by the block's parent, however, so all keys in the map
// will either be NULL or a block with (height + 1) % Period() == 0. // will either be nullptr or a block with (height + 1) % Period() == 0.
typedef std::map<const CBlockIndex*, ThresholdState> ThresholdConditionCache; typedef std::map<const CBlockIndex*, ThresholdState> ThresholdConditionCache;
struct VBDeploymentInfo { struct VBDeploymentInfo {

View file

@ -47,7 +47,7 @@ void CDBEnv::Reset()
fMockDb = false; fMockDb = false;
} }
CDBEnv::CDBEnv() : dbenv(NULL) CDBEnv::CDBEnv() : dbenv(nullptr)
{ {
Reset(); Reset();
} }
@ -56,7 +56,7 @@ CDBEnv::~CDBEnv()
{ {
EnvShutdown(); EnvShutdown();
delete dbenv; delete dbenv;
dbenv = NULL; dbenv = nullptr;
} }
void CDBEnv::Close() void CDBEnv::Close()
@ -125,7 +125,7 @@ void CDBEnv::MakeMock()
dbenv->set_lk_max_objects(10000); dbenv->set_lk_max_objects(10000);
dbenv->set_flags(DB_AUTO_COMMIT, 1); dbenv->set_flags(DB_AUTO_COMMIT, 1);
dbenv->log_set_config(DB_LOG_IN_MEMORY, 1); dbenv->log_set_config(DB_LOG_IN_MEMORY, 1);
int ret = dbenv->open(NULL, int ret = dbenv->open(nullptr,
DB_CREATE | DB_CREATE |
DB_INIT_LOCK | DB_INIT_LOCK |
DB_INIT_LOG | DB_INIT_LOG |
@ -147,10 +147,10 @@ CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type
assert(mapFileUseCount.count(strFile) == 0); assert(mapFileUseCount.count(strFile) == 0);
Db db(dbenv, 0); Db db(dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, NULL, 0); int result = db.verify(strFile.c_str(), nullptr, nullptr, 0);
if (result == 0) if (result == 0)
return VERIFY_OK; return VERIFY_OK;
else if (recoverFunc == NULL) else if (recoverFunc == nullptr)
return RECOVER_FAIL; return RECOVER_FAIL;
// Try to recover: // Try to recover:
@ -170,7 +170,7 @@ bool CDB::Recover(const std::string& filename, void *callbackDataIn, bool (*reco
int64_t now = GetTime(); int64_t now = GetTime();
newFilename = strprintf("%s.%d.bak", filename, now); newFilename = strprintf("%s.%d.bak", filename, now);
int result = bitdb.dbenv->dbrename(NULL, filename.c_str(), NULL, int result = bitdb.dbenv->dbrename(nullptr, filename.c_str(), nullptr,
newFilename.c_str(), DB_AUTO_COMMIT); newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0) if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename); LogPrintf("Renamed %s to %s\n", filename, newFilename);
@ -190,7 +190,7 @@ bool CDB::Recover(const std::string& filename, void *callbackDataIn, bool (*reco
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size()); LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
std::unique_ptr<Db> pdbCopy(new Db(bitdb.dbenv, 0)); std::unique_ptr<Db> pdbCopy(new Db(bitdb.dbenv, 0));
int ret = pdbCopy->open(NULL, // Txn pointer int ret = pdbCopy->open(nullptr, // Txn pointer
filename.c_str(), // Filename filename.c_str(), // Filename
"main", // Logical db name "main", // Logical db name
DB_BTREE, // Database type DB_BTREE, // Database type
@ -299,7 +299,7 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
std::stringstream strDump; std::stringstream strDump;
Db db(dbenv, 0); Db db(dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, &strDump, flags); int result = db.verify(strFile.c_str(), nullptr, &strDump, flags);
if (result == DB_VERIFY_BAD) { if (result == DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage: Database salvage found errors, all data may not be recoverable.\n"); LogPrintf("CDBEnv::Salvage: Database salvage found errors, all data may not be recoverable.\n");
if (!fAggressive) { if (!fAggressive) {
@ -357,7 +357,7 @@ void CDBEnv::CheckpointLSN(const std::string& strFile)
} }
CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb(NULL), activeTxn(NULL) CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr)
{ {
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w')); fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
fFlushOnClose = fFlushOnCloseIn; fFlushOnClose = fFlushOnCloseIn;
@ -367,7 +367,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
} }
const std::string &strFilename = dbw.strFile; const std::string &strFilename = dbw.strFile;
bool fCreate = strchr(pszMode, 'c') != NULL; bool fCreate = strchr(pszMode, 'c') != nullptr;
unsigned int nFlags = DB_THREAD; unsigned int nFlags = DB_THREAD;
if (fCreate) if (fCreate)
nFlags |= DB_CREATE; nFlags |= DB_CREATE;
@ -380,7 +380,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
strFile = strFilename; strFile = strFilename;
++env->mapFileUseCount[strFile]; ++env->mapFileUseCount[strFile];
pdb = env->mapDb[strFile]; pdb = env->mapDb[strFile];
if (pdb == NULL) { if (pdb == nullptr) {
int ret; int ret;
pdb = new Db(env->dbenv, 0); pdb = new Db(env->dbenv, 0);
@ -392,8 +392,8 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
throw std::runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFile)); throw std::runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFile));
} }
ret = pdb->open(NULL, // Txn pointer ret = pdb->open(nullptr, // Txn pointer
fMockDb ? NULL : strFile.c_str(), // Filename fMockDb ? nullptr : strFile.c_str(), // Filename
fMockDb ? strFile.c_str() : "main", // Logical db name fMockDb ? strFile.c_str() : "main", // Logical db name
DB_BTREE, // Database type DB_BTREE, // Database type
nFlags, // Flags nFlags, // Flags
@ -401,7 +401,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
if (ret != 0) { if (ret != 0) {
delete pdb; delete pdb;
pdb = NULL; pdb = nullptr;
--env->mapFileUseCount[strFile]; --env->mapFileUseCount[strFile];
strFile = ""; strFile = "";
throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename)); throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename));
@ -443,8 +443,8 @@ void CDB::Close()
return; return;
if (activeTxn) if (activeTxn)
activeTxn->abort(); activeTxn->abort();
activeTxn = NULL; activeTxn = nullptr;
pdb = NULL; pdb = nullptr;
if (fFlushOnClose) if (fFlushOnClose)
Flush(); Flush();
@ -459,12 +459,12 @@ void CDBEnv::CloseDb(const std::string& strFile)
{ {
{ {
LOCK(cs_db); LOCK(cs_db);
if (mapDb[strFile] != NULL) { if (mapDb[strFile] != nullptr) {
// Close the database handle // Close the database handle
Db* pdb = mapDb[strFile]; Db* pdb = mapDb[strFile];
pdb->close(0); pdb->close(0);
delete pdb; delete pdb;
mapDb[strFile] = NULL; mapDb[strFile] = nullptr;
} }
} }
} }
@ -492,7 +492,7 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
CDB db(dbw, "r"); CDB db(dbw, "r");
Db* pdbCopy = new Db(env->dbenv, 0); Db* pdbCopy = new Db(env->dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer int ret = pdbCopy->open(nullptr, // Txn pointer
strFileRes.c_str(), // Filename strFileRes.c_str(), // Filename
"main", // Logical db name "main", // Logical db name
DB_BTREE, // Database type DB_BTREE, // Database type
@ -527,7 +527,7 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
} }
Dbt datKey(ssKey.data(), ssKey.size()); Dbt datKey(ssKey.data(), ssKey.size());
Dbt datValue(ssValue.data(), ssValue.size()); Dbt datValue(ssValue.data(), ssValue.size());
int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE); int ret2 = pdbCopy->put(nullptr, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0) if (ret2 > 0)
fSuccess = false; fSuccess = false;
} }
@ -541,10 +541,10 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
} }
if (fSuccess) { if (fSuccess) {
Db dbA(env->dbenv, 0); Db dbA(env->dbenv, 0);
if (dbA.remove(strFile.c_str(), NULL, 0)) if (dbA.remove(strFile.c_str(), nullptr, 0))
fSuccess = false; fSuccess = false;
Db dbB(env->dbenv, 0); Db dbB(env->dbenv, 0);
if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0)) if (dbB.rename(strFileRes.c_str(), nullptr, strFile.c_str(), 0))
fSuccess = false; fSuccess = false;
} }
if (!fSuccess) if (!fSuccess)

View file

@ -77,10 +77,10 @@ public:
DbTxn* TxnBegin(int flags = DB_TXN_WRITE_NOSYNC) DbTxn* TxnBegin(int flags = DB_TXN_WRITE_NOSYNC)
{ {
DbTxn* ptxn = NULL; DbTxn* ptxn = nullptr;
int ret = dbenv->txn_begin(NULL, &ptxn, flags); int ret = dbenv->txn_begin(nullptr, &ptxn, flags);
if (!ptxn || ret != 0) if (!ptxn || ret != 0)
return NULL; return nullptr;
return ptxn; return ptxn;
} }
}; };
@ -191,7 +191,7 @@ public:
int ret = pdb->get(activeTxn, &datKey, &datValue, 0); int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
memory_cleanse(datKey.get_data(), datKey.get_size()); memory_cleanse(datKey.get_data(), datKey.get_size());
bool success = false; bool success = false;
if (datValue.get_data() != NULL) { if (datValue.get_data() != nullptr) {
// Unserialize value // Unserialize value
try { try {
CDataStream ssValue((char*)datValue.get_data(), (char*)datValue.get_data() + datValue.get_size(), SER_DISK, CLIENT_VERSION); CDataStream ssValue((char*)datValue.get_data(), (char*)datValue.get_data() + datValue.get_size(), SER_DISK, CLIENT_VERSION);
@ -282,11 +282,11 @@ public:
Dbc* GetCursor() Dbc* GetCursor()
{ {
if (!pdb) if (!pdb)
return NULL; return nullptr;
Dbc* pcursor = NULL; Dbc* pcursor = nullptr;
int ret = pdb->cursor(NULL, &pcursor, 0); int ret = pdb->cursor(nullptr, &pcursor, 0);
if (ret != 0) if (ret != 0)
return NULL; return nullptr;
return pcursor; return pcursor;
} }
@ -306,7 +306,7 @@ public:
int ret = pcursor->get(&datKey, &datValue, fFlags); int ret = pcursor->get(&datKey, &datValue, fFlags);
if (ret != 0) if (ret != 0)
return ret; return ret;
else if (datKey.get_data() == NULL || datValue.get_data() == NULL) else if (datKey.get_data() == nullptr || datValue.get_data() == nullptr)
return 99999; return 99999;
// Convert to streams // Convert to streams
@ -342,7 +342,7 @@ public:
if (!pdb || !activeTxn) if (!pdb || !activeTxn)
return false; return false;
int ret = activeTxn->commit(0); int ret = activeTxn->commit(0);
activeTxn = NULL; activeTxn = nullptr;
return (ret == 0); return (ret == 0);
} }
@ -351,7 +351,7 @@ public:
if (!pdb || !activeTxn) if (!pdb || !activeTxn)
return false; return false;
int ret = activeTxn->abort(); int ret = activeTxn->abort();
activeTxn = NULL; activeTxn = nullptr;
return (ret == 0); return (ret == 0);
} }
@ -366,7 +366,7 @@ public:
return Write(std::string("version"), nVersion); return Write(std::string("version"), nVersion);
} }
bool static Rewrite(CWalletDBWrapper& dbw, const char* pszSkip = NULL); bool static Rewrite(CWalletDBWrapper& dbw, const char* pszSkip = nullptr);
}; };
#endif // BITCOIN_WALLET_DB_H #endif // BITCOIN_WALLET_DB_H

View file

@ -1818,8 +1818,8 @@ UniValue listsinceblock(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
const CBlockIndex* pindex = NULL; // Block index of the specified block or the common ancestor, if the block provided was in a deactivated chain. const CBlockIndex* pindex = nullptr; // Block index of the specified block or the common ancestor, if the block provided was in a deactivated chain.
const CBlockIndex* paltindex = NULL; // Block index of the specified block, even if it's in a deactivated chain. const CBlockIndex* paltindex = nullptr; // Block index of the specified block, even if it's in a deactivated chain.
int target_confirms = 1; int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE; isminefilter filter = ISMINE_SPENDABLE;
@ -2725,10 +2725,10 @@ UniValue listunspent(const JSONRPCRequest& request)
UniValue results(UniValue::VARR); UniValue results(UniValue::VARR);
std::vector<COutput> vecOutputs; std::vector<COutput> vecOutputs;
assert(pwallet != NULL); assert(pwallet != nullptr);
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
pwallet->AvailableCoins(vecOutputs, !include_unsafe, NULL, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth); pwallet->AvailableCoins(vecOutputs, !include_unsafe, nullptr, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
for (const COutput& out : vecOutputs) { for (const COutput& out : vecOutputs) {
CTxDestination address; CTxDestination address;
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey; const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;

View file

@ -14,7 +14,7 @@ void RegisterWalletRPCCommands(CRPCTable &t);
* Figures out what wallet, if any, to use for a JSONRPCRequest. * Figures out what wallet, if any, to use for a JSONRPCRequest.
* *
* @param[in] request JSONRPCRequest that wishes to access a wallet * @param[in] request JSONRPCRequest that wishes to access a wallet
* @return NULL if no wallet should be used, or a pointer to the CWallet * @return nullptr if no wallet should be used, or a pointer to the CWallet
*/ */
CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest& request); CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest& request);

View file

@ -48,7 +48,7 @@ bool OldEncrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char>
bool fOk = true; bool fOk = true;
EVP_CIPHER_CTX_init(ctx); EVP_CIPHER_CTX_init(ctx);
if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0; if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, chKey, chIV) != 0;
if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0; if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0;
if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0; if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0;
EVP_CIPHER_CTX_cleanup(ctx); EVP_CIPHER_CTX_cleanup(ctx);
@ -76,7 +76,7 @@ bool OldDecrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial
bool fOk = true; bool fOk = true;
EVP_CIPHER_CTX_init(ctx); EVP_CIPHER_CTX_init(ctx);
if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0; if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, chKey, chIV) != 0;
if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0; if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0;
if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0; if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0;
EVP_CIPHER_CTX_cleanup(ctx); EVP_CIPHER_CTX_cleanup(ctx);

View file

@ -28,7 +28,7 @@ WalletTestingSetup::~WalletTestingSetup()
{ {
UnregisterValidationInterface(pwalletMain); UnregisterValidationInterface(pwalletMain);
delete pwalletMain; delete pwalletMain;
pwalletMain = NULL; pwalletMain = nullptr;
bitdb.Flush(true); bitdb.Flush(true);
bitdb.Reset(); bitdb.Reset();

Some files were not shown because too many files have changed in this diff Show more