From 2ed2f8964f53d6d0618e7fc652e5bcc03e4e30b5 Mon Sep 17 00:00:00 2001 From: Greg-Griffith Date: Wed, 18 Mar 2020 13:13:42 -0700 Subject: [PATCH] refactor the active network code no longer uses the concept of the active network (mainnet, testnet, regtest). now use only the chain manager to manage the number of active chains on the network and have the network set at launch --- src/.formatted-files | 6 +- src/Makefile.am | 6 +- src/args.cpp | 2 +- src/base58.cpp | 24 +- src/base58.h | 17 +- src/blockgeneration/miner.cpp | 21 +- src/blockgeneration/minter.cpp | 12 +- src/chain/block.cpp | 5 +- src/chain/chainman.cpp | 10 +- src/chain/chainman.h | 11 +- src/chain/chainparams.cpp | 399 ++++++++++++++++++ .../networktemplate.h => chain/chainparams.h} | 76 ++-- src/chain/checkpoints.cpp | 11 +- src/chain/checkpoints.h | 7 +- src/chain/tx.cpp | 21 +- src/consensus/tx_verify.cpp | 9 +- src/eccoind.cpp | 6 +- src/globals.cpp | 6 +- src/httprpc.cpp | 2 +- src/httpserver.cpp | 4 +- src/init.cpp | 56 ++- src/init.h | 3 - src/kernel.cpp | 31 +- src/main.cpp | 83 ++-- src/main.h | 4 +- src/net/addrdb.cpp | 8 +- src/net/messages.cpp | 127 +++--- src/net/net.cpp | 18 +- src/net/net.h | 6 +- src/networks/netman.cpp | 382 ----------------- src/networks/netman.h | 108 ----- src/networks/network.h | 53 --- src/pow.cpp | 4 +- src/processblock.cpp | 116 +++-- src/processblock.h | 6 +- src/processheader.cpp | 10 +- src/processheader.h | 4 +- src/rpc/rpcblockchain.cpp | 87 ++-- src/rpc/rpcdump.cpp | 18 +- src/rpc/rpcmining.cpp | 84 ++-- src/rpc/rpcmisc.cpp | 10 +- src/rpc/rpcnet.cpp | 2 +- src/rpc/rpcrawtransaction.cpp | 32 +- src/rpc/rpcwallet.cpp | 10 +- src/script/interpreter.cpp | 4 +- src/test/base58_tests.cpp | 4 +- src/test/net_tests.cpp | 2 +- src/test/test_bitcoin.cpp | 17 +- src/test/test_bitcoin.h | 4 +- src/txdb.cpp | 6 +- src/util/util.cpp | 4 +- src/verifydb.cpp | 24 +- src/verifydb.h | 4 +- src/wallet/wallet.cpp | 76 ++-- src/zmq/zmqpublishnotifier.cpp | 2 +- 55 files changed, 934 insertions(+), 1130 deletions(-) create mode 100644 src/chain/chainparams.cpp rename src/{networks/networktemplate.h => chain/chainparams.h} (60%) delete mode 100644 src/networks/netman.cpp delete mode 100644 src/networks/netman.h delete mode 100644 src/networks/network.h diff --git a/src/.formatted-files b/src/.formatted-files index 9cae2890..4bee0c15 100644 --- a/src/.formatted-files +++ b/src/.formatted-files @@ -25,6 +25,8 @@ chain/chain.cpp chain/chain.h chain/chainman.cpp chain/chainman.h +chain/chainparams.cpp +chain/chainparams.h chain/checkpoints.cpp chain/checkpoints.h chain/outpoint.h @@ -114,10 +116,6 @@ net/tagdb.cpp net/tagdb.h net/tagstore.cpp net/tagstore.h -networks/netman.cpp -networks/netman.h -networks/network.h -networks/networktemplate.h policy/fees.cpp policy/fees.h policy/policy.cpp diff --git a/src/Makefile.am b/src/Makefile.am index c8624be0..f66a5f28 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -113,9 +113,7 @@ BITCOIN_CORE_H = \ net/routingtag.h \ net/tagdb.h \ net/tagstore.h \ - networks/netman.h \ - networks/network.h \ - networks/networktemplate.h \ + chain/chainparams.h \ policy/fees.h \ policy/policy.h \ pow.h \ @@ -203,6 +201,7 @@ libbitcoin_server_a_SOURCES = \ chain/blockindex.cpp \ chain/chain.cpp \ chain/chainman.cpp \ + chain/chainparams.cpp \ chain/checkpoints.cpp \ chain/tx.cpp \ clientversion.cpp \ @@ -260,7 +259,6 @@ libbitcoin_server_a_SOURCES = \ net/packetmanager.cpp \ net/protocol.cpp \ net/routingtag.cpp \ - networks/netman.cpp \ policy/fees.cpp \ policy/policy.cpp \ pow.cpp \ diff --git a/src/args.cpp b/src/args.cpp index 31739721..cbb12064 100644 --- a/src/args.cpp +++ b/src/args.cpp @@ -8,7 +8,7 @@ #include "args.h" #include "util/util.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "random.h" #include "serialize.h" #include "util/utilstrencodings.h" diff --git a/src/base58.cpp b/src/base58.cpp index fb2804ac..b9fd7dc6 100644 --- a/src/base58.cpp +++ b/src/base58.cpp @@ -224,13 +224,13 @@ class CBitcoinAddressVisitor : public boost::static_visitor bool CBitcoinAddress::Set(const CKeyID &id) { - SetData(pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::PUBKEY_ADDRESS), &id, 20); + SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CBitcoinAddress::Set(const CScriptID &id) { - SetData(pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::SCRIPT_ADDRESS), &id, 20); + SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } @@ -239,12 +239,12 @@ bool CBitcoinAddress::Set(const CTxDestination &dest) return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } -bool CBitcoinAddress::IsValid() const { return IsValid(pnetMan->getActivePaymentNetwork()); } -bool CBitcoinAddress::IsValid(const CNetworkTemplate ¶ms) const +bool CBitcoinAddress::IsValid() const { return IsValid(Params()); } +bool CBitcoinAddress::IsValid(const CChainParams ¶ms) const { bool fCorrectSize = vchData.size() == 20; - bool fKnownVersion = vchVersion == params.Base58Prefix(CNetworkTemplate::PUBKEY_ADDRESS) || - vchVersion == params.Base58Prefix(CNetworkTemplate::SCRIPT_ADDRESS); + bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) || + vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } @@ -254,9 +254,9 @@ CTxDestination CBitcoinAddress::Get() const return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); - if (vchVersion == pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::PUBKEY_ADDRESS)) + if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); - else if (vchVersion == pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::SCRIPT_ADDRESS)) + else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); @@ -264,7 +264,7 @@ CTxDestination CBitcoinAddress::Get() const bool CBitcoinAddress::GetKeyID(CKeyID &keyID) const { - if (!IsValid() || vchVersion != pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::PUBKEY_ADDRESS)) + if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); @@ -275,13 +275,13 @@ bool CBitcoinAddress::GetKeyID(CKeyID &keyID) const bool CBitcoinAddress::IsScript() const { return IsValid() && - vchVersion == pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::SCRIPT_ADDRESS); + vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CBitcoinSecret::SetKey(const CKey &vchSecret) { assert(vchSecret.IsValid()); - SetData(pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::SECRET_KEY), vchSecret.begin(), + SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); @@ -298,7 +298,7 @@ CKey CBitcoinSecret::GetKey() bool CBitcoinSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); - bool fCorrectVersion = vchVersion == pnetMan->getActivePaymentNetwork()->Base58Prefix(CNetworkTemplate::SECRET_KEY); + bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } diff --git a/src/base58.h b/src/base58.h index 2386801c..33fbf718 100644 --- a/src/base58.h +++ b/src/base58.h @@ -17,8 +17,7 @@ #define BITCOIN_BASE58_H #include "key.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "pubkey.h" #include "script/script.h" #include "script/standard.h" @@ -27,7 +26,7 @@ #include #include -extern CNetworkManager *pnetMan; + /** * Encode a byte sequence as a base58-encoded string. @@ -115,7 +114,7 @@ class CBitcoinAddress : public CBase58Data bool Set(const CScriptID &id); bool Set(const CTxDestination &dest); bool IsValid() const; - bool IsValid(const CNetworkTemplate ¶ms) const; + bool IsValid(const CChainParams ¶ms) const; CBitcoinAddress() {} CBitcoinAddress(const CTxDestination &dest) { Set(dest); } @@ -142,7 +141,7 @@ class CBitcoinSecret : public CBase58Data CBitcoinSecret() {} }; -template +template class CBitcoinExtKeyBase : public CBase58Data { public: @@ -150,7 +149,7 @@ class CBitcoinExtKeyBase : public CBase58Data { unsigned char vch[Size]; key.Encode(vch); - SetData(pnetMan->getActivePaymentNetwork()->Base58Prefix(Type), vch, vch + Size); + SetData(Params().Base58Prefix(Type), vch, vch + Size); } K GetKey() @@ -167,13 +166,13 @@ class CBitcoinExtKeyBase : public CBase58Data CBitcoinExtKeyBase(const K &key) { SetKey(key); } CBitcoinExtKeyBase(const std::string &strBase58c) { - SetString(strBase58c.c_str(), pnetMan->getActivePaymentNetwork()->Base58Prefix(Type).size()); + SetString(strBase58c.c_str(), Params().Base58Prefix(Type).size()); } CBitcoinExtKeyBase() {} }; -typedef CBitcoinExtKeyBase CBitcoinExtKey; -typedef CBitcoinExtKeyBase CBitcoinExtPubKey; +typedef CBitcoinExtKeyBase CBitcoinExtKey; +typedef CBitcoinExtKeyBase CBitcoinExtPubKey; #endif // BITCOIN_BASE58_H diff --git a/src/blockgeneration/miner.cpp b/src/blockgeneration/miner.cpp index 51ee594d..07f5f26b 100644 --- a/src/blockgeneration/miner.cpp +++ b/src/blockgeneration/miner.cpp @@ -16,8 +16,7 @@ #include "init.h" #include "kernel.h" #include "net/net.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "policy/policy.h" #include "processblock.h" #include "timedata.h" @@ -130,7 +129,7 @@ std::unique_ptr CreateNewPoWBlock(CWallet *pwallet, const CScrip // ppcoin: if coinstake available add coinstake tx // Commented out unused variable assuming no side effect within GetAdjustedTime() // static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup - CBlockIndex *pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexPrev = g_chainman.chainActive.Tip(); // This vector will be sorted into a priority queue: @@ -151,7 +150,7 @@ std::unique_ptr CreateNewPoWBlock(CWallet *pwallet, const CScrip { LOCK(cs_main); READLOCK(mempool.cs); - CBlockIndex *_pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *_pindexPrev = g_chainman.chainActive.Tip(); const int nHeight = _pindexPrev->nHeight + 1; pblock->nTime = GetAdjustedTime(); const int64_t nMedianTimePast = _pindexPrev->GetMedianTimePast(); @@ -305,7 +304,7 @@ std::unique_ptr CreateNewPoWBlock(CWallet *pwallet, const CScrip pblock->hashPrevBlock = _pindexPrev->GetBlockHash(); pblock->nTime = std::max(_pindexPrev->GetMedianTimePast() + 1, pblock->GetMaxTransactionTime()); pblock->nTime = std::max(pblock->GetBlockTime(), _pindexPrev->GetBlockTime() - nMaxClockDrift); - UpdateTime(pblock, pnetMan->getActivePaymentNetwork()->GetConsensus(), _pindexPrev); + UpdateTime(pblock, Params().GetConsensus(), _pindexPrev); pblock->vtx[0]->vout[0].nValue = GetProofOfWorkReward(nFees, _pindexPrev->nHeight + 1, _pindexPrev->GetBlockHash()); pblock->nNonce = 0; @@ -373,7 +372,7 @@ bool CheckWork(const CBlock *pblock, CWallet &wallet, boost::shared_ptrgetChainActive()->chainActive.Tip(); + CBlockIndex *ptip = g_chainman.chainActive.Tip(); if (ptip == nullptr) { return false; @@ -394,7 +393,7 @@ bool CheckWork(const CBlock *pblock, CWallet &wallet, boost::shared_ptrgetActivePaymentNetwork(); + const CChainParams &chainparams = Params(); if (!ProcessNewBlock(state, chainparams, NULL, pblock, true, NULL)) return error("Miner : ProcessBlock, block not accepted"); } @@ -433,7 +432,7 @@ void EccMiner(CWallet *pwallet) if (shutdown_threads.load() || shutdown_miner_threads.load()) return; } - while (pnetMan->getChainActive()->IsInitialBlockDownload() || pwallet->IsLocked()) + while (g_chainman.IsInitialBlockDownload() || pwallet->IsLocked()) { MilliSleep(1000); if (shutdown_threads.load() || shutdown_miner_threads.load()) @@ -449,7 +448,7 @@ void EccMiner(CWallet *pwallet) // Create new block // unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - CBlockIndex *pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexPrev = g_chainman.chainActive.Tip(); std::unique_ptr pblocktemplate(CreateNewPoWBlock(pwallet, coinbaseScript->reserveScript)); if (!pblocktemplate.get()) { @@ -538,12 +537,12 @@ void EccMiner(CWallet *pwallet) break; if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; - if (pindexPrev != pnetMan->getChainActive()->chainActive.Tip()) + if (pindexPrev != g_chainman.chainActive.Tip()) break; // Update nTime every few seconds pblock->nTime = std::max(pindexPrev->GetMedianTimePast() + 1, pblock->GetMaxTransactionTime()); pblock->nTime = std::max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift); - UpdateTime(pblock, pnetMan->getActivePaymentNetwork()->GetConsensus(), pindexPrev); + UpdateTime(pblock, Params().GetConsensus(), pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (pblock->GetBlockTime() >= (int64_t)pblock->vtx[0]->nTime + nMaxClockDrift) break; // need to update coinbase timestamp diff --git a/src/blockgeneration/minter.cpp b/src/blockgeneration/minter.cpp index 81dd2ba4..6bcd9ad8 100644 --- a/src/blockgeneration/minter.cpp +++ b/src/blockgeneration/minter.cpp @@ -36,7 +36,7 @@ bool CheckStake(const CBlock *pblock, CWallet &wallet, boost::shared_ptrgetChainActive()->chainActive.Tip(); + CBlockIndex *ptip = g_chainman.chainActive.Tip(); if (ptip == nullptr) { return false; @@ -54,7 +54,7 @@ bool CheckStake(const CBlock *pblock, CWallet &wallet, boost::shared_ptrgetActivePaymentNetwork(); + const CChainParams &chainparams = Params(); if (!ProcessNewBlock(state, chainparams, nullptr, pblock, true, nullptr)) { return error("Minter : ProcessBlock, block not accepted"); @@ -97,7 +97,7 @@ std::unique_ptr CreateNewPoSBlock(CWallet *pwallet, const CScrip // ppcoin: if coinstake available add coinstake tx static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup - CBlockIndex *pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexPrev = g_chainman.chainActive.Tip(); // This vector will be sorted into a priority queue: @@ -146,7 +146,7 @@ std::unique_ptr CreateNewPoSBlock(CWallet *pwallet, const CScrip { LOCK(cs_main); READLOCK(mempool.cs); - CBlockIndex *_pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *_pindexPrev = g_chainman.chainActive.Tip(); const int nHeight = _pindexPrev->nHeight + 1; pblock->nTime = GetAdjustedTime(); const int64_t nMedianTimePast = _pindexPrev->GetMedianTimePast(); @@ -340,7 +340,7 @@ void EccMinter(CWallet *pwallet) if (shutdown_threads.load() || shutdown_minter_threads.load()) return; } - while (pnetMan->getChainActive()->IsInitialBlockDownload() || pwallet->IsLocked()) + while (g_chainman.IsInitialBlockDownload() || pwallet->IsLocked()) { MilliSleep(1000); if (shutdown_threads.load() || shutdown_minter_threads.load()) @@ -352,7 +352,7 @@ void EccMinter(CWallet *pwallet) if (shutdown_threads.load() || shutdown_minter_threads.load()) return; } - CBlockIndex *pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexPrev = g_chainman.chainActive.Tip(); std::unique_ptr pblocktemplate(CreateNewPoSBlock(pwallet, coinbaseScript->reserveScript)); if (!pblocktemplate.get()) { diff --git a/src/chain/block.cpp b/src/chain/block.cpp index cffad4fe..8b7d8eb3 100644 --- a/src/chain/block.cpp +++ b/src/chain/block.cpp @@ -11,8 +11,7 @@ #include "crypto/scrypt.h" #include "init.h" #include "main.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "timedata.h" #include "tinyformat.h" #include "util/util.h" @@ -122,7 +121,7 @@ bool CBlock::SignScryptBlock(const CKeyStore &keystore) bool CBlock::CheckBlockSignature() const { - if (GetHash() == pnetMan->getActivePaymentNetwork()->GetConsensus().hashGenesisBlock) + if (GetHash() == Params().GetConsensus().hashGenesisBlock) return vchBlockSig.empty(); std::vector > vSolutions; diff --git a/src/chain/chainman.cpp b/src/chain/chainman.cpp index b4c7a369..01a234c2 100644 --- a/src/chain/chainman.cpp +++ b/src/chain/chainman.cpp @@ -13,7 +13,7 @@ #include "main.h" #include "net/messages.h" #include "net/nodestate.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "processblock.h" #include "processheader.h" #include "txmempool.h" @@ -85,7 +85,7 @@ static std::atomic lockIBDState{false}; bool CChainManager::IsInitialBlockDownload() { - const CNetworkTemplate &chainParams = pnetMan->getActivePaymentNetwork(); + const CChainParams &chainParams = Params(); if (fImporting || fReindex) return true; if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints())) @@ -118,7 +118,7 @@ CBlockIndex *CChainManager::InsertBlockIndex(uint256 hash) return pindexNew; } -bool CChainManager::InitBlockIndex(const CNetworkTemplate &chainparams) +bool CChainManager::InitBlockIndex(const CChainParams &chainparams) { LOCK(cs_main); @@ -151,7 +151,7 @@ bool CChainManager::InitBlockIndex(const CNetworkTemplate &chainparams) } CBlockIndex *pindex = AddToBlockIndex(block); { - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); // ppcoin: compute stake entropy bit for stake modifier if (!pindex->SetStakeEntropyBit(block.GetStakeEntropyBit())) { @@ -330,7 +330,7 @@ bool CChainManager::LoadBlockIndexDB() } -bool CChainManager::LoadExternalBlockFile(const CNetworkTemplate &chainparams, FILE *fileIn, CDiskBlockPos *dbp) +bool CChainManager::LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp) { // std::map of disk positions for blocks with unknown parent (only used for reindex) static std::multimap mapBlocksUnknownParent; diff --git a/src/chain/chainman.h b/src/chain/chainman.h index 559752bc..6c221f05 100644 --- a/src/chain/chainman.h +++ b/src/chain/chainman.h @@ -9,10 +9,9 @@ #include #include "chain.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "txdb.h" - struct BlockHasher { size_t operator()(const uint256 &hash) const { return hash.GetCheapHash(); } @@ -20,7 +19,7 @@ struct BlockHasher typedef std::unordered_map BlockMap; -/** Manages the BlockMap and CChain's for a given protocol. */ +/** Manages the BlockMap and CChain's for the activated network ( Network() ). */ class CChainManager { public: @@ -79,7 +78,7 @@ class CChainManager bool IsInitialBlockDownload(); /** Initialize a new block tree database + block data on disk */ - bool InitBlockIndex(const CNetworkTemplate &chainparams); + bool InitBlockIndex(const CChainParams &chainparams); /** Create a new block index entry for a given block hash loaded from disk*/ CBlockIndex *InsertBlockIndex(uint256 hash); @@ -88,10 +87,12 @@ class CChainManager bool LoadBlockIndex(); /** Import blocks from an external file */ - bool LoadExternalBlockFile(const CNetworkTemplate &chainparams, FILE *fileIn, CDiskBlockPos *dbp = NULL); + bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp = NULL); /** Unload database information */ void UnloadBlockIndex(); }; +extern CChainManager g_chainman; + #endif // CHAINMAN_H diff --git a/src/chain/chainparams.cpp b/src/chain/chainparams.cpp new file mode 100644 index 00000000..3129f804 --- /dev/null +++ b/src/chain/chainparams.cpp @@ -0,0 +1,399 @@ +// This file is part of the Eccoin project +// Copyright (c) 2017-2018 Greg Griffith +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "chainparams.h" + +#include "args.h" +#include "consensus/merkle.h" +#include "tinyformat.h" +#include "util/util.h" + +#include + +extern CChainParams chainparams; + +const CChainParams &Params() +{ + return chainparams; +} + +void AppendParamsHelpMessages(std::string &strUsage, bool debugHelp) +{ + strUsage += HelpMessageGroup("Chain selection options:"); + strUsage += HelpMessageOpt("-testnet", "Use the test chain"); + if (debugHelp) + { + strUsage += HelpMessageOpt("-regtest", + "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. " + "This is intended for regression testing tools and app development."); + } +} + +class CLegacyNetwork : public CChainParams +{ +public: + CLegacyNetwork() + { + strNetworkID = "LEGACY"; + strNetworkDataDir = ""; + consensus.nMajorityEnforceBlockUpgrade = 750; + consensus.nMajorityRejectBlockOutdated = 950; + consensus.nMajorityWindow = 1000; + consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + consensus.posLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + consensus.nTargetTimespan = 30 * 45; + consensus.nTargetSpacing = 45; + consensus.fPowAllowMinDifficultyBlocks = false; + consensus.fPowNoRetargeting = false; + consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 + consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nTargetSpacing + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 + + /** + * The message start string is designed to be unlikely to occur in normal data. + * The characters are rarely used upper ASCII, not valid as UTF-8, and produce + * a large 32-bit integer with any alignment. + */ + pchMessageStart[0] = 0xce; + pchMessageStart[1] = 0xf1; + pchMessageStart[2] = 0xdb; + pchMessageStart[3] = 0xfa; + nDefaultPort = 19118; + nRPCPort = 19119; + nMaxTipAge = 24 * 60 * 60; + nStakeMaxAge = 60 * 60 * 24 * 84; // 84 days + nStakeMinAge = 60 * 60 * 2; // 2 hours + + const char *pszTimestamp = + "AP | Mar 2, 2014, 10.35 AM IST: China blames Uighur separatists for knife attack; 33 dead"; + CTransaction txNew; + txNew.nTime = 1393744287; + txNew.vin.resize(1); + txNew.vout.resize(1); + txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(9999) + << std::vector((const unsigned char *)pszTimestamp, + (const unsigned char *)pszTimestamp + strlen(pszTimestamp)); + txNew.vout[0].SetEmpty(); + + genesis.vtx.push_back(MakeTransactionRef(txNew)); + genesis.hashPrevBlock.SetNull(); + genesis.nVersion = 1; + genesis.nTime = 1393744307; + genesis.nBits = 0x1e0fffff; + genesis.nNonce = 12799721; + genesis.hashMerkleRoot = BlockMerkleRoot(genesis); + + consensus.hashGenesisBlock = genesis.GetHash(); + assert(consensus.hashGenesisBlock == + uint256S("0xa60ac43c88dbc44b826cf315352a8a7b373d2af8b6e1c4c4a0638859c5e9ecd1")); + assert(genesis.hashMerkleRoot == + uint256S("0x4db82fe8b45f3dae2b7c7b8be5ec4c37e72e25eaf989b9db24ce1d0fd37eed8b")); + + vSeeds.push_back(CDNSSeedData("ECC-Seed1", "eccserver1.ddns.net", true)); + vSeeds.push_back(CDNSSeedData("ECC-Seed2", "eccnode.altj.com", true)); + vSeeds.push_back(CDNSSeedData("ECC-Seed3", "5.189.131.197", true)); + vSeeds.push_back(CDNSSeedData("ECC-Seed4", "185.21.216.160", true)); + + base58Prefixes[CChainParams::PUBKEY_ADDRESS] = std::vector(1, 33); + base58Prefixes[CChainParams::SCRIPT_ADDRESS] = std::vector(1, 8); + base58Prefixes[CChainParams::SECRET_KEY] = std::vector(1, 161); + base58Prefixes[CChainParams::EXT_PUBLIC_KEY] = {(0x04),(0x88),(0xB2),(0x1E)}; + base58Prefixes[CChainParams::EXT_SECRET_KEY] = {(0x04),(0x88),(0xAD),(0xE4)}; + + fMiningRequiresPeers = true; + fDefaultConsistencyChecks = false; + fRequireStandard = true; + fMineBlocksOnDemand = false; + fTestnetToBeDeprecatedFieldRPC = false; + + mapCheckpoints = + { + {0, uint256S("0xa60ac43c88dbc44b826cf315352a8a7b373d2af8b6e1c4c4a0638859c5e9ecd1")}, + {1, uint256S("0x00000762d19a3a38458e73de6c937fd483f17bd75f55d7fe4e95713f51d6b816")}, + {2, uint256S("0x00000ea50ea0cae64779ff4bb4a0ee94841e2ee20642641a062cbdd342e0a3c5")}, + {3, uint256S("0x00000513cc6f4bec8d7e7bd0ded854200b6c784c8c830a3e4fd0cccc2cb9e58c")}, + {1000, uint256S("0x000000000df3f7a5f719c247782d7a43d75186ebc043341e2668320f9d940bcd")}, + {10000, uint256S("0x00000000076d45a9579c879d46354dd81eeba7060a9a065e13c9dd1c28f474d1")}, + {23920, uint256S("0x000000000331540c766c4ac667a6fbc65ff93f5a30fbb0c6822986885b1b56c0")}, + {36918, uint256S("0x0000000001353725582b099cdd3c89933bbd08a17ace464fba935ecfc41572ef")}, + {50000, uint256S("0x0000000001c770384cd12a74eb5456358425fc6a94a250c3466aaa2ca7460131")}, + {86401, uint256S("0x51bb1ac3ffd009c12791b9d4320dec0ba69e15c8b6d03d17889b0c09fb5b05a4")}, + {86402, uint256S("0xa9f3141e571231e02b4fb649370af6173e1a80a9e0d21aa8859bd17ce1260a05")}, + {86403, uint256S("0xf6c11aadca44fce2390107e229d4d0d70f7cf64266b959672711c68e0f411af5")}, + {86759, uint256S("0x5c6ed2e23ccc27d59a0659a9a32a4c0ca97d829249277c6a35918f4ec94b1748")}, + {86761, uint256S("0xca305a45c9f8a89c050f004d0438b38f190fe6bfe51128f0c3e864ddcf2c765c")}, + {86901, uint256S("0xe769d38b7e140267b688f9d9cc6b58d38185427facb6a1aa719db60a0d54f3f7")}, + {87000, uint256S("0xbb069ba59aa5a6acc68413ef7c2d0c009b061daf160edf958738d197a059f11d")}, + {87101, uint256S("0x1ffbfd2a70e626d5f848775851e6f89bee6f2225ed78131b16f9547449d2e2ee")}, + {96500, uint256S("0x13f0755045a3ae90d33c4bcf6ba1581025fc6e0caf46f7624063cb59dcc3d27c")}, + {100000, uint256S("0x28a483386650a188c3346fd5e329e2c8cc137cf3557547e8525f5cdea601501a")}, + {136500, uint256S("0x7e4ec82a165762e8a324038ef1cdd0b83e603f4737ae6f9e5967b13b8b6ace5c")}, + {150000, uint256S("0xfee6d00910e8d0aa2f0ca8a447b4de366a12f9df2521f77c5a97a5ae0af8834e")}, + {185000, uint256S("0xce904504a0df58944c6a633b739abcec3bbb256b510a616b465c24525d564828")}, + {197712, uint256S("0x7576d0f370b1efdce01075a9491fb8d2f98af485f78d170196270f1eb156ee40")}, + {200000, uint256S("0x1f1ea51aee8a7456655e31857c7cd4a9f494556438485abd4c60d86cacf24b44")}, + {205000, uint256S("0x9e4528bc818bb1ee2cdf44ba7805e88b4fc85bbf496516f35d4d642c6812503e")}, + {209762, uint256S("0x49448f382f9ec8f126542244573e7349c7b07db0cbdc2ab8326942cbfff603b3")}, + {209786, uint256S("0x28558eedf7f5c049e9f2ea61da270fffc5b50310aafb29c7595840784e8b1d61")}, + {215650, uint256S("0xd7fb37df6be4bf2c5c9ea47ba4a14f9af35c326cd225122b03f61b74d1283d09")}, + {215690, uint256S("0x8af4d5450c238460a4775b19c94872eaf5664657f702bef53576bc9f77af319d")}, + {220504, uint256S("0x5781d160a46a6631a21e62a9a67932d0f9b8636c8f5241973b076db3854de405")}, + {221000, uint256S("0x51cd22cde58a3738e851f155a282b4624d3e18e84fbcb02de5006029dec8f7e3")}, + {233855, uint256S("0x77c1312f0b4ba0fc34cb7a0f3472012739bbd22c317add69edaa4908e83b00eb")}, + {236850, uint256S("0x139203f72c943433880c4f8d3581a4cb7ee0877f341639cd4c7810edc7fc7d80")}, + {237000, uint256S("0x70fdb4f39e571afff137c7bd40c4df98ccab32cec1d305074bac9fca30754bc0")}, + {241130, uint256S("0xdd900777cb9e2ea2cae0bf410ce2f2484a415c7bf7af59d9492868195583e3b2")}, + {242150, uint256S("0xba96de8da95ac53cedc7fd0cd3c17b32f5d3a04f33a544060606c095b28bf4c1")}, + {300000, uint256S("0x2c654dfa9f1ab51a64509910b1f053fc20d572022480814988c36f042cb3010b")}, + {350000, uint256S("0xfdb1df53f4365d494d9fa54247a533cbfcd9b6992491f40c8ccfeed454932a70")}, + {400000, uint256S("0xc04d360938d5ff66294100a10424f7e284abe76d117f28460e16752edeb03444")}, + {435000, uint256S("0x801a211aa479129e42554bc812d624e585e1b0dd608e23b1a7f87a9d14e7fdec")}, + {450000, uint256S("0x53e21a2574ff6acc0f31640c4058554dde2fe8972ec72867403e8b88e9ba1bc6")}, + {500000, uint256S("0x779f22407cf9fa0adb8a361918ccf249ef913070ce368070c1ac5063005e3e3c")}, + {550000, uint256S("0xf340b738c21c0a9b6b2eff0f40d9ab3fca9830d8597131680cd5a2615594cfb0")}, + {600000, uint256S("0x589fc3d25c15caaa468dc8b4249e1cbb6ea18368897bd3b1d80f1404486e3783")}, + {650000, uint256S("0xc28634f7211ff0582dfe8df1849711a9bd7815005e59dff0059a20876c465f51")}, + {675000, uint256S("0xe1aca23bd72ad9d153767272f43d33a0542d2a61a78e281341d0f12cd0521024")}, + {675500, uint256S("0x26ccdf8bcb1a50ecef8f507de74ff030789aa1b52491fc4a4de4e4679d53a398")}, + {687345, uint256S("0xae2e43c35a3346fa798a0a356ca7a4bce57885ee64e4319295f7f3b7210944f1")}, + {700000, uint256S("0x0ab361e8acd391c6b5e726eb4704dd8d60e2e3b3f8856e2f7d6373c9a3e0da36")}, + {702950, uint256S("0x26d2cd7b13f1aaa34ffc379696d0e5b14c2ddf8ef2c2c78348fec23f8b55e8ff")}, + {1030250, uint256S("0x434ee5c39b6ba186d66cbfaaa8004910b3556726f990b9f33bb48b9fc280c5de")}, + {1491250, uint256S("0x45a01a2b45ca91433c8c12378914463bd13afc410b27eeb18855d5b060d7e270")}, + {1492500, uint256S("0xd4185d9ae0c38211ac6e0ceddcca4207a00fc59d11b087e76c9bf6d4081856c8")}, + {1493040, uint256S("0xcd266ca5eaca1f561d3adf5ab0bc4994ea26418dd12d9072d5c5194639c40ac2")} + }; + } +}; +static CLegacyNetwork static_CLegacyNetwork; + +class CTestnet0Network : public CChainParams +{ +public: + CTestnet0Network() + { + strNetworkID = "TESTNET0"; + strNetworkDataDir = "testnet0"; + consensus.nMajorityEnforceBlockUpgrade = 750; + consensus.nMajorityRejectBlockOutdated = 950; + consensus.nMajorityWindow = 1000; + consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + consensus.posLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + consensus.nTargetTimespan = 30 * 45; + consensus.nTargetSpacing = 45; + consensus.fPowAllowMinDifficultyBlocks = true; + consensus.fPowNoRetargeting = true; + consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 + consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nTargetSpacing + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; + // January 1, 2008 + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; + // December 31, 2008 + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; + + /** + * The message start string is designed to be unlikely to occur in normal data. + * The characters are rarely used upper ASCII, not valid as UTF-8, and produce + * a large 32-bit integer with any alignment. + */ + pchMessageStart[0] = 0xee; + pchMessageStart[1] = 0xff; + pchMessageStart[2] = 0xaa; + pchMessageStart[3] = 0xbb; + nDefaultPort = 30000; + nRPCPort = 30001; + nMaxTipAge = 24 * 60 * 60; + nStakeMaxAge = 60 * 60 * 24 * 84; // 84 days + nStakeMinAge = 60 * 2; // 2 minutes + + const char *pszTimestamp = "AP | Sep 12, 2018, Testing0 begins"; + CTransaction txNew; + txNew.nTime = 1536781520; + txNew.vin.resize(1); + txNew.vout.resize(1); + txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(9999) + << std::vector((const unsigned char *)pszTimestamp, + (const unsigned char *)pszTimestamp + strlen(pszTimestamp)); + txNew.vout[0].SetEmpty(); + + genesis.vtx.push_back(MakeTransactionRef(txNew)); + genesis.hashPrevBlock.SetNull(); + genesis.nVersion = 1; + genesis.nTime = 1536781520; + genesis.nBits = 0x1e0fffff; + genesis.nNonce = 12799721; + genesis.hashMerkleRoot = BlockMerkleRoot(genesis); + + consensus.hashGenesisBlock = genesis.GetHash(); + assert(consensus.hashGenesisBlock == + uint256S("0xcdf2b68d2fc9afdf991df5e321f59198189926ee757bf5efcf5c8c1a07b7c90e")); + assert(genesis.hashMerkleRoot == + uint256S("0x68d635c49ffdd2bf5edf78149d0e2ea7dff97901d4596e865b87919853085311")); + + base58Prefixes[CChainParams::PUBKEY_ADDRESS] = std::vector(1, 51); + base58Prefixes[CChainParams::SCRIPT_ADDRESS] = std::vector(1, 15); + base58Prefixes[CChainParams::SECRET_KEY] = std::vector(1, 159); + base58Prefixes[CChainParams::EXT_PUBLIC_KEY] = {(0x04),(0x88),(0xB2),(0x1E)}; + base58Prefixes[CChainParams::EXT_SECRET_KEY] = {(0x04),(0x88),(0xAD),(0xE4)}; + + fMiningRequiresPeers = false; + fDefaultConsistencyChecks = false; + fRequireStandard = true; + fMineBlocksOnDemand = false; + fTestnetToBeDeprecatedFieldRPC = true; + + mapCheckpoints = + { + {0, uint256S("0xcdf2b68d2fc9afdf991df5e321f59198189926ee757bf5efcf5c8c1a07b7c90e")} + }; + } +}; +static CTestnet0Network static_CTestnet0Network; + +class CRegtestNetwork : public CChainParams +{ +public: + CRegtestNetwork() + { + strNetworkID = "REGTEST"; + strNetworkDataDir = "regtest"; + consensus.nMajorityEnforceBlockUpgrade = 750; + consensus.nMajorityRejectBlockOutdated = 950; + consensus.nMajorityWindow = 1000; + consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + consensus.posLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + consensus.nTargetTimespan = 30 * 45; + consensus.nTargetSpacing = 45; + consensus.fPowAllowMinDifficultyBlocks = true; + consensus.fPowNoRetargeting = true; + consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 + consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nTargetSpacing + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; + // January 1, 2008 + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; + // December 31, 2008 + consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; + + /** + * The message start string is designed to be unlikely to occur in normal data. + * The characters are rarely used upper ASCII, not valid as UTF-8, and produce + * a large 32-bit integer with any alignment. + */ + pchMessageStart[0] = 0xaa; + pchMessageStart[1] = 0xbb; + pchMessageStart[2] = 0xcc; + pchMessageStart[3] = 0xdd; + nDefaultPort = 40000; + nRPCPort = 40001; + nMaxTipAge = 24 * 60 * 60; + nStakeMaxAge = 1; + nStakeMinAge = 1; + + const char *pszTimestamp = "AP | Sep 12, 2018, Regtest implemented"; + CTransaction txNew; + txNew.nTime = 1536781520; + txNew.vin.resize(1); + txNew.vout.resize(1); + txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(9999) + << std::vector((const unsigned char *)pszTimestamp, + (const unsigned char *)pszTimestamp + strlen(pszTimestamp)); + txNew.vout[0].SetEmpty(); + + genesis.vtx.push_back(MakeTransactionRef(txNew)); + genesis.hashPrevBlock.SetNull(); + genesis.nVersion = 1; + genesis.nTime = 1536781520; + genesis.nBits = 0x207fffff; + genesis.nNonce = 12799721; + genesis.hashMerkleRoot = BlockMerkleRoot(genesis); + + consensus.hashGenesisBlock = genesis.GetHash(); + assert(consensus.hashGenesisBlock == + uint256S("0x296d58ef241b0dde2372fbc7b09ec4aacf7b4dad88561f02469f3f4695c4fbb1")); + assert(genesis.hashMerkleRoot == + uint256S("0x3565e20605dbdfe7a63ec4b9f5b9d2d25b69fcc13d6bfd7cc42615fcd41a323c")); + + base58Prefixes[CChainParams::PUBKEY_ADDRESS] = std::vector(1, 51); + base58Prefixes[CChainParams::SCRIPT_ADDRESS] = std::vector(1, 15); + base58Prefixes[CChainParams::SECRET_KEY] = std::vector(1, 159); + base58Prefixes[CChainParams::EXT_PUBLIC_KEY] = {(0x04),(0x88),(0xB2),(0x1E)}; + base58Prefixes[CChainParams::EXT_SECRET_KEY] = {(0x04),(0x88),(0xAD),(0xE4)}; + + fMiningRequiresPeers = false; + fDefaultConsistencyChecks = true; + fRequireStandard = false; + fMineBlocksOnDemand = true; + fTestnetToBeDeprecatedFieldRPC = false; + + mapCheckpoints = + { + {0, uint256S("0x296d58ef241b0dde2372fbc7b09ec4aacf7b4dad88561f02469f3f4695c4fbb1")} + }; + } +}; +static CRegtestNetwork static_CRegtestNetwork; + +std::string ChainNameFromCommandLine() +{ + bool fRegTest = gArgs.GetBoolArg("-regtest", false); + bool fTestNet = gArgs.GetBoolArg("-testnet0", false); + + if (fTestNet && fRegTest) + { + throw std::runtime_error("Invalid combination of -regtest and -testnet."); + } + if (fTestNet) + { + return "TESTNET0"; + } + if (fRegTest) + { + return "REGTEST"; + } + return "LEGACY"; +} + +int RPCPortFromCommandLine() +{ + bool fRegTest = gArgs.GetBoolArg("-regtest", false); + bool fTestNet = gArgs.GetBoolArg("-testnet0", false); + + if (fTestNet && fRegTest) + { + throw std::runtime_error("Invalid combination of -regtest and -testnet."); + } + if (fTestNet) + { + return 30001; + } + if (fRegTest) + { + return 40001; + } + return 19119; +} + +void CheckAndSetParams(const std::string &network) +{ + if (network == "LEGACY") + { + chainparams = static_CLegacyNetwork; + } + else if (network == "TESTNET0") + { + chainparams = static_CTestnet0Network; + } + else if (network == "REGTEST") + { + chainparams = static_CRegtestNetwork; + } + else + { + throw std::runtime_error(strprintf("%s: Unknown network %s.", __func__, network)); + } + return; +} diff --git a/src/networks/networktemplate.h b/src/chain/chainparams.h similarity index 60% rename from src/networks/networktemplate.h rename to src/chain/chainparams.h index 765a443d..56bdef91 100644 --- a/src/networks/networktemplate.h +++ b/src/chain/chainparams.h @@ -6,12 +6,15 @@ #ifndef BITCOIN_CHAINPARAMS_H #define BITCOIN_CHAINPARAMS_H +#include +#include +#include + #include "chain/block.h" +#include "chain/checkpoints.h" #include "consensus/params.h" #include "net/protocol.h" -#include - struct CDNSSeedData { std::string name, host; @@ -22,14 +25,6 @@ struct CDNSSeedData } }; - -typedef std::map MapCheckpoints; - -struct CCheckpointData -{ - MapCheckpoints mapCheckpoints; -}; - /** * CChainParams defines various tweakable parameters of a given instance of the * Bitcoin system. There are three: the main network on which people trade goods @@ -37,7 +32,7 @@ struct CCheckpointData * a regression test mode which is intended for private networks only. It has * minimal difficulty to ensure that blocks can be found instantly. */ -class CNetworkTemplate +class CChainParams { public: enum Base58Type @@ -51,8 +46,7 @@ class CNetworkTemplate MAX_BASE58_TYPES }; - /// TODO: make all of the data members below this point protected and make setters for them all - +protected: Consensus::Params consensus; CMessageHeader::MessageMagic pchMessageStart; int nDefaultPort; @@ -68,11 +62,12 @@ class CNetworkTemplate bool fRequireStandard; bool fMineBlocksOnDemand; bool fTestnetToBeDeprecatedFieldRPC; - CCheckpointData checkpointData; + MapCheckpoints mapCheckpoints; unsigned int nStakeMaxAge; unsigned int nStakeMinAge; - +public: + CChainParams() {} const Consensus::Params &GetConsensus() const { return consensus; } const CMessageHeader::MessageMagic &MessageStart() const { return pchMessageStart; } int GetDefaultPort() const { return nDefaultPort; } @@ -94,50 +89,29 @@ class CNetworkTemplate std::string NetworkDataDir() const { return strNetworkDataDir; } const std::vector &DNSSeeds() const { return vSeeds; } const std::vector &Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } - const CCheckpointData &Checkpoints() const { return checkpointData; } + const MapCheckpoints &Checkpoints() const { return mapCheckpoints; } unsigned int getStakeMaxAge() const { return nStakeMaxAge; } unsigned int getStakeMinAge() const { return nStakeMinAge; } int getpch0() const { return pchMessageStart[0]; } int getpch1() const { return pchMessageStart[1]; } int getpch2() const { return pchMessageStart[2]; } int getpch3() const { return pchMessageStart[3]; } - CNetworkTemplate() {} - CNetworkTemplate(CNetworkTemplate *param_netTemplate) - { - this->consensus = param_netTemplate->GetConsensus(); +}; - this->pchMessageStart[0] = param_netTemplate->getpch0(); - this->pchMessageStart[1] = param_netTemplate->getpch1(); - this->pchMessageStart[2] = param_netTemplate->getpch2(); - this->pchMessageStart[3] = param_netTemplate->getpch3(); +const CChainParams &Params(); - this->base58Prefixes[CNetworkTemplate::PUBKEY_ADDRESS] = - param_netTemplate->Base58Prefix(CNetworkTemplate::PUBKEY_ADDRESS); - this->base58Prefixes[CNetworkTemplate::SCRIPT_ADDRESS] = - param_netTemplate->Base58Prefix(CNetworkTemplate::SCRIPT_ADDRESS); - this->base58Prefixes[CNetworkTemplate::SECRET_KEY] = - param_netTemplate->Base58Prefix(CNetworkTemplate::SECRET_KEY); - this->base58Prefixes[CNetworkTemplate::EXT_PUBLIC_KEY] = - param_netTemplate->Base58Prefix(CNetworkTemplate::EXT_PUBLIC_KEY); - this->base58Prefixes[CNetworkTemplate::EXT_SECRET_KEY] = - param_netTemplate->Base58Prefix(CNetworkTemplate::EXT_SECRET_KEY); +static const int64_t LONGER_BLOCKTIME_HARDFORK = 1525478400; // May 5th at 00:00:00 UTC - this->nDefaultPort = param_netTemplate->GetDefaultPort(); - this->nRPCPort = param_netTemplate->GetRPCPort(); - this->nMaxTipAge = param_netTemplate->MaxTipAge(); - this->vSeeds = param_netTemplate->DNSSeeds(); - this->strNetworkID = param_netTemplate->NetworkIDString(); - this->strNetworkDataDir = param_netTemplate->NetworkDataDir(); - this->genesis = param_netTemplate->GenesisBlock(); - this->fMiningRequiresPeers = param_netTemplate->MiningRequiresPeers(); - this->fDefaultConsistencyChecks = param_netTemplate->DefaultConsistencyChecks(); - this->fRequireStandard = param_netTemplate->RequireStandard(); - this->fMineBlocksOnDemand = param_netTemplate->MineBlocksOnDemand(); - this->fTestnetToBeDeprecatedFieldRPC = param_netTemplate->TestnetToBeDeprecatedFieldRPC(); - this->checkpointData = param_netTemplate->Checkpoints(); - this->nStakeMaxAge = param_netTemplate->getStakeMaxAge(); - this->nStakeMinAge = param_netTemplate->getStakeMinAge(); - } -}; +// TODO : Fix this workaround that is used for RPC on command line. shuould either construct pnetMan earlier or find +// another way to get this value +int RPCPortFromCommandLine(); + +/** + * Looks for -regtest, -testnet and returns the appropriate BIP70 chain name. + * @return CBaseChainParams::MAX_NETWORK_TYPES if an invalid combination is given. CBaseChainParams::MAIN by default. + */ +std::string ChainNameFromCommandLine(); + +void CheckAndSetParams(const std::string &network); #endif // BITCOIN_CHAINPARAMS_H diff --git a/src/chain/checkpoints.cpp b/src/chain/checkpoints.cpp index 9589241b..8ec583df 100644 --- a/src/chain/checkpoints.cpp +++ b/src/chain/checkpoints.cpp @@ -10,7 +10,6 @@ #include "chain.h" #include "init.h" #include "main.h" -#include "networks/networktemplate.h" #include "uint256.h" #include @@ -18,24 +17,20 @@ namespace Checkpoints { -int GetTotalBlocksEstimate(const CCheckpointData &data) +int GetTotalBlocksEstimate(const MapCheckpoints &checkpoints) { - const MapCheckpoints &checkpoints = data.mapCheckpoints; - if (checkpoints.empty()) return 0; return checkpoints.rbegin()->first; } -CBlockIndex *GetLastCheckpoint(const CCheckpointData &data) +CBlockIndex *GetLastCheckpoint(const MapCheckpoints &checkpoints) { - const MapCheckpoints &checkpoints = data.mapCheckpoints; - BOOST_REVERSE_FOREACH (const MapCheckpoints::value_type &i, checkpoints) { const uint256 &hash = i.second; - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hash); if (pindex) { return pindex; diff --git a/src/chain/checkpoints.h b/src/chain/checkpoints.h index f61753a4..a68a8d75 100644 --- a/src/chain/checkpoints.h +++ b/src/chain/checkpoints.h @@ -13,7 +13,8 @@ #include class CBlockIndex; -struct CCheckpointData; + +typedef std::map MapCheckpoints; /** * Block-chain checkpoints are compiled-in sanity checks. @@ -22,10 +23,10 @@ struct CCheckpointData; namespace Checkpoints { //! Return conservative estimate of total number of blocks, 0 if unknown -int GetTotalBlocksEstimate(const CCheckpointData &data); +int GetTotalBlocksEstimate(const MapCheckpoints &checkpoints); //! Returns last CBlockIndex* in mapBlockIndex that is a checkpoint -CBlockIndex *GetLastCheckpoint(const CCheckpointData &data); +CBlockIndex *GetLastCheckpoint(const MapCheckpoints &checkpoints); } // namespace Checkpoints diff --git a/src/chain/tx.cpp b/src/chain/tx.cpp index c44cffed..da29ebb8 100644 --- a/src/chain/tx.cpp +++ b/src/chain/tx.cpp @@ -14,8 +14,7 @@ #include "crypto/hash.h" #include "init.h" #include "main.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "timedata.h" #include "tinyformat.h" #include "txdb.h" @@ -206,7 +205,7 @@ bool CTransaction::IsFinal(int nBlockHeight, int64_t nBlockTime) const if (nLockTime == 0) return true; if (nBlockHeight == 0) - nBlockHeight = pnetMan->getChainActive()->chainActive.Height(); + nBlockHeight = g_chainman.chainActive.Height(); if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64_t)nLockTime < ((int64_t)nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) @@ -244,16 +243,16 @@ uint64_t CTransaction::GetCoinAge(uint64_t nCoinAge, bool byValue) const CBlock block; CDiskBlockPos blockPos(txindex.nFile, txindex.nPos); { - if (!ReadBlockFromDisk(block, blockPos, pnetMan->getActivePaymentNetwork()->GetConsensus())) + if (!ReadBlockFromDisk(block, blockPos, Params().GetConsensus())) return false; // unable to read block of previous transaction } - if (block.GetBlockTime() + pnetMan->getActivePaymentNetwork()->getStakeMinAge() > nTime) + if (block.GetBlockTime() + Params().getStakeMinAge() > nTime) continue; // only count coins meeting min age requirement CTransaction txPrev; uint256 blockHashOfTx; if (!GetTransaction( - txin.prevout.hash, txPrev, pnetMan->getActivePaymentNetwork()->GetConsensus(), blockHashOfTx)) + txin.prevout.hash, txPrev, Params().GetConsensus(), blockHashOfTx)) { return false; } @@ -299,16 +298,16 @@ bool CTransaction::GetCoinAge(uint64_t &nCoinAge) const CBlock block; CDiskBlockPos blockPos(txindex.nFile, txindex.nPos); { - if (!ReadBlockFromDisk(block, blockPos, pnetMan->getActivePaymentNetwork()->GetConsensus())) + if (!ReadBlockFromDisk(block, blockPos, Params().GetConsensus())) return false; // unable to read block of previous transaction } - if (block.GetBlockTime() + pnetMan->getActivePaymentNetwork()->getStakeMinAge() > nTime) + if (block.GetBlockTime() + Params().getStakeMinAge() > nTime) continue; // only count coins meeting min age requirement CTransaction txPrev; uint256 blockHashOfTx; if (!GetTransaction( - txin.prevout.hash, txPrev, pnetMan->getActivePaymentNetwork()->GetConsensus(), blockHashOfTx)) + txin.prevout.hash, txPrev, Params().GetConsensus(), blockHashOfTx)) { return false; } @@ -381,8 +380,8 @@ bool GetTransaction(const uint256 &hash, CoinAccessor coin(*(pcoinsTip), hash); if (!coin->IsSpent()) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - pindexSlow = pnetMan->getChainActive()->chainActive[coin->nHeight]; + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + pindexSlow = g_chainman.chainActive[coin->nHeight]; } } diff --git a/src/consensus/tx_verify.cpp b/src/consensus/tx_verify.cpp index 8a16a42f..72f9f991 100644 --- a/src/consensus/tx_verify.cpp +++ b/src/consensus/tx_verify.cpp @@ -5,6 +5,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "chain/chainman.h" #include "consensus/tx_verify.h" #include "base58.h" #include "consensus/consensus.h" @@ -79,9 +80,9 @@ bool CheckTransaction(const CTransaction &tx, CValidationState &state) */ int GetSpendHeight(const CCoinsViewCache &inputs) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - BlockMap::iterator i = pnetMan->getChainActive()->mapBlockIndex.find(inputs.GetBestBlock()); - if (i != pnetMan->getChainActive()->mapBlockIndex.end()) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + BlockMap::iterator i = g_chainman.mapBlockIndex.find(inputs.GetBestBlock()); + if (i != g_chainman.mapBlockIndex.end()) { CBlockIndex *pindexPrev = i->second; if (pindexPrev) @@ -117,7 +118,7 @@ bool Consensus::CheckTxInputs(const CTransaction &tx, CValidationState &state, c if (nSpendHeight == -1) nSpendHeight = GetSpendHeight(inputs); if (nSpendHeight - coin.nHeight < COINBASE_MATURITY && - pnetMan->getChainActive()->chainActive.Tip()->nHeight > 1600000) + g_chainman.chainActive.Tip()->nHeight > 1600000) return state.Invalid(false, REJECT_INVALID, "bad-txns-premature-spend-of-coinbase", strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight)); } diff --git a/src/eccoind.cpp b/src/eccoind.cpp index 1c0807b7..ba3fe929 100644 --- a/src/eccoind.cpp +++ b/src/eccoind.cpp @@ -9,7 +9,7 @@ #include "httprpc.h" #include "httpserver.h" #include "init.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "rpc/rpcserver.h" #include "sync.h" #include "threadgroup.h" @@ -56,7 +56,7 @@ bool AppInit(int argc, char *argv[]) // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { - CheckParams(ChainNameFromCommandLine()); + CheckAndSetParams(ChainNameFromCommandLine()); } catch (const std::exception &e) { @@ -73,8 +73,6 @@ bool AppInit(int argc, char *argv[]) return false; } - GenerateNetworkTemplates(); - // Process help and version before taking care about datadir if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version")) { diff --git a/src/globals.cpp b/src/globals.cpp index ebbdc53c..b0f1e95f 100644 --- a/src/globals.cpp +++ b/src/globals.cpp @@ -3,6 +3,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "chain/chainman.h" #include "coins.h" #include "fs.h" #include "main.h" @@ -72,11 +73,12 @@ fs::path pathCached; fs::path pathCachedNetSpecific; - CWallet *pwalletMain = nullptr; -CNetworkManager *pnetMan = nullptr; std::unique_ptr g_connman; std::unique_ptr peerLogic; CAodvRouteTable g_aodvtable; CPacketManager g_packetman; + +CChainParams chainparams; +CChainManager g_chainman; diff --git a/src/httprpc.cpp b/src/httprpc.cpp index 2847f81b..407b298b 100644 --- a/src/httprpc.cpp +++ b/src/httprpc.cpp @@ -11,7 +11,7 @@ #include "base58.h" #include "crypto/hmac_sha256.h" #include "httpserver.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "random.h" #include "rpc/rpcprotocol.h" #include "rpc/rpcserver.h" diff --git a/src/httpserver.cpp b/src/httpserver.cpp index dd6c2ab4..e3053050 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -11,7 +11,7 @@ #include "args.h" #include "init.h" #include "net/netbase.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "rpc/rpcprotocol.h" // For HTTP status codes #include "sync.h" @@ -337,7 +337,7 @@ static void ThreadHTTP(struct event_base *base, struct evhttp *http) /** Bind HTTP server to specified addresses */ static bool HTTPBindAddresses(struct evhttp *http) { - int defaultPort = gArgs.GetArg("-rpcport", pnetMan->getActivePaymentNetwork()->GetRPCPort()); + int defaultPort = gArgs.GetArg("-rpcport", Params().GetRPCPort()); std::vector > endpoints; // Determine what addresses to bind to diff --git a/src/init.cpp b/src/init.cpp index 60c6838c..e2174056 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -23,8 +23,7 @@ #include "net/addrman.h" #include "net/messages.h" #include "net/net.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "policy/policy.h" #include "processblock.h" #include "rpc/rpcserver.h" @@ -412,7 +411,7 @@ std::string HelpMessage() strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(("Support filtering of blocks and transaction with bloom filters (default: %u)"), 1)); strUsage += HelpMessageOpt("-port=", strprintf(("Listen for connections on (default: %u)"), - pnetMan->getActivePaymentNetwork()->GetDefaultPort())); + Params().GetDefaultPort())); strUsage += HelpMessageOpt("-proxy=", ("Connect through SOCKS5 proxy")); strUsage += HelpMessageOpt("-proxyrandomize", strprintf(("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), @@ -501,10 +500,10 @@ std::string HelpMessage() strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and " "mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", - pnetMan->getActivePaymentNetwork()->DefaultConsistencyChecks())); + Params().DefaultConsistencyChecks())); strUsage += HelpMessageOpt("-checkmempool=", strprintf("Run checks every transactions (default: %u)", - pnetMan->getActivePaymentNetwork()->DefaultConsistencyChecks())); + Params().DefaultConsistencyChecks())); strUsage += HelpMessageOpt( "-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED)); @@ -615,7 +614,7 @@ std::string HelpMessage() "format: :$. A canonical python script is included in " "share/rpcuser. This option can be specified multiple times")); strUsage += HelpMessageOpt("-rpcport=", strprintf(("Listen for JSON-RPC connections on (default: %u)"), - pnetMan->getActivePaymentNetwork()->GetRPCPort())); + Params().GetRPCPort())); strUsage += HelpMessageOpt( "-rpcallowip=", ("Allow JSON-RPC connections from specified source. Valid for are a single IP (e.g. " "1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. " @@ -680,7 +679,7 @@ struct CImportingNow void ThreadImport(std::vector vImportFiles) { - const CNetworkTemplate &chainparams = pnetMan->getActivePaymentNetwork(); + const CChainParams &chainparams = Params(); RenameThread("bitcoin-loadblk"); // -reindex if (fReindex) @@ -702,7 +701,7 @@ void ThreadImport(std::vector vImportFiles) } LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); GetMainSignals().SystemMessage(strprintf("REINDEX: BLOCK FILE blk%05u.dat", (unsigned int)nFile)); - pnetMan->getChainActive()->LoadExternalBlockFile(chainparams, file, &pos); + g_chainman.LoadExternalBlockFile(chainparams, file, &pos); nFile++; } pblocktree->WriteReindexing(false); @@ -710,7 +709,7 @@ void ThreadImport(std::vector vImportFiles) LogPrintf("Reindexing finished\n"); GetMainSignals().SystemMessage("REINDEX: COMPLETE"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): - pnetMan->getChainActive()->InitBlockIndex(chainparams); + g_chainman.InitBlockIndex(chainparams); } // hardcoded $DATADIR/bootstrap.dat @@ -723,7 +722,7 @@ void ThreadImport(std::vector vImportFiles) CImportingNow imp; fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LogPrintf("Importing bootstrap.dat...\n"); - pnetMan->getChainActive()->LoadExternalBlockFile(chainparams, file); + g_chainman.LoadExternalBlockFile(chainparams, file); RenameOver(pathBootstrap, pathBootstrapOld); } else @@ -740,7 +739,7 @@ void ThreadImport(std::vector vImportFiles) { CImportingNow imp; LogPrintf("Importing blocks file %s...\n", path.string()); - pnetMan->getChainActive()->LoadExternalBlockFile(chainparams, file); + g_chainman.LoadExternalBlockFile(chainparams, file); } else { @@ -891,13 +890,6 @@ int initMaxConnections; int initUserMaxConnections; int initFD; - -void GenerateNetworkTemplates() -{ - pnetMan = new CNetworkManager(); - pnetMan->SetParams(ChainNameFromCommandLine()); -} - /** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ @@ -955,7 +947,7 @@ bool AppInit2(thread_group &threadGroup) #endif // ********************************************************* Step 2: parameter interactions - const CNetworkTemplate &chainparams = pnetMan->getActivePaymentNetwork(); + const CChainParams &chainparams = Params(); // also see: InitParameterInteraction() @@ -1057,8 +1049,8 @@ bool AppInit2(thread_group &threadGroup) gArgs.GetArg("-minrelaytxfee", DEFAULT_TRANSACTION_MINFEE))); } - fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !pnetMan->getActivePaymentNetwork()->RequireStandard()); - if (pnetMan->getActivePaymentNetwork()->RequireStandard() && !fRequireStandard) + fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard()); + if (Params().RequireStandard() && !fRequireStandard) return InitError( strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString())); nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp); @@ -1455,7 +1447,7 @@ bool AppInit2(thread_group &threadGroup) { try { - pnetMan->getChainActive()->UnloadBlockIndex(); + g_chainman.UnloadBlockIndex(); pcoinsTip.reset(); pcoinsdbview.reset(); pcoinscatcher.reset(); @@ -1480,7 +1472,7 @@ bool AppInit2(thread_group &threadGroup) } } - if (!pnetMan->getChainActive()->LoadBlockIndex()) + if (!g_chainman.LoadBlockIndex()) { strLoadError = ("Error loading block database"); break; @@ -1488,9 +1480,9 @@ bool AppInit2(thread_group &threadGroup) // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - if (!pnetMan->getChainActive()->mapBlockIndex.empty() && - pnetMan->getChainActive()->mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + if (!g_chainman.mapBlockIndex.empty() && + g_chainman.mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0) { return InitError("Incorrect or no genesis block found. Wrong datadir for network?"); @@ -1498,7 +1490,7 @@ bool AppInit2(thread_group &threadGroup) } // Initialize the block index (no-op if non-empty database was already loaded) - if (!pnetMan->getChainActive()->InitBlockIndex(chainparams)) + if (!g_chainman.InitBlockIndex(chainparams)) { strLoadError = ("Error initializing block database"); break; @@ -1508,7 +1500,7 @@ bool AppInit2(thread_group &threadGroup) LogPrintf("Verifying blocks..."); { - CBlockIndex *tip = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *tip = g_chainman.chainActive.Tip(); if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) { strLoadError = ("The block database contains a block which appears to be from the future. " @@ -1588,10 +1580,10 @@ bool AppInit2(thread_group &threadGroup) } threadGroup.create_thread(&ThreadImport, vImportFiles); - if (pnetMan->getChainActive()->chainActive.Tip() == nullptr) + if (g_chainman.chainActive.Tip() == nullptr) { LogPrintf("Waiting for genesis block to be imported...\n"); - while (!shutdown_threads.load() && pnetMan->getChainActive()->chainActive.Tip() == nullptr) + while (!shutdown_threads.load() && g_chainman.chainActive.Tip() == nullptr) { MilliSleep(10); } @@ -1616,8 +1608,8 @@ bool AppInit2(thread_group &threadGroup) RandAddSeedPerfmon(); //// debug print - LogPrintf("mapBlockIndex.size() = %u\n", pnetMan->getChainActive()->mapBlockIndex.size()); - LogPrintf("nBestHeight = %d\n", pnetMan->getChainActive()->chainActive.Height()); + LogPrintf("mapBlockIndex.size() = %u\n", g_chainman.mapBlockIndex.size()); + LogPrintf("nBestHeight = %d\n", g_chainman.chainActive.Height()); LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0); LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0); diff --git a/src/init.h b/src/init.h index e4f702d4..5c0c41c1 100644 --- a/src/init.h +++ b/src/init.h @@ -9,14 +9,12 @@ #define BITCOIN_INIT_H #include "chain/chainman.h" -#include "networks/netman.h" #include "wallet/wallet.h" #include class CWallet; extern CWallet *pwalletMain; -extern CNetworkManager *pnetMan; void StartShutdown(); bool ShutdownRequested(); @@ -27,7 +25,6 @@ void Shutdown(thread_group &threadGroup); void InitLogging(); //! Parameter interaction: change current parameters depending on various rules void InitParameterInteraction(); -void GenerateNetworkTemplates(); bool AppInit2(thread_group &threadGroup); /** Help for options shared between UI and daemon (for -help) */ diff --git a/src/kernel.cpp b/src/kernel.cpp index d863ded5..440c71e5 100644 --- a/src/kernel.cpp +++ b/src/kernel.cpp @@ -15,8 +15,7 @@ #include "kernel.h" #include "main.h" #include "net/net.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "script/stakescript.h" #include "timedata.h" #include "txdb.h" @@ -28,19 +27,19 @@ static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint256 &nStakeModifier) { nStakeModifier.SetNull(); - const CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hashBlockFrom); + const CBlockIndex *pindex = g_chainman.LookupBlockIndex(hashBlockFrom); if (!pindex) { return error("GetKernelStakeModifier() : block not indexed"); } int blocksToGo = 5; - if (pnetMan->getChainActive()->chainActive.Tip()->nHeight >= 1504350) + if (g_chainman.chainActive.Tip()->nHeight >= 1504350) { blocksToGo = 180; } - while (pnetMan->getChainActive()->chainActive.Next(pindex) && blocksToGo > 0) + while (g_chainman.chainActive.Next(pindex) && blocksToGo > 0) { - pindex = pnetMan->getChainActive()->chainActive.Next(pindex); + pindex = g_chainman.chainActive.Next(pindex); blocksToGo = blocksToGo - 1; } if (blocksToGo > 0) @@ -109,16 +108,16 @@ bool ComputeNextStakeModifier(const CBlockIndex *pindexPrev, const CTransaction // First try finding the previous transaction in database CTransaction txPrev; uint256 blockHashOfTx; - if (!GetTransaction(txin.prevout.hash, txPrev, pnetMan->getActivePaymentNetwork()->GetConsensus(), blockHashOfTx)) + if (!GetTransaction(txin.prevout.hash, txPrev, Params().GetConsensus(), blockHashOfTx)) // previous transaction not in main chain, may occur during initial download return error("ComputeNextStakeModifier() : INFO: read txPrev failed"); // Read block header CBlock block; - CBlockIndex *index = pnetMan->getChainActive()->LookupBlockIndex(blockHashOfTx); + CBlockIndex *index = g_chainman.LookupBlockIndex(blockHashOfTx); { - if (!ReadBlockFromDisk(block, index, pnetMan->getActivePaymentNetwork()->GetConsensus())) + if (!ReadBlockFromDisk(block, index, Params().GetConsensus())) { // unable to read block of previous transaction LogPrint("kernel", "ComputeNextStakeModifier() : read block failed"); @@ -170,7 +169,7 @@ bool CheckStakeKernelHash(int nHeight, return error("CheckStakeKernelHash() : nTime violation"); unsigned int nTimeBlockFrom = blockFrom.GetBlockTime(); - if (nTimeBlockFrom + pnetMan->getActivePaymentNetwork()->getStakeMinAge() > nTimeTx) // Min age requirement + if (nTimeBlockFrom + Params().getStakeMinAge() > nTimeTx) // Min age requirement return error("CheckStakeKernelHash() : min age violation"); int64_t nValueIn = txPrev.vout[prevout.n].nValue; @@ -178,7 +177,7 @@ bool CheckStakeKernelHash(int nHeight, // v0.3 protocol kernel hash weight starts from 0 at the min age // this change increases active coins participating the hash and helps // to secure the network when proof-of-stake difficulty is low - int64_t nTimeWeight = ((int64_t)nTimeTx - txPrev.nTime) - pnetMan->getActivePaymentNetwork()->getStakeMinAge(); + int64_t nTimeWeight = ((int64_t)nTimeTx - txPrev.nTime) - Params().getStakeMinAge(); if (nTimeWeight <= 0) { @@ -222,9 +221,9 @@ bool CheckStakeKernelHash(int nHeight, bool fNegative; bool fOverflow; hashTarget.SetCompact( - GetNextTargetRequired(pnetMan->getChainActive()->chainActive.Tip(), true), &fNegative, &fOverflow); + GetNextTargetRequired(g_chainman.chainActive.Tip(), true), &fNegative, &fOverflow); if (fNegative || hashTarget == 0 || fOverflow || - hashTarget > UintToArith256(pnetMan->getActivePaymentNetwork()->GetConsensus().posLimit)) + hashTarget > UintToArith256(Params().GetConsensus().posLimit)) return error("CheckStakeKernelHash(): nBits below minimum work for proof of stake"); std::string reductionHex = reduction.GetHex(); @@ -264,7 +263,7 @@ bool CheckProofOfStake(int nHeight, const CTransaction &tx, uint256 &hashProofOf // First try finding the previous transaction in database CTransaction txPrev; uint256 blockHashOfTx; - if (!GetTransaction(txin.prevout.hash, txPrev, pnetMan->getActivePaymentNetwork()->GetConsensus(), blockHashOfTx)) + if (!GetTransaction(txin.prevout.hash, txPrev, Params().GetConsensus(), blockHashOfTx)) // previous transaction not in main chain, may occur during initial download return error("CheckProofOfStake() : INFO: read txPrev failed"); // Verify signature @@ -273,9 +272,9 @@ bool CheckProofOfStake(int nHeight, const CTransaction &tx, uint256 &hashProofOf // Read block header CBlock block; - CBlockIndex *index = pnetMan->getChainActive()->LookupBlockIndex(blockHashOfTx); + CBlockIndex *index = g_chainman.LookupBlockIndex(blockHashOfTx); { - if (!ReadBlockFromDisk(block, index, pnetMan->getActivePaymentNetwork()->GetConsensus())) + if (!ReadBlockFromDisk(block, index, Params().GetConsensus())) { LogPrint("kernel", "CheckProofOfStake() : read block failed"); return false; diff --git a/src/main.cpp b/src/main.cpp index 11c17cba..f149ad3d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -24,8 +24,7 @@ #include "net/addrman.h" #include "net/messages.h" #include "net/net.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "policy/policy.h" #include "pow.h" #include "processblock.h" @@ -132,7 +131,7 @@ int nPeersWithValidatedDownloads = 0; // Registration of network node signals. // -int GetHeight() { return pnetMan->getChainActive()->chainActive.Height(); } +int GetHeight() { return g_chainman.chainActive.Height(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions @@ -154,7 +153,7 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // evaluated is what is used. Thus if we want to know if a // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than chainActive.Height(). - const int nBlockHeight = pnetMan->getChainActive()->chainActive.Height() + 1; + const int nBlockHeight = g_chainman.chainActive.Height() + 1; // BIP113 will require that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. @@ -162,7 +161,7 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? - pnetMan->getChainActive()->chainActive.Tip()->GetMedianTimePast() : + g_chainman.chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime(); return IsFinalTx(tx, nBlockHeight, nBlockTime); @@ -177,8 +176,8 @@ bool TestLockPointValidity(const LockPoints *lp) { // Check whether chainActive is an extension of the block at which the LockPoints // calculation was valid. If not LockPoints are no longer valid - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - if (!pnetMan->getChainActive()->chainActive.Contains(lp->maxInputBlock)) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + if (!g_chainman.chainActive.Contains(lp->maxInputBlock)) { return false; } @@ -193,7 +192,7 @@ bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp, bool AssertLockHeld(cs_main); AssertLockHeld(mempool.cs); - CBlockIndex *tip = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *tip = g_chainman.chainActive.Tip(); CBlockIndex index; index.pprev = tip; // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate @@ -431,7 +430,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool &pool, pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees); CAmount inChainInputValue; - double dPriority = view.GetPriority(tx, pnetMan->getChainActive()->chainActive.Height(), inChainInputValue); + double dPriority = view.GetPriority(tx, g_chainman.chainActive.Height(), inChainInputValue); // Keep track of transactions that spend a coinbase, which we re-scan // during reorgs to ensure COINBASE_MATURITY is still met. @@ -446,7 +445,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool &pool, } } - CTxMemPoolEntry entry(ptx, nFees, GetTime(), dPriority, pnetMan->getChainActive()->chainActive.Height(), + CTxMemPoolEntry entry(ptx, nFees, GetTime(), dPriority, g_chainman.chainActive.Height(), pool.HasNoInputsOf(tx), inChainInputValue, fSpendsCoinbase, nSigOps, lp); unsigned int nSize = entry.GetTxSize(); @@ -606,7 +605,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool &pool, { WRITELOCK(pool.cs); // Store transaction in memory - pool.addUnchecked(hash, entry, setAncestors, !pnetMan->getChainActive()->IsInitialBlockDownload()); + pool.addUnchecked(hash, entry, setAncestors, !g_chainman.IsInitialBlockDownload()); } // trim mempool and check if tx was trimmed @@ -892,7 +891,7 @@ bool FlushStateToDisk(CValidationState &state, FlushStateMode mode) nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) { // Update best block in wallet (so we can detect restored wallets). - GetMainSignals().SetBestChain(pnetMan->getChainActive()->chainActive.GetLocator()); + GetMainSignals().SetBestChain(g_chainman.chainActive.GetLocator()); nLastSetChain = nNow; } @@ -923,7 +922,7 @@ void PruneBlockIndexCandidates() // reorganization to a better block fails. std::set::iterator it = setBlockIndexCandidates.begin(); while (it != setBlockIndexCandidates.end() && - setBlockIndexCandidates.value_comp()(*it, pnetMan->getChainActive()->chainActive.Tip())) + setBlockIndexCandidates.value_comp()(*it, g_chainman.chainActive.Tip())) { setBlockIndexCandidates.erase(it++); } @@ -932,15 +931,15 @@ void PruneBlockIndexCandidates() bool InvalidateBlock(CValidationState &state, const Consensus::Params &consensusParams, CBlockIndex *pindex) { - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); // Mark the block itself as invalid. pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); setBlockIndexCandidates.erase(pindex); - while (pnetMan->getChainActive()->chainActive.Contains(pindex)) + while (g_chainman.chainActive.Contains(pindex)) { - CBlockIndex *pindexWalk = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexWalk = g_chainman.chainActive.Tip(); pindexWalk->nStatus |= BLOCK_FAILED_CHILD; setDirtyBlockIndex.insert(pindexWalk); setBlockIndexCandidates.erase(pindexWalk); @@ -948,7 +947,7 @@ bool InvalidateBlock(CValidationState &state, const Consensus::Params &consensus // unconditionally valid already, so force disconnect away from it. if (!DisconnectTip(state, consensusParams)) { - mempool.removeForReorg(pcoinsTip.get(), pnetMan->getChainActive()->chainActive.Tip()->nHeight + 1, + mempool.removeForReorg(pcoinsTip.get(), g_chainman.chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); return false; } @@ -957,11 +956,11 @@ bool InvalidateBlock(CValidationState &state, const Consensus::Params &consensus LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); - BlockMap::iterator it = pnetMan->getChainActive()->mapBlockIndex.begin(); - while (it != pnetMan->getChainActive()->mapBlockIndex.end()) + BlockMap::iterator it = g_chainman.mapBlockIndex.begin(); + while (it != g_chainman.mapBlockIndex.end()) { if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && - !setBlockIndexCandidates.value_comp()(it->second, pnetMan->getChainActive()->chainActive.Tip())) + !setBlockIndexCandidates.value_comp()(it->second, g_chainman.chainActive.Tip())) { setBlockIndexCandidates.insert(it->second); } @@ -970,21 +969,21 @@ bool InvalidateBlock(CValidationState &state, const Consensus::Params &consensus InvalidChainFound(pindex); mempool.removeForReorg( - pcoinsTip.get(), pnetMan->getChainActive()->chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + pcoinsTip.get(), g_chainman.chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); return true; } bool ReconsiderBlock(CValidationState &state, CBlockIndex *pindex) { int nHeight = pindex->nHeight; - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); // Remove the invalidity flag from this block if (!pindex->IsValid()) { pindex->nStatus &= ~BLOCK_FAILED_MASK; setDirtyBlockIndex.insert(pindex); if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx && - setBlockIndexCandidates.value_comp()(pnetMan->getChainActive()->chainActive.Tip(), pindex)) + setBlockIndexCandidates.value_comp()(g_chainman.chainActive.Tip(), pindex)) { setBlockIndexCandidates.insert(pindex); } @@ -995,15 +994,15 @@ bool ReconsiderBlock(CValidationState &state, CBlockIndex *pindex) } } // Remove the invalidity flag from all descendants. - BlockMap::iterator it = pnetMan->getChainActive()->mapBlockIndex.begin(); - while (it != pnetMan->getChainActive()->mapBlockIndex.end()) + BlockMap::iterator it = g_chainman.mapBlockIndex.begin(); + while (it != g_chainman.mapBlockIndex.end()) { if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) { it->second->nStatus &= ~BLOCK_FAILED_MASK; setDirtyBlockIndex.insert(it->second); if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && - setBlockIndexCandidates.value_comp()(pnetMan->getChainActive()->chainActive.Tip(), it->second)) + setBlockIndexCandidates.value_comp()(g_chainman.chainActive.Tip(), it->second)) { setBlockIndexCandidates.insert(it->second); } @@ -1038,7 +1037,7 @@ bool ReceivedBlockTransactions(const CBlock &block, // for setBlockIndexCandidates AssertLockHeld(cs_main); // for nStatus and nSequenceId - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); pindexNew->nTx = block.vtx.size(); pindexNew->nChainTx = 0; pindexNew->nFile = pos.nFile; @@ -1064,8 +1063,8 @@ bool ReceivedBlockTransactions(const CBlock &block, LOCK(cs_nBlockSequenceId); pindex->nSequenceId = nBlockSequenceId++; } - if (pnetMan->getChainActive()->chainActive.Tip() == NULL || - !setBlockIndexCandidates.value_comp()(pindex, pnetMan->getChainActive()->chainActive.Tip())) + if (g_chainman.chainActive.Tip() == NULL || + !setBlockIndexCandidates.value_comp()(pindex, g_chainman.chainActive.Tip())) { setBlockIndexCandidates.insert(pindex); } @@ -1165,7 +1164,7 @@ bool FindBlockPos(CValidationState &state, bool CheckIndexAgainstCheckpoint(const CBlockIndex *pindexPrev, CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, const uint256 &hash) { if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock) @@ -1183,7 +1182,7 @@ bool CheckIndexAgainstCheckpoint(const CBlockIndex *pindexPrev, bool ContextualCheckBlock(const CBlock &block, CValidationState &state, CBlockIndex *const pindexPrev) { const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; - const Consensus::Params &consensusParams = pnetMan->getActivePaymentNetwork()->GetConsensus(); + const Consensus::Params &consensusParams = Params().GetConsensus(); // Start enforcing BIP113 (Median Time Past) using versionbits logic. int nLockTimeFlags = 0; @@ -1326,13 +1325,13 @@ const CBlockIndex *GetLastBlockIndex(const CBlockIndex *pindex, bool fProofOfSta unsigned int GetNextTargetRequired(const CBlockIndex *pindexLast, bool fProofOfStake) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - arith_uint256 bnTargetLimit = UintToArith256(pnetMan->getActivePaymentNetwork()->GetConsensus().powLimit); + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + arith_uint256 bnTargetLimit = UintToArith256(Params().GetConsensus().powLimit); if (fProofOfStake) { // Proof-of-Stake blocks has own target limit since nVersion=3 supermajority on mainNet and always on testNet - bnTargetLimit = UintToArith256(pnetMan->getActivePaymentNetwork()->GetConsensus().posLimit); + bnTargetLimit = UintToArith256(Params().GetConsensus().posLimit); } if (pindexLast == NULL) @@ -1341,7 +1340,7 @@ unsigned int GetNextTargetRequired(const CBlockIndex *pindexLast, bool fProofOfS const CBlockIndex *pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); // Special rule for regtest: we never retarget. - if (pnetMan->getActivePaymentNetwork()->GetConsensus().fPowNoRetargeting) + if (Params().GetConsensus().fPowNoRetargeting) { return pindexPrev->nBits; } @@ -1357,9 +1356,9 @@ unsigned int GetNextTargetRequired(const CBlockIndex *pindexLast, bool fProofOfS { nActualSpacing = 1; } - else if (nActualSpacing > pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetTimespan) + else if (nActualSpacing > Params().GetConsensus().nTargetTimespan) { - nActualSpacing = pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetTimespan; + nActualSpacing = Params().GetConsensus().nTargetTimespan; } // ppcoin: target change every block @@ -1367,8 +1366,8 @@ unsigned int GetNextTargetRequired(const CBlockIndex *pindexLast, bool fProofOfS arith_uint256 bnNew; bnNew.SetCompact(pindexPrev->nBits); int64_t spacing; - int64_t targetSpacing = pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetSpacing; - if (pindexPrev->GetMedianTimePast() > SERVICE_UPGRADE_HARDFORK) + int64_t targetSpacing = Params().GetConsensus().nTargetSpacing; + if (pindexPrev->GetMedianTimePast() > LONGER_BLOCKTIME_HARDFORK) { targetSpacing = 150; } @@ -1382,7 +1381,7 @@ unsigned int GetNextTargetRequired(const CBlockIndex *pindexLast, bool fProofOfS (3 * (int64_t)targetSpacing), ((int64_t)targetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight))); } int64_t nTargetSpacing = spacing; - int64_t nInterval = pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetTimespan / nTargetSpacing; + int64_t nInterval = Params().GetConsensus().nTargetTimespan / nTargetSpacing; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); @@ -1407,7 +1406,7 @@ static const CAmount OLD_MAX_MONEY = 50000000000 * COIN; // miner's coin base reward int64_t GetProofOfWorkReward(int64_t nFees, const int nHeight, uint256 prevHash) { - if (pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + if (Params().MineBlocksOnDemand()) { // just return 50 coins for regtest and the fees return (50 * COIN) + nFees; @@ -1439,7 +1438,7 @@ const int YEARLY_BLOCKCOUNT = 700800; int64_t GetProofOfStakeReward(int64_t nCoinAge, int nHeight) { int64_t nRewardCoinYear = 2.5 * MAX_MINT_PROOF_OF_STAKE; - int64_t CMS = pnetMan->getChainActive()->chainActive.Tip()->nMoneySupply; + int64_t CMS = g_chainman.chainActive.Tip()->nMoneySupply; if (CMS == MAX_MONEY) { // if we are already at max money supply limits (25 billion coins, we return 0 as no new coins are to be minted diff --git a/src/main.h b/src/main.h index 467822eb..0c1f7379 100644 --- a/src/main.h +++ b/src/main.h @@ -31,7 +31,7 @@ class CBlockIndex; class CBlockTreeDB; class CBloomFilter; -class CNetworkTemplate; +class CChainParams; class CInv; class CScriptCheck; class CTxMemPool; @@ -197,7 +197,7 @@ extern std::set setDirtyBlockIndex; void PruneBlockIndexCandidates(); bool CheckIndexAgainstCheckpoint(const CBlockIndex *pindexPrev, CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, const uint256 &hash); bool IsSuperMajority(int minVersion, const CBlockIndex *pstart, diff --git a/src/net/addrdb.cpp b/src/net/addrdb.cpp index e3827861..5a1322c4 100644 --- a/src/net/addrdb.cpp +++ b/src/net/addrdb.cpp @@ -29,7 +29,7 @@ bool CBanDB::Write(const banmap_t &banSet) // serialize banlist, checksum data up to that point, then append csum CDataStream ssBanlist(SER_DISK, CLIENT_VERSION); - ssBanlist << FLATDATA(pnetMan->getActivePaymentNetwork()->MessageStart()); + ssBanlist << FLATDATA(Params().MessageStart()); ssBanlist << banSet; uint256 hash = Hash(ssBanlist.begin(), ssBanlist.end()); ssBanlist << hash; @@ -104,7 +104,7 @@ bool CBanDB::Read(banmap_t &banSet) ssBanlist >> FLATDATA(pchMsgTmp); // ... verify the network matches ours - if (memcmp(pchMsgTmp, std::begin(pnetMan->getActivePaymentNetwork()->MessageStart()), sizeof(pchMsgTmp))) + if (memcmp(pchMsgTmp, std::begin(Params().MessageStart()), sizeof(pchMsgTmp))) { return error("%s: Invalid network magic number", __func__); } @@ -130,7 +130,7 @@ bool CAddrDB::Write(const CAddrMan &addr) // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); - ssPeers << FLATDATA(pnetMan->getActivePaymentNetwork()->MessageStart()); + ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; @@ -210,7 +210,7 @@ bool CAddrDB::Read(CAddrMan &addr, CDataStream &ssPeers) ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours - if (memcmp(pchMsgTmp, std::begin(pnetMan->getActivePaymentNetwork()->MessageStart()), sizeof(pchMsgTmp))) + if (memcmp(pchMsgTmp, std::begin(Params().MessageStart()), sizeof(pchMsgTmp))) { return error("%s: Invalid network magic number", __func__); } diff --git a/src/net/messages.cpp b/src/net/messages.cpp index 5e305401..42199762 100644 --- a/src/net/messages.cpp +++ b/src/net/messages.cpp @@ -23,8 +23,7 @@ #include "net/nodestate.h" #include "net/packetmanager.h" #include "net/protocol.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "policy/fees.h" #include "policy/policy.h" #include "processblock.h" @@ -92,7 +91,7 @@ uint32_t GetFetchFlags(CNode *pfrom, const CBlockIndex *pprev, const Consensus:: void PushNodeVersion(CNode *pnode, CConnman &connman, int64_t nTime) { ServiceFlags nLocalNodeServices = pnode->GetLocalServices(); - int nNodeStartingHeight = pnetMan->getChainActive()->chainActive.Height(); + int nNodeStartingHeight = g_chainman.chainActive.Height(); NodeId nodeid = pnode->GetId(); CAddress addr = pnode->addr; @@ -292,11 +291,11 @@ CBlockIndex *LastCommonAncestor(CBlockIndex *pa, CBlockIndex *pb) bool CanDirectFetch(const Consensus::Params &consensusParams) { int64_t targetSpacing = consensusParams.nTargetSpacing; - if (pnetMan->getChainActive()->chainActive.Tip()->GetMedianTimePast() > SERVICE_UPGRADE_HARDFORK) + if (g_chainman.chainActive.Tip()->GetMedianTimePast() > LONGER_BLOCKTIME_HARDFORK) { targetSpacing = 150; } - return pnetMan->getChainActive()->chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - (targetSpacing * 80); + return g_chainman.chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - (targetSpacing * 80); } void RelayTransaction(const CTransaction &tx, CConnman &connman) @@ -481,7 +480,7 @@ void ProcessBlockAvailability(NodeId nodeid) if (!state->hashLastUnknownBlock.IsNull()) { - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(state->hashLastUnknownBlock); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(state->hashLastUnknownBlock); if (pindex && pindex->nChainWork > 0) { if (state->pindexBestKnownBlock == NULL || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) @@ -525,7 +524,7 @@ void FindNextBlocksToDownload(NodeId nodeid, ProcessBlockAvailability(nodeid); if (state->pindexBestKnownBlock == NULL || - state->pindexBestKnownBlock->nChainWork < pnetMan->getChainActive()->chainActive.Tip()->nChainWork) + state->pindexBestKnownBlock->nChainWork < g_chainman.chainActive.Tip()->nChainWork) { // This peer has nothing interesting. return; @@ -535,8 +534,8 @@ void FindNextBlocksToDownload(NodeId nodeid, { // Bootstrap quickly by guessing a parent of our best tip is the forking point. // Guessing wrong in either direction is not a problem. - state->pindexLastCommonBlock = pnetMan->getChainActive()->chainActive[std::min( - state->pindexBestKnownBlock->nHeight, pnetMan->getChainActive()->chainActive.Height())]; + state->pindexLastCommonBlock = g_chainman.chainActive[std::min( + state->pindexBestKnownBlock->nHeight, g_chainman.chainActive.Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor @@ -579,7 +578,7 @@ void FindNextBlocksToDownload(NodeId nodeid, // We consider the chain that this peer is on invalid. return; } - if (pindex->nStatus & BLOCK_HAVE_DATA || pnetMan->getChainActive()->chainActive.Contains(pindex)) + if (pindex->nStatus & BLOCK_HAVE_DATA || g_chainman.chainActive.Contains(pindex)) { if (pindex->nChainTx) { @@ -635,7 +634,7 @@ void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) ProcessBlockAvailability(nodeid); - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hash); if (pindex && pindex->nChainWork > 0) { // An actually better block was announced. @@ -730,13 +729,13 @@ bool AlreadyHave(const CInv &inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) case MSG_TX: { assert(recentRejects); - if (pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) + if (g_chainman.chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) { // If the chain tip has changed previously rejected transactions // might be now valid, e.g. due to a nLockTime'd tx becoming valid, // or a double-spend. Reset the rejects filter and give those // txs a second chance. - hashRecentRejectsChainTip = pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash(); + hashRecentRejectsChainTip = g_chainman.chainActive.Tip()->GetBlockHash(); recentRejects->reset(); } LOCK(cs_orphans); @@ -745,8 +744,8 @@ bool AlreadyHave(const CInv &inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1)); } case MSG_BLOCK: - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - return pnetMan->getChainActive()->mapBlockIndex.count(inv.hash); + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + return g_chainman.mapBlockIndex.count(inv.hash); } // Don't know what it is, just say we already got one return true; @@ -774,11 +773,11 @@ void static ProcessGetData(CNode *pfrom, CConnman &connman, const Consensus::Par if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) { bool send = false; - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(inv.hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(inv.hash); if (pindex) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - if (pnetMan->getChainActive()->chainActive.Contains(pindex)) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + if (g_chainman.chainActive.Contains(pindex)) { send = true; } @@ -792,11 +791,11 @@ void static ProcessGetData(CNode *pfrom, CConnman &connman, const Consensus::Par // we know about. send = pindex->IsValid(BLOCK_VALID_SCRIPTS) && - (pnetMan->getChainActive()->pindexBestHeader != nullptr) && - (pnetMan->getChainActive()->pindexBestHeader.load()->GetBlockTime() - pindex->GetBlockTime() < + (g_chainman.pindexBestHeader != nullptr) && + (g_chainman.pindexBestHeader.load()->GetBlockTime() - pindex->GetBlockTime() < nOneMonth) && - (GetBlockProofEquivalentTime(*pnetMan->getChainActive()->pindexBestHeader, *pindex, - *pnetMan->getChainActive()->pindexBestHeader, consensusParams) < nOneMonth); + (GetBlockProofEquivalentTime(*g_chainman.pindexBestHeader, *pindex, + *g_chainman.pindexBestHeader, consensusParams) < nOneMonth); if (!send) { LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", @@ -810,8 +809,8 @@ void static ProcessGetData(CNode *pfrom, CConnman &connman, const Consensus::Par // assume > 1 week = historical static const int nOneWeek = 7 * 24 * 60 * 60; if (send && connman.OutboundTargetReached(true) && - (((pnetMan->getChainActive()->pindexBestHeader != nullptr) && - (pnetMan->getChainActive()->pindexBestHeader.load()->GetBlockTime() - pindex->GetBlockTime() > + (((g_chainman.pindexBestHeader != nullptr) && + (g_chainman.pindexBestHeader.load()->GetBlockTime() - pindex->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted) @@ -883,7 +882,7 @@ void static ProcessGetData(CNode *pfrom, CConnman &connman, const Consensus::Par // redundant, and we want it right after the last block // so they don't wait for other stuff first. std::vector vInv; - vInv.push_back(CInv(MSG_BLOCK, pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash())); + vInv.push_back(CInv(MSG_BLOCK, g_chainman.chainActive.Tip()->GetBlockHash())); connman.PushMessage(pfrom, NetMsgType::INV, vInv); } } @@ -950,7 +949,7 @@ bool static ProcessMessage(CNode *pfrom, int64_t nTimeReceived, CConnman &connman) { - const CNetworkTemplate &chainparams = pnetMan->getActivePaymentNetwork(); + const CChainParams &chainparams = Params(); RandAddSeedPerfmon(); LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id); if (gArgs.IsArgSet("-dropmessagestest") && GetRand(atoi(gArgs.GetArg("-dropmessagestest", "0"))) == 0) @@ -1091,7 +1090,7 @@ bool static ProcessMessage(CNode *pfrom, if (!pfrom->fInbound) { // Advertise our address - if (fListen && !pnetMan->getChainActive()->IsInitialBlockDownload()) + if (fListen && !g_chainman.IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices()); FastRandomContext insecure_rand; @@ -1300,7 +1299,7 @@ bool static ProcessMessage(CNode *pfrom, LOCK(cs_main); uint32_t nFetchFlags = - GetFetchFlags(pfrom, pnetMan->getChainActive()->chainActive.Tip(), chainparams.GetConsensus()); + GetFetchFlags(pfrom, g_chainman.chainActive.Tip(), chainparams.GetConsensus()); std::vector vToFetch; @@ -1328,7 +1327,7 @@ bool static ProcessMessage(CNode *pfrom, // getheaders response here. When we receive the headers, we // will then ask for the blocks we need. connman.PushMessage(pfrom, NetMsgType::GETHEADERS, - pnetMan->getChainActive()->chainActive.GetLocator(pnetMan->getChainActive()->pindexBestHeader), + g_chainman.chainActive.GetLocator(g_chainman.pindexBestHeader), inv.hash); CNodeStateAccessor nodestate(nodestateman, pfrom->GetId()); if (CanDirectFetch(chainparams.GetConsensus()) && nodestate.IsNull() == false && @@ -1340,7 +1339,7 @@ bool static ProcessMessage(CNode *pfrom, MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus()); } LogPrint("net", "getheaders (%d) %s to peer=%d\n", - pnetMan->getChainActive()->pindexBestHeader.load()->nHeight, inv.hash.ToString(), pfrom->id); + g_chainman.pindexBestHeader.load()->nHeight, inv.hash.ToString(), pfrom->id); } } else @@ -1352,7 +1351,7 @@ bool static ProcessMessage(CNode *pfrom, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id); } else if (!fAlreadyHave && !fImporting && !fReindex && - !pnetMan->getChainActive()->IsInitialBlockDownload()) + !g_chainman.IsInitialBlockDownload()) { pfrom->AskFor(inv); } @@ -1400,7 +1399,7 @@ bool static ProcessMessage(CNode *pfrom, LOCK(cs_main); - if (pnetMan->getChainActive()->IsInitialBlockDownload() && !pfrom->fWhitelisted) + if (g_chainman.IsInitialBlockDownload() && !pfrom->fWhitelisted) { LogPrintf("Ignoring getheaders from peer=%d because our node is in initial block download\n", pfrom->id); return true; @@ -1411,7 +1410,7 @@ bool static ProcessMessage(CNode *pfrom, if (locator.IsNull()) { // If locator is null, return the hashStop block - pindex = pnetMan->getChainActive()->LookupBlockIndex(hashStop); + pindex = g_chainman.LookupBlockIndex(hashStop); if (!pindex) { return true; @@ -1420,10 +1419,10 @@ bool static ProcessMessage(CNode *pfrom, else { // Find the last block the caller has in the main chain - pindex = pnetMan->getChainActive()->FindForkInGlobalIndex(pnetMan->getChainActive()->chainActive, locator); + pindex = g_chainman.FindForkInGlobalIndex(g_chainman.chainActive, locator); if (pindex) { - pindex = pnetMan->getChainActive()->chainActive.Next(pindex); + pindex = g_chainman.chainActive.Next(pindex); } } @@ -1433,7 +1432,7 @@ bool static ProcessMessage(CNode *pfrom, int nLimit = MAX_HEADERS_RESULTS; LogPrintf("getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->id); - for (; pindex; pindex = pnetMan->getChainActive()->chainActive.Next(pindex)) + for (; pindex; pindex = g_chainman.chainActive.Next(pindex)) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) @@ -1453,7 +1452,7 @@ bool static ProcessMessage(CNode *pfrom, // without the new block. By resetting the BestHeaderSent, we ensure we // will re-announce the new block via headers (or compact blocks again) // in the SendMessages logic. - nodestate->pindexBestHeaderSent = pindex ? pindex : pnetMan->getChainActive()->chainActive.Tip(); + nodestate->pindexBestHeaderSent = pindex ? pindex : g_chainman.chainActive.Tip(); connman.PushMessage(pfrom, NetMsgType::HEADERS, vHeaders); } @@ -1591,7 +1590,7 @@ bool static ProcessMessage(CNode *pfrom, if (!fRejectedParents) { uint32_t nFetchFlags = - GetFetchFlags(pfrom, pnetMan->getChainActive()->chainActive.Tip(), chainparams.GetConsensus()); + GetFetchFlags(pfrom, g_chainman.chainActive.Tip(), chainparams.GetConsensus()); for (const CTxIn &txin : tx.vin) { CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash); @@ -1703,7 +1702,7 @@ bool static ProcessMessage(CNode *pfrom, } // check if these are duplicate headers uint256 hash = headers.front().GetHash(); - CBlockIndex *_pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *_pindex = g_chainman.LookupBlockIndex(hash); if (hash != chainparams.GetConsensus().hashGenesisBlock) { if (_pindex) @@ -1716,7 +1715,7 @@ bool static ProcessMessage(CNode *pfrom, } } LOCK(cs_main); - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); CBlockIndex *pindexLast = nullptr; for (const CBlockHeader &header : headers) { @@ -1738,7 +1737,7 @@ bool static ProcessMessage(CNode *pfrom, if (state.GetRejectReason() == "bad-prevblk") { connman.PushMessage(pfrom, NetMsgType::GETHEADERS, - pnetMan->getChainActive()->chainActive.GetLocator(pindexLast), uint256()); + g_chainman.chainActive.GetLocator(pindexLast), uint256()); } return error("invalid header received"); } @@ -1756,7 +1755,7 @@ bool static ProcessMessage(CNode *pfrom, LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight); connman.PushMessage(pfrom, NetMsgType::GETHEADERS, - pnetMan->getChainActive()->chainActive.GetLocator(pindexLast), uint256()); + g_chainman.chainActive.GetLocator(pindexLast), uint256()); } bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus()); @@ -1764,12 +1763,12 @@ bool static ProcessMessage(CNode *pfrom, // If this set of headers is valid and ends in a block with at least as // much work as our tip, download as much as possible. if (fCanDirectFetch && pindexLast && pindexLast->IsValid(BLOCK_VALID_TREE) && - pnetMan->getChainActive()->chainActive.Tip()->nChainWork <= pindexLast->nChainWork) + g_chainman.chainActive.Tip()->nChainWork <= pindexLast->nChainWork) { std::vector vToFetch; CBlockIndex *pindexWalk = pindexLast; // Calculate all the blocks we'd need to switch to pindexLast, up to a limit. - while (pindexWalk && !pnetMan->getChainActive()->chainActive.Contains(pindexWalk) && + while (pindexWalk && !g_chainman.chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) && !mapBlocksInFlight.count(pindexWalk->GetBlockHash())) @@ -1783,7 +1782,7 @@ bool static ProcessMessage(CNode *pfrom, // very large reorg at a time we think we're close to caught up to // the main chain -- this shouldn't really happen. Bail out on the // direct fetch and rely on parallel download instead. - if (!pnetMan->getChainActive()->chainActive.Contains(pindexWalk)) + if (!g_chainman.chainActive.Contains(pindexWalk)) { LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n", pindexLast->GetBlockHash().ToString(), pindexLast->nHeight); @@ -1827,7 +1826,7 @@ bool static ProcessMessage(CNode *pfrom, // unless we're still syncing with the network. Such an unrequested // block may still be processed, subject to the conditions in // AcceptBlock(). - bool forceProcessing = pfrom->fWhitelisted && !pnetMan->getChainActive()->IsInitialBlockDownload(); + bool forceProcessing = pfrom->fWhitelisted && !g_chainman.IsInitialBlockDownload(); { LOCK(cs_main); // Also always process if we requested the block explicitly, as we @@ -2203,7 +2202,7 @@ bool ProcessMessages(CNode *pfrom, CConnman &connman) TRY_LOCK(pfrom->csRecvGetData, locked); if (locked && !pfrom->vRecvGetData.empty()) { - ProcessGetData(pfrom, connman, pnetMan->getActivePaymentNetwork()->GetConsensus()); + ProcessGetData(pfrom, connman, Params().GetConsensus()); } } @@ -2236,7 +2235,7 @@ bool ProcessMessages(CNode *pfrom, CConnman &connman) msg.SetVersion(pfrom->GetRecvVersion()); // Scan for message start - if (memcmp(std::begin(msg.hdr.pchMessageStart), std::begin(pnetMan->getActivePaymentNetwork()->MessageStart()), + if (memcmp(std::begin(msg.hdr.pchMessageStart), std::begin(Params().MessageStart()), CMessageHeader::MESSAGE_START_SIZE) != 0) { LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id); @@ -2246,7 +2245,7 @@ bool ProcessMessages(CNode *pfrom, CConnman &connman) // Read header CMessageHeader &hdr = msg.hdr; - if (!hdr.IsValid(pnetMan->getActivePaymentNetwork()->MessageStart())) + if (!hdr.IsValid(Params().MessageStart())) { LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id); return fMoreWork; @@ -2333,7 +2332,7 @@ bool ProcessMessages(CNode *pfrom, CConnman &connman) bool SendMessages(CNode *pto, CConnman &connman) { - const Consensus::Params &consensusParams = pnetMan->getActivePaymentNetwork()->GetConsensus(); + const Consensus::Params &consensusParams = Params().GetConsensus(); // Don't send anything until the version handshake is complete if (!pto->fSuccessfullyConnected || pto->fDisconnect) @@ -2386,7 +2385,7 @@ bool SendMessages(CNode *pto, CConnman &connman) // Address refresh broadcast int64_t nNow = GetTimeMicros(); - if (!pnetMan->getChainActive()->IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) + if (!g_chainman.IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) { AdvertiseLocal(pto); pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL); @@ -2428,9 +2427,9 @@ bool SendMessages(CNode *pto, CConnman &connman) } // Start block sync - if (pnetMan->getChainActive()->pindexBestHeader == nullptr) + if (g_chainman.pindexBestHeader == nullptr) { - pnetMan->getChainActive()->pindexBestHeader = pnetMan->getChainActive()->chainActive.Tip(); + g_chainman.pindexBestHeader = g_chainman.chainActive.Tip(); } // Download if this is a nice peer, or we have no nice peers and this one @@ -2440,11 +2439,11 @@ bool SendMessages(CNode *pto, CConnman &connman) if (!state->fSyncStarted && !pto->fClient && !fImporting && !fReindex) { if (fFetch || - pnetMan->getChainActive()->pindexBestHeader.load()->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) + g_chainman.pindexBestHeader.load()->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) { CNodeStateAccessor modableState(nodestateman, pto->GetId()); modableState->fSyncStarted = true; - const CBlockIndex *pindexStart = pnetMan->getChainActive()->pindexBestHeader; + const CBlockIndex *pindexStart = g_chainman.pindexBestHeader; /** * If possible, start at the block preceding the currently best * known header. This ensures that we always get a non-empty list of @@ -2461,14 +2460,14 @@ bool SendMessages(CNode *pto, CConnman &connman) LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight); connman.PushMessage( - pto, NetMsgType::GETHEADERS, pnetMan->getChainActive()->chainActive.GetLocator(pindexStart), uint256()); + pto, NetMsgType::GETHEADERS, g_chainman.chainActive.GetLocator(pindexStart), uint256()); } } // Resend wallet transactions that haven't gotten in a block yet // Except during reindex, importing and IBD, when old wallet transactions // become unconfirmed and spams other nodes. - if (!fReindex && !fImporting && !pnetMan->getChainActive()->IsInitialBlockDownload()) + if (!fReindex && !fImporting && !g_chainman.IsInitialBlockDownload()) { GetMainSignals().Broadcast(nTimeBestReceived.load(), &connman); } @@ -2499,12 +2498,12 @@ bool SendMessages(CNode *pto, CConnman &connman) // aren't on chainActive, give up. for (const uint256 &hash : pto->vBlockHashesToAnnounce) { - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hash); if (!pindex) { continue; } - if (pnetMan->getChainActive()->chainActive[pindex->nHeight] != pindex) + if (g_chainman.chainActive[pindex->nHeight] != pindex) { // Bail out if we reorged away from this block fRevertToInv = true; @@ -2562,7 +2561,7 @@ bool SendMessages(CNode *pto, CConnman &connman) for (const uint256 &hashToAnnounce : pto->vBlockHashesToAnnounce) { CBlockIndex *pindex = nullptr; - pindex = pnetMan->getChainActive()->LookupBlockIndex(hashToAnnounce); + pindex = g_chainman.LookupBlockIndex(hashToAnnounce); if (!pindex) { continue; @@ -2571,10 +2570,10 @@ bool SendMessages(CNode *pto, CConnman &connman) // Warn if we're announcing a block that is not on the main // chain. This should be very rare and could be optimized out. // Just log for now. - if (pnetMan->getChainActive()->chainActive[pindex->nHeight] != pindex) + if (g_chainman.chainActive[pindex->nHeight] != pindex) { LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n", hashToAnnounce.ToString(), - pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash().ToString()); + g_chainman.chainActive.Tip()->GetBlockHash().ToString()); } // If the peer's chain has this block, don't inv it back. @@ -2707,7 +2706,7 @@ bool SendMessages(CNode *pto, CConnman &connman) if (state->vBlocksInFlight.size() > 0) { int64_t targetSpacing = consensusParams.nTargetSpacing; - if (pnetMan->getChainActive()->chainActive.Tip()->GetMedianTimePast() > SERVICE_UPGRADE_HARDFORK) + if (g_chainman.chainActive.Tip()->GetMedianTimePast() > LONGER_BLOCKTIME_HARDFORK) { targetSpacing = 150; } @@ -2730,7 +2729,7 @@ bool SendMessages(CNode *pto, CConnman &connman) // // Message: getdata (blocks) // - if (!pto->fClient && (fFetch || !pnetMan->getChainActive()->IsInitialBlockDownload()) && + if (!pto->fClient && (fFetch || !g_chainman.IsInitialBlockDownload()) && state->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { std::vector vToDownload; diff --git a/src/net/net.cpp b/src/net/net.cpp index a8ca324a..ef723e3d 100644 --- a/src/net/net.cpp +++ b/src/net/net.cpp @@ -17,7 +17,7 @@ #include "crypto/hash.h" #include "init.h" #include "net/addrman.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "util/utilstrencodings.h" @@ -98,7 +98,7 @@ void CConnman::AddOneShot(const std::string &strDest) unsigned short GetListenPort() { - return (unsigned short)(gArgs.GetArg("-port", pnetMan->getActivePaymentNetwork()->GetDefaultPort())); + return (unsigned short)(gArgs.GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer @@ -354,7 +354,7 @@ CNode *CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, - pnetMan->getActivePaymentNetwork()->GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : + Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { if (!IsSelectableSocket(hSocket)) @@ -738,7 +738,7 @@ bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool &complete if (vRecvMsg.empty() || vRecvMsg.back().complete()) { vRecvMsg.push_back( - CNetMessage(pnetMan->getActivePaymentNetwork()->MessageStart(), SER_NETWORK, MIN_PROTO_VERSION)); + CNetMessage(Params().MessageStart(), SER_NETWORK, MIN_PROTO_VERSION)); } CNetMessage &msg = vRecvMsg.back(); @@ -1683,7 +1683,7 @@ void CConnman::ThreadDNSAddressSeed() } } - const std::vector &vSeeds = pnetMan->getActivePaymentNetwork()->DNSSeeds(); + const std::vector &vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); @@ -1705,7 +1705,7 @@ void CConnman::ThreadDNSAddressSeed() { int nOneDay = 24 * 3600; CAddress addr = CAddress( - CService(ip, pnetMan->getActivePaymentNetwork()->GetDefaultPort()), requiredServiceBits); + CService(ip, Params().GetDefaultPort()), requiredServiceBits); // Use a random age between 3 and 7 days old. addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); vAdd.push_back(addr); @@ -1958,7 +1958,7 @@ void CConnman::ThreadOpenConnections() // do not allow non-default ports, unless after 50 invalid addresses // selected already. - if (addr.GetPort() != pnetMan->getActivePaymentNetwork()->GetDefaultPort() && nTries < 50) + if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) { continue; } @@ -2027,7 +2027,7 @@ std::vector CConnman::GetAddedNodeInfo() for (const std::string &strAddNode : lAddresses) { - CService service(LookupNumeric(strAddNode.c_str(), pnetMan->getActivePaymentNetwork()->GetDefaultPort())); + CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort())); if (service.IsValid()) { // strAddNode is an IP:port @@ -2091,7 +2091,7 @@ void CConnman::ThreadOpenAddedConnections() // IP/port. tried = true; CService service( - LookupNumeric(info.strAddedNode.c_str(), pnetMan->getActivePaymentNetwork()->GetDefaultPort())); + LookupNumeric(info.strAddedNode.c_str(), Params().GetDefaultPort())); OpenNetworkConnection( CAddress(service, NODE_NONE), false, &grant, info.strAddedNode.c_str(), false, false, true); MilliSleep(500); diff --git a/src/net/net.h b/src/net/net.h index c9ecb626..b15540c5 100644 --- a/src/net/net.h +++ b/src/net/net.h @@ -26,7 +26,7 @@ #include "net/netbase.h" #include "net/protocol.h" #include "net/tagstore.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "random.h" #include "streams.h" #include "sync.h" @@ -101,7 +101,7 @@ static const std::string strRoutingFile = "routing.dat"; /** Subversion as sent to the P2P network in `version` messages */ extern std::string strSubVersion; -extern CNetworkManager *pnetMan; + typedef int64_t NodeId; // Command, total bytes @@ -457,7 +457,7 @@ class CConnman std::vector serializedHeader; serializedHeader.reserve(CMessageHeader::HEADER_SIZE); uint256 hash = Hash(data.data(), data.data() + nMessageSize); - CMessageHeader hdr(pnetMan->getActivePaymentNetwork()->MessageStart(), sCommand.c_str(), nMessageSize); + CMessageHeader hdr(Params().MessageStart(), sCommand.c_str(), nMessageSize); memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE); CVectorWriter{SER_NETWORK, MIN_PROTO_VERSION, serializedHeader, 0, hdr}; diff --git a/src/networks/netman.cpp b/src/networks/netman.cpp deleted file mode 100644 index 8d019dfc..00000000 --- a/src/networks/netman.cpp +++ /dev/null @@ -1,382 +0,0 @@ -// This file is part of the Eccoin project -// Copyright (c) 2017-2018 Greg Griffith -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#include "netman.h" -#include "args.h" -#include "consensus/merkle.h" -#include "tinyformat.h" -#include "util/util.h" -#include - - -#include - -void AppendParamsHelpMessages(std::string &strUsage, bool debugHelp) -{ - strUsage += HelpMessageGroup("Chain selection options:"); - strUsage += HelpMessageOpt("-testnet", "Use the test chain"); - if (debugHelp) - { - strUsage += HelpMessageOpt("-regtest", - "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. " - "This is intended for regression testing tools and app development."); - } -} - -void CNetworkManager::ConstructNetworks() -{ - if (legacyTemplate != nullptr) - { - pnetLegacy = new CNetwork(legacyTemplate); - } - if (testnet0Template != nullptr) - { - pnetTestnet0 = new CNetwork(testnet0Template); - } - if (regTestTemplate != nullptr) - { - pnetRegTest = new CNetwork(regTestTemplate); - } -} - -void CNetworkManager::ConstructLegacyNetworkTemplate() -{ - legacyTemplate->strNetworkID = "LEGACY"; - legacyTemplate->strNetworkDataDir = ""; - legacyTemplate->consensus.nMajorityEnforceBlockUpgrade = 750; - legacyTemplate->consensus.nMajorityRejectBlockOutdated = 950; - legacyTemplate->consensus.nMajorityWindow = 1000; - legacyTemplate->consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - legacyTemplate->consensus.posLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - legacyTemplate->consensus.nTargetTimespan = 30 * 45; - legacyTemplate->consensus.nTargetSpacing = 45; - legacyTemplate->consensus.fPowAllowMinDifficultyBlocks = false; - legacyTemplate->consensus.fPowNoRetargeting = false; - legacyTemplate->consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 - legacyTemplate->consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nTargetSpacing - legacyTemplate->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; - legacyTemplate->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 - legacyTemplate->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 - - /** - * The message start string is designed to be unlikely to occur in normal data. - * The characters are rarely used upper ASCII, not valid as UTF-8, and produce - * a large 32-bit integer with any alignment. - */ - legacyTemplate->pchMessageStart[0] = 0xce; - legacyTemplate->pchMessageStart[1] = 0xf1; - legacyTemplate->pchMessageStart[2] = 0xdb; - legacyTemplate->pchMessageStart[3] = 0xfa; - legacyTemplate->nDefaultPort = 19118; - legacyTemplate->nRPCPort = 19119; - legacyTemplate->nMaxTipAge = 24 * 60 * 60; - legacyTemplate->nStakeMaxAge = 60 * 60 * 24 * 84; // 84 days - legacyTemplate->nStakeMinAge = 60 * 60 * 2; // 2 hours - - const char *pszTimestamp = - "AP | Mar 2, 2014, 10.35 AM IST: China blames Uighur separatists for knife attack; 33 dead"; - CTransaction txNew; - txNew.nTime = 1393744287; - txNew.vin.resize(1); - txNew.vout.resize(1); - txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(9999) - << std::vector((const unsigned char *)pszTimestamp, - (const unsigned char *)pszTimestamp + strlen(pszTimestamp)); - txNew.vout[0].SetEmpty(); - - legacyTemplate->genesis.vtx.push_back(MakeTransactionRef(txNew)); - legacyTemplate->genesis.hashPrevBlock.SetNull(); - legacyTemplate->genesis.nVersion = 1; - legacyTemplate->genesis.nTime = 1393744307; - legacyTemplate->genesis.nBits = 0x1e0fffff; - legacyTemplate->genesis.nNonce = 12799721; - legacyTemplate->genesis.hashMerkleRoot = BlockMerkleRoot(legacyTemplate->genesis); - - legacyTemplate->consensus.hashGenesisBlock = legacyTemplate->genesis.GetHash(); - assert(legacyTemplate->consensus.hashGenesisBlock == - uint256S("0xa60ac43c88dbc44b826cf315352a8a7b373d2af8b6e1c4c4a0638859c5e9ecd1")); - assert(legacyTemplate->genesis.hashMerkleRoot == - uint256S("0x4db82fe8b45f3dae2b7c7b8be5ec4c37e72e25eaf989b9db24ce1d0fd37eed8b")); - - legacyTemplate->vSeeds.push_back(CDNSSeedData("ECC-Seed1", "eccserver1.ddns.net", true)); - legacyTemplate->vSeeds.push_back(CDNSSeedData("ECC-Seed2", "eccnode.altj.com", true)); - legacyTemplate->vSeeds.push_back(CDNSSeedData("ECC-Seed3", "5.189.131.197", true)); - legacyTemplate->vSeeds.push_back(CDNSSeedData("ECC-Seed4", "185.21.216.160", true)); - - legacyTemplate->base58Prefixes[CNetworkTemplate::PUBKEY_ADDRESS] = std::vector(1, 33); - legacyTemplate->base58Prefixes[CNetworkTemplate::SCRIPT_ADDRESS] = std::vector(1, 8); - legacyTemplate->base58Prefixes[CNetworkTemplate::SECRET_KEY] = std::vector(1, 161); - legacyTemplate->base58Prefixes[CNetworkTemplate::EXT_PUBLIC_KEY] = - boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container >(); - legacyTemplate->base58Prefixes[CNetworkTemplate::EXT_SECRET_KEY] = - boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container >(); - - legacyTemplate->fMiningRequiresPeers = true; - legacyTemplate->fDefaultConsistencyChecks = false; - legacyTemplate->fRequireStandard = true; - legacyTemplate->fMineBlocksOnDemand = false; - legacyTemplate->fTestnetToBeDeprecatedFieldRPC = false; - - legacyTemplate->checkpointData = (CCheckpointData){ - boost::assign::map_list_of(0, uint256S("0xa60ac43c88dbc44b826cf315352a8a7b373d2af8b6e1c4c4a0638859c5e9ecd1"))( - 1, uint256S("0x00000762d19a3a38458e73de6c937fd483f17bd75f55d7fe4e95713f51d6b816"))( - 2, uint256S("0x00000ea50ea0cae64779ff4bb4a0ee94841e2ee20642641a062cbdd342e0a3c5"))( - 3, uint256S("0x00000513cc6f4bec8d7e7bd0ded854200b6c784c8c830a3e4fd0cccc2cb9e58c"))( - 1000, uint256S("0x000000000df3f7a5f719c247782d7a43d75186ebc043341e2668320f9d940bcd"))( - 10000, uint256S("0x00000000076d45a9579c879d46354dd81eeba7060a9a065e13c9dd1c28f474d1"))( - 23920, uint256S("0x000000000331540c766c4ac667a6fbc65ff93f5a30fbb0c6822986885b1b56c0"))( - 36918, uint256S("0x0000000001353725582b099cdd3c89933bbd08a17ace464fba935ecfc41572ef"))( - 50000, uint256S("0x0000000001c770384cd12a74eb5456358425fc6a94a250c3466aaa2ca7460131"))( - 86401, uint256S("0x51bb1ac3ffd009c12791b9d4320dec0ba69e15c8b6d03d17889b0c09fb5b05a4"))( - 86402, uint256S("0xa9f3141e571231e02b4fb649370af6173e1a80a9e0d21aa8859bd17ce1260a05"))( - 86403, uint256S("0xf6c11aadca44fce2390107e229d4d0d70f7cf64266b959672711c68e0f411af5"))( - 86759, uint256S("0x5c6ed2e23ccc27d59a0659a9a32a4c0ca97d829249277c6a35918f4ec94b1748"))( - 86761, uint256S("0xca305a45c9f8a89c050f004d0438b38f190fe6bfe51128f0c3e864ddcf2c765c"))( - 86901, uint256S("0xe769d38b7e140267b688f9d9cc6b58d38185427facb6a1aa719db60a0d54f3f7"))( - 87000, uint256S("0xbb069ba59aa5a6acc68413ef7c2d0c009b061daf160edf958738d197a059f11d"))( - 87101, uint256S("0x1ffbfd2a70e626d5f848775851e6f89bee6f2225ed78131b16f9547449d2e2ee"))( - 96500, uint256S("0x13f0755045a3ae90d33c4bcf6ba1581025fc6e0caf46f7624063cb59dcc3d27c"))( - 100000, uint256S("0x28a483386650a188c3346fd5e329e2c8cc137cf3557547e8525f5cdea601501a"))( - 136500, uint256S("0x7e4ec82a165762e8a324038ef1cdd0b83e603f4737ae6f9e5967b13b8b6ace5c"))( - 150000, uint256S("0xfee6d00910e8d0aa2f0ca8a447b4de366a12f9df2521f77c5a97a5ae0af8834e"))( - 185000, uint256S("0xce904504a0df58944c6a633b739abcec3bbb256b510a616b465c24525d564828"))( - 197712, uint256S("0x7576d0f370b1efdce01075a9491fb8d2f98af485f78d170196270f1eb156ee40"))( - 200000, uint256S("0x1f1ea51aee8a7456655e31857c7cd4a9f494556438485abd4c60d86cacf24b44"))( - 205000, uint256S("0x9e4528bc818bb1ee2cdf44ba7805e88b4fc85bbf496516f35d4d642c6812503e"))( - 209762, uint256S("0x49448f382f9ec8f126542244573e7349c7b07db0cbdc2ab8326942cbfff603b3"))( - 209786, uint256S("0x28558eedf7f5c049e9f2ea61da270fffc5b50310aafb29c7595840784e8b1d61"))( - 215650, uint256S("0xd7fb37df6be4bf2c5c9ea47ba4a14f9af35c326cd225122b03f61b74d1283d09"))( - 215690, uint256S("0x8af4d5450c238460a4775b19c94872eaf5664657f702bef53576bc9f77af319d"))( - 220504, uint256S("0x5781d160a46a6631a21e62a9a67932d0f9b8636c8f5241973b076db3854de405"))( - 221000, uint256S("0x51cd22cde58a3738e851f155a282b4624d3e18e84fbcb02de5006029dec8f7e3"))( - 233855, uint256S("0x77c1312f0b4ba0fc34cb7a0f3472012739bbd22c317add69edaa4908e83b00eb"))( - 236850, uint256S("0x139203f72c943433880c4f8d3581a4cb7ee0877f341639cd4c7810edc7fc7d80"))( - 237000, uint256S("0x70fdb4f39e571afff137c7bd40c4df98ccab32cec1d305074bac9fca30754bc0"))( - 241130, uint256S("0xdd900777cb9e2ea2cae0bf410ce2f2484a415c7bf7af59d9492868195583e3b2"))( - 242150, uint256S("0xba96de8da95ac53cedc7fd0cd3c17b32f5d3a04f33a544060606c095b28bf4c1"))( - 300000, uint256S("0x2c654dfa9f1ab51a64509910b1f053fc20d572022480814988c36f042cb3010b"))( - 350000, uint256S("0xfdb1df53f4365d494d9fa54247a533cbfcd9b6992491f40c8ccfeed454932a70"))( - 400000, uint256S("0xc04d360938d5ff66294100a10424f7e284abe76d117f28460e16752edeb03444"))( - 435000, uint256S("0x801a211aa479129e42554bc812d624e585e1b0dd608e23b1a7f87a9d14e7fdec"))( - 450000, uint256S("0x53e21a2574ff6acc0f31640c4058554dde2fe8972ec72867403e8b88e9ba1bc6"))( - 500000, uint256S("0x779f22407cf9fa0adb8a361918ccf249ef913070ce368070c1ac5063005e3e3c"))( - 550000, uint256S("0xf340b738c21c0a9b6b2eff0f40d9ab3fca9830d8597131680cd5a2615594cfb0"))( - 600000, uint256S("0x589fc3d25c15caaa468dc8b4249e1cbb6ea18368897bd3b1d80f1404486e3783"))( - 650000, uint256S("0xc28634f7211ff0582dfe8df1849711a9bd7815005e59dff0059a20876c465f51"))( - 675000, uint256S("0xe1aca23bd72ad9d153767272f43d33a0542d2a61a78e281341d0f12cd0521024"))( - 675500, uint256S("0x26ccdf8bcb1a50ecef8f507de74ff030789aa1b52491fc4a4de4e4679d53a398"))( - 687345, uint256S("0xae2e43c35a3346fa798a0a356ca7a4bce57885ee64e4319295f7f3b7210944f1"))( - 700000, uint256S("0x0ab361e8acd391c6b5e726eb4704dd8d60e2e3b3f8856e2f7d6373c9a3e0da36"))( - 702950, uint256S("0x26d2cd7b13f1aaa34ffc379696d0e5b14c2ddf8ef2c2c78348fec23f8b55e8ff"))( - 1030250, uint256S("0x434ee5c39b6ba186d66cbfaaa8004910b3556726f990b9f33bb48b9fc280c5de"))( - 1491250, uint256S("0x45a01a2b45ca91433c8c12378914463bd13afc410b27eeb18855d5b060d7e270"))( - 1492500, uint256S("0xd4185d9ae0c38211ac6e0ceddcca4207a00fc59d11b087e76c9bf6d4081856c8"))( - 1493040, uint256S("0xcd266ca5eaca1f561d3adf5ab0bc4994ea26418dd12d9072d5c5194639c40ac2"))}; -} - -void CNetworkManager::ConstructTetnet0Template() -{ - testnet0Template->strNetworkID = "TESTNET0"; - testnet0Template->strNetworkDataDir = "testnet0"; - testnet0Template->consensus.nMajorityEnforceBlockUpgrade = 750; - testnet0Template->consensus.nMajorityRejectBlockOutdated = 950; - testnet0Template->consensus.nMajorityWindow = 1000; - testnet0Template->consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - testnet0Template->consensus.posLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - testnet0Template->consensus.nTargetTimespan = 30 * 45; - testnet0Template->consensus.nTargetSpacing = 45; - testnet0Template->consensus.fPowAllowMinDifficultyBlocks = true; - testnet0Template->consensus.fPowNoRetargeting = true; - testnet0Template->consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 - testnet0Template->consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nTargetSpacing - testnet0Template->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; - // January 1, 2008 - testnet0Template->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; - // December 31, 2008 - testnet0Template->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; - - /** - * The message start string is designed to be unlikely to occur in normal data. - * The characters are rarely used upper ASCII, not valid as UTF-8, and produce - * a large 32-bit integer with any alignment. - */ - testnet0Template->pchMessageStart[0] = 0xee; - testnet0Template->pchMessageStart[1] = 0xff; - testnet0Template->pchMessageStart[2] = 0xaa; - testnet0Template->pchMessageStart[3] = 0xbb; - testnet0Template->nDefaultPort = 30000; - testnet0Template->nRPCPort = 30001; - testnet0Template->nMaxTipAge = 24 * 60 * 60; - testnet0Template->nStakeMaxAge = 60 * 60 * 24 * 84; // 84 days - testnet0Template->nStakeMinAge = 60 * 2; // 2 minutes - - const char *pszTimestamp = "AP | Sep 12, 2018, Testing0 begins"; - CTransaction txNew; - txNew.nTime = 1536781520; - txNew.vin.resize(1); - txNew.vout.resize(1); - txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(9999) - << std::vector((const unsigned char *)pszTimestamp, - (const unsigned char *)pszTimestamp + strlen(pszTimestamp)); - txNew.vout[0].SetEmpty(); - - testnet0Template->genesis.vtx.push_back(MakeTransactionRef(txNew)); - testnet0Template->genesis.hashPrevBlock.SetNull(); - testnet0Template->genesis.nVersion = 1; - testnet0Template->genesis.nTime = 1536781520; - testnet0Template->genesis.nBits = 0x1e0fffff; - testnet0Template->genesis.nNonce = 12799721; - testnet0Template->genesis.hashMerkleRoot = BlockMerkleRoot(testnet0Template->genesis); - - testnet0Template->consensus.hashGenesisBlock = testnet0Template->genesis.GetHash(); - assert(testnet0Template->consensus.hashGenesisBlock == - uint256S("0xcdf2b68d2fc9afdf991df5e321f59198189926ee757bf5efcf5c8c1a07b7c90e")); - assert(testnet0Template->genesis.hashMerkleRoot == - uint256S("0x68d635c49ffdd2bf5edf78149d0e2ea7dff97901d4596e865b87919853085311")); - - testnet0Template->base58Prefixes[CNetworkTemplate::PUBKEY_ADDRESS] = std::vector(1, 51); - testnet0Template->base58Prefixes[CNetworkTemplate::SCRIPT_ADDRESS] = std::vector(1, 15); - testnet0Template->base58Prefixes[CNetworkTemplate::SECRET_KEY] = std::vector(1, 159); - testnet0Template->base58Prefixes[CNetworkTemplate::EXT_PUBLIC_KEY] = - boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container >(); - testnet0Template->base58Prefixes[CNetworkTemplate::EXT_SECRET_KEY] = - boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container >(); - - testnet0Template->fMiningRequiresPeers = false; - testnet0Template->fDefaultConsistencyChecks = false; - testnet0Template->fRequireStandard = true; - testnet0Template->fMineBlocksOnDemand = false; - testnet0Template->fTestnetToBeDeprecatedFieldRPC = true; - - testnet0Template->checkpointData = (CCheckpointData){ - boost::assign::map_list_of(0, uint256S("0xcdf2b68d2fc9afdf991df5e321f59198189926ee757bf5efcf5c8c1a07b7c90e"))}; -} - -void CNetworkManager::ConstructRegTestTemplate() -{ - regTestTemplate->strNetworkID = "REGTEST"; - regTestTemplate->strNetworkDataDir = "regtest"; - regTestTemplate->consensus.nMajorityEnforceBlockUpgrade = 750; - regTestTemplate->consensus.nMajorityRejectBlockOutdated = 950; - regTestTemplate->consensus.nMajorityWindow = 1000; - regTestTemplate->consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - regTestTemplate->consensus.posLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - regTestTemplate->consensus.nTargetTimespan = 30 * 45; - regTestTemplate->consensus.nTargetSpacing = 45; - regTestTemplate->consensus.fPowAllowMinDifficultyBlocks = true; - regTestTemplate->consensus.fPowNoRetargeting = true; - regTestTemplate->consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 - regTestTemplate->consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nTargetSpacing - regTestTemplate->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; - // January 1, 2008 - regTestTemplate->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; - // December 31, 2008 - regTestTemplate->consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; - - /** - * The message start string is designed to be unlikely to occur in normal data. - * The characters are rarely used upper ASCII, not valid as UTF-8, and produce - * a large 32-bit integer with any alignment. - */ - regTestTemplate->pchMessageStart[0] = 0xaa; - regTestTemplate->pchMessageStart[1] = 0xbb; - regTestTemplate->pchMessageStart[2] = 0xcc; - regTestTemplate->pchMessageStart[3] = 0xdd; - regTestTemplate->nDefaultPort = 40000; - regTestTemplate->nRPCPort = 40001; - regTestTemplate->nMaxTipAge = 24 * 60 * 60; - regTestTemplate->nStakeMaxAge = 1; - regTestTemplate->nStakeMinAge = 1; - - const char *pszTimestamp = "AP | Sep 12, 2018, Regtest implemented"; - CTransaction txNew; - txNew.nTime = 1536781520; - txNew.vin.resize(1); - txNew.vout.resize(1); - txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(9999) - << std::vector((const unsigned char *)pszTimestamp, - (const unsigned char *)pszTimestamp + strlen(pszTimestamp)); - txNew.vout[0].SetEmpty(); - - regTestTemplate->genesis.vtx.push_back(MakeTransactionRef(txNew)); - regTestTemplate->genesis.hashPrevBlock.SetNull(); - regTestTemplate->genesis.nVersion = 1; - regTestTemplate->genesis.nTime = 1536781520; - regTestTemplate->genesis.nBits = 0x207fffff; - regTestTemplate->genesis.nNonce = 12799721; - regTestTemplate->genesis.hashMerkleRoot = BlockMerkleRoot(regTestTemplate->genesis); - - regTestTemplate->consensus.hashGenesisBlock = regTestTemplate->genesis.GetHash(); - assert(regTestTemplate->consensus.hashGenesisBlock == - uint256S("0x296d58ef241b0dde2372fbc7b09ec4aacf7b4dad88561f02469f3f4695c4fbb1")); - assert(regTestTemplate->genesis.hashMerkleRoot == - uint256S("0x3565e20605dbdfe7a63ec4b9f5b9d2d25b69fcc13d6bfd7cc42615fcd41a323c")); - - regTestTemplate->base58Prefixes[CNetworkTemplate::PUBKEY_ADDRESS] = std::vector(1, 51); - regTestTemplate->base58Prefixes[CNetworkTemplate::SCRIPT_ADDRESS] = std::vector(1, 15); - regTestTemplate->base58Prefixes[CNetworkTemplate::SECRET_KEY] = std::vector(1, 159); - regTestTemplate->base58Prefixes[CNetworkTemplate::EXT_PUBLIC_KEY] = - boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container >(); - regTestTemplate->base58Prefixes[CNetworkTemplate::EXT_SECRET_KEY] = - boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container >(); - - regTestTemplate->fMiningRequiresPeers = false; - regTestTemplate->fDefaultConsistencyChecks = true; - regTestTemplate->fRequireStandard = false; - regTestTemplate->fMineBlocksOnDemand = true; - regTestTemplate->fTestnetToBeDeprecatedFieldRPC = false; - - regTestTemplate->checkpointData = (CCheckpointData){ - boost::assign::map_list_of(0, uint256S("0x296d58ef241b0dde2372fbc7b09ec4aacf7b4dad88561f02469f3f4695c4fbb1"))}; -} - -std::string ChainNameFromCommandLine() -{ - bool fRegTest = gArgs.GetBoolArg("-regtest", false); - bool fTestNet = gArgs.GetBoolArg("-testnet0", false); - - if (fTestNet && fRegTest) - { - throw std::runtime_error("Invalid combination of -regtest and -testnet."); - } - if (fTestNet) - { - return "TESTNET0"; - } - if (fRegTest) - { - return "REGTEST"; - } - return "LEGACY"; -} - -int RPCPortFromCommandLine() -{ - bool fRegTest = gArgs.GetBoolArg("-regtest", false); - bool fTestNet = gArgs.GetBoolArg("-testnet0", false); - - if (fTestNet && fRegTest) - { - throw std::runtime_error("Invalid combination of -regtest and -testnet."); - } - if (fTestNet) - { - return 30001; - } - if (fRegTest) - { - return 40001; - } - return 19119; -} - -void CheckParams(const std::string &network) -{ - if (network != "LEGACY" && network != "TESTNET0" && network != "REGTEST") - { - throw std::runtime_error(strprintf("%s: Unknown network %s.", __func__, network)); - } - return; -} diff --git a/src/networks/netman.h b/src/networks/netman.h deleted file mode 100644 index 2df438fe..00000000 --- a/src/networks/netman.h +++ /dev/null @@ -1,108 +0,0 @@ -// This file is part of the Eccoin project -// Copyright (c) 2017-2018 Greg Griffith -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_CHAINPARAMSBASE_H -#define BITCOIN_CHAINPARAMSBASE_H - -#include -#include - -#include "network.h" - -static const int64_t SERVICE_UPGRADE_HARDFORK = 1525478400; // May 5th at 00:00:00 UTC - -/** - * CNetwork defines the base parameters (shared between bitcoin-cli and bitcoind) - * of a given instance of the Bitcoin system. - */ -class CNetworkManager -{ -private: - CNetwork *activePaymentNetwork; - - CNetwork *pnetLegacy; - CNetwork *pnetTestnet0; - CNetwork *pnetRegTest; - - CNetworkTemplate *legacyTemplate; - CNetworkTemplate *testnet0Template; - CNetworkTemplate *regTestTemplate; - -public: - CNetworkManager() - { - setNull(); - initialize(); - } - - void setNull() - { - legacyTemplate = nullptr; - testnet0Template = nullptr; - regTestTemplate = nullptr; - - - pnetLegacy = nullptr; - pnetTestnet0 = nullptr; - pnetRegTest = nullptr; - - activePaymentNetwork = nullptr; - } - - void initialize() - { - legacyTemplate = new CNetworkTemplate(); - ConstructLegacyNetworkTemplate(); - testnet0Template = new CNetworkTemplate(); - ConstructTetnet0Template(); - regTestTemplate = new CNetworkTemplate(); - ConstructRegTestTemplate(); - // only run construct networks after all templates have been made - ConstructNetworks(); - } - - void ConstructLegacyNetworkTemplate(); - void ConstructTetnet0Template(); - void ConstructRegTestTemplate(); - void ConstructNetworks(); - - CNetwork *getActivePaymentNetwork() { return activePaymentNetwork; } - CChainManager *getChainActive() { return activePaymentNetwork->getChainManager(); } - void SetParams(const std::string &network) - { - if (network == "LEGACY") - { - activePaymentNetwork = pnetLegacy; - } - else if (network == "TESTNET0") - { - activePaymentNetwork = pnetTestnet0; - } - else if (network == "REGTEST") - { - activePaymentNetwork = pnetRegTest; - } - else - { - throw std::runtime_error(strprintf("%s: Unknown network %s.", __func__, network)); - } - return; - } -}; - -// TODO : Fix this workaround that is used for RPC on command line. shuould either construct pnetMan earlier or find -// another way to get this value -int RPCPortFromCommandLine(); - -/** - * Looks for -regtest, -testnet and returns the appropriate BIP70 chain name. - * @return CBaseChainParams::MAX_NETWORK_TYPES if an invalid combination is given. CBaseChainParams::MAIN by default. - */ -std::string ChainNameFromCommandLine(); - - -void CheckParams(const std::string &network); - -#endif // BITCOIN_CHAINPARAMSBASE_H diff --git a/src/networks/network.h b/src/networks/network.h deleted file mode 100644 index 6fcd1d32..00000000 --- a/src/networks/network.h +++ /dev/null @@ -1,53 +0,0 @@ -// This file is part of the Eccoin project -// Copyright (c) 2017-2018 Greg Griffith -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef NETWORK_H -#define NETWORK_H - -#include -#include -#include - -#include "chain/chainman.h" -#include "networktemplate.h" - - -/** BIP70 chain name strings */ -/* - - //ecc networks - LEGACY = "LEGACY", // legacy network that started the chain in 2014 - - //service networks - ANS = "ANS" , // Address-Name Service (DNS for addresses to usernames) - CMTP = "CMTP", // Chain Mail Transfer Protocol - SFSP = "SFSP", // Secure File Storage Protocol (SFTP equivalent) - WEB = "WEB" , // (HTTP and HTTPS) - - /// if testnet or regtest are active, none of the service networks should be allowed to be - TESTNET0 = "TESTNET0", // - REGTEST = "REGTEST", // - -*/ - -/** - * CNetwork defines the base parameters (shared between bitcoin-cli and bitcoind) - * of a given instance of the Bitcoin system. - */ -class CNetwork : public CNetworkTemplate -{ -public: - CNetwork(CNetworkTemplate *param_netTemplate) : CNetworkTemplate(param_netTemplate) - { - this->chainman = CChainManager(); - } - const std::string &DataDir() const { return strNetworkDataDir; } - CChainManager *getChainManager() { return &chainman; } - /// TODO: put a check somewhere to make sure all data members have been set properly -private: - CChainManager chainman; -}; - -#endif // NETWORK_H diff --git a/src/pow.cpp b/src/pow.cpp index 297c3768..6b3e2ef0 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -10,7 +10,7 @@ #include "arith_uint256.h" #include "chain/chain.h" #include "main.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "uint256.h" #include "util/util.h" @@ -70,7 +70,7 @@ int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, sign = -1; } int64_t targetSpacing = params.nTargetSpacing; - if (tip.GetMedianTimePast() > SERVICE_UPGRADE_HARDFORK) + if (tip.GetMedianTimePast() > LONGER_BLOCKTIME_HARDFORK) { targetSpacing = 150; } diff --git a/src/processblock.cpp b/src/processblock.cpp index 061036e2..73efc968 100644 --- a/src/processblock.cpp +++ b/src/processblock.cpp @@ -26,8 +26,7 @@ #include "main.h" #include "net/messages.h" #include "net/net.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "policy/policy.h" #include "processblock.h" #include "processheader.h" @@ -46,19 +45,18 @@ CBlockIndex *pindexBestForkBase = nullptr; /** Update chainActive and related internal data structures. */ void UpdateTip(CBlockIndex *pindexNew) { - const CNetworkTemplate &chainParams = pnetMan->getActivePaymentNetwork(); - pnetMan->getChainActive()->chainActive.SetTip(pindexNew); + g_chainman.chainActive.SetTip(pindexNew); // New best block nTimeBestReceived.store(GetTime()); mempool.AddTransactionsUpdated(1); LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s cache=%.1fMiB(%utx)\n", __func__, - pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash().ToString(), - pnetMan->getChainActive()->chainActive.Height(), - log(pnetMan->getChainActive()->chainActive.Tip()->nChainWork.getdouble()) / log(2.0), - (unsigned long)(pnetMan->getChainActive()->chainActive.Tip()->nChainTx), - DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pnetMan->getChainActive()->chainActive.Tip()->GetBlockTime()), + g_chainman.chainActive.Tip()->GetBlockHash().ToString(), + g_chainman.chainActive.Height(), + log(g_chainman.chainActive.Tip()->nChainWork.getdouble()) / log(2.0), + (unsigned long)(g_chainman.chainActive.Tip()->nChainTx), + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", g_chainman.chainActive.Tip()->GetBlockTime()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1 << 20)), pcoinsTip->GetCacheSize()); cvBlockChange.notify_all(); @@ -68,7 +66,7 @@ void UpdateTip(CBlockIndex *pindexNew) * after this, with cs_main held. */ bool DisconnectTip(CValidationState &state, const Consensus::Params &consensusParams) { - CBlockIndex *pindexDelete = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexDelete = g_chainman.chainActive.Tip(); assert(pindexDelete); // Read block from disk. std::shared_ptr pblock = std::make_shared(); @@ -128,12 +126,12 @@ bool DisconnectTip(CValidationState &state, const Consensus::Params &consensusPa * corresponding to pindexNew, to bypass loading it again from disk. */ bool ConnectTip(CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, CBlockIndex *pindexNew, const CBlock *pblock) { AssertLockHeld(cs_main); - assert(pindexNew->pprev == pnetMan->getChainActive()->chainActive.Tip()); + assert(pindexNew->pprev == g_chainman.chainActive.Tip()); // Read block from disk. CBlock block; if (!pblock) @@ -165,7 +163,7 @@ bool ConnectTip(CValidationState &state, // Remove conflicting transactions from the mempool. std::list txConflicted; mempool.removeForBlock( - pblock->vtx, pindexNew->nHeight, txConflicted, !pnetMan->getChainActive()->IsInitialBlockDownload()); + pblock->vtx, pindexNew->nHeight, txConflicted, !g_chainman.IsInitialBlockDownload()); // Update chainActive & related variables. UpdateTip(pindexNew); @@ -208,18 +206,18 @@ void CheckForkWarningConditions() AssertLockHeld(cs_main); // Before we get past initial download, we cannot reliably alert about forks // (we assume we don't get stuck on a fork before the last checkpoint) - if (pnetMan->getChainActive()->IsInitialBlockDownload()) + if (g_chainman.IsInitialBlockDownload()) return; // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it) // of our head, drop it - if (pindexBestForkTip && pnetMan->getChainActive()->chainActive.Height() - pindexBestForkTip->nHeight >= 72) + if (pindexBestForkTip && g_chainman.chainActive.Height() - pindexBestForkTip->nHeight >= 72) pindexBestForkTip = NULL; if (pindexBestForkTip || (pindexBestInvalid && - pindexBestInvalid->nChainWork > pnetMan->getChainActive()->chainActive.Tip()->nChainWork + - (GetBlockProof(*pnetMan->getChainActive()->chainActive.Tip()) * 6))) + pindexBestInvalid->nChainWork > g_chainman.chainActive.Tip()->nChainWork + + (GetBlockProof(*g_chainman.chainActive.Tip()) * 6))) { if (!fLargeWorkForkFound && pindexBestForkBase) { @@ -255,7 +253,7 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip) AssertLockHeld(cs_main); // If we are on a fork that is sufficiently large, set a warning flag CBlockIndex *pfork = pindexNewForkTip; - CBlockIndex *plonger = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *plonger = g_chainman.chainActive.Tip(); while (pfork && pfork != plonger) { while (plonger && plonger->nHeight > pfork->nHeight) @@ -275,7 +273,7 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip) if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) && pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && - pnetMan->getChainActive()->chainActive.Height() - pindexNewForkTip->nHeight < 72) + g_chainman.chainActive.Height() - pindexNewForkTip->nHeight < 72) { pindexBestForkTip = pindexNewForkTip; pindexBestForkBase = pfork; @@ -289,18 +287,18 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip) * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork. */ bool ActivateBestChainStep(CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, CBlockIndex *pindexMostWork, const CBlock *pblock) { AssertLockHeld(cs_main); bool fInvalidFound = false; - const CBlockIndex *pindexOldTip = pnetMan->getChainActive()->chainActive.Tip(); - const CBlockIndex *pindexFork = pnetMan->getChainActive()->chainActive.FindFork(pindexMostWork); + const CBlockIndex *pindexOldTip = g_chainman.chainActive.Tip(); + const CBlockIndex *pindexFork = g_chainman.chainActive.FindFork(pindexMostWork); // Disconnect active blocks which are no longer in the best chain. bool fBlocksDisconnected = false; - while (pnetMan->getChainActive()->chainActive.Tip() && pnetMan->getChainActive()->chainActive.Tip() != pindexFork) + while (g_chainman.chainActive.Tip() && g_chainman.chainActive.Tip() != pindexFork) { if (!DisconnectTip(state, chainparams.GetConsensus())) return false; @@ -353,16 +351,16 @@ bool ActivateBestChainStep(CValidationState &state, else { pindexNewTip = pindexConnect; - if (!pnetMan->getChainActive()->IsInitialBlockDownload()) + if (!g_chainman.IsInitialBlockDownload()) { // Notify external zmq listeners about the new tip. GetMainSignals().UpdatedBlockTip(pindexConnect); } - BlockNotifyCallback(pnetMan->getChainActive()->IsInitialBlockDownload(), pindexNewTip); + BlockNotifyCallback(g_chainman.IsInitialBlockDownload(), pindexNewTip); PruneBlockIndexCandidates(); if (!pindexOldTip || - pnetMan->getChainActive()->chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) + g_chainman.chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) { // We're in a better position than we were. Return temporarily to release the lock. fContinue = false; @@ -383,10 +381,10 @@ bool ActivateBestChainStep(CValidationState &state, } // Relay Inventory - CBlockIndex *pindexNewTip = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexNewTip = g_chainman.chainActive.Tip(); if (pindexFork != pindexNewTip) { - if (!pnetMan->getChainActive()->IsInitialBlockDownload()) + if (!g_chainman.IsInitialBlockDownload()) { // Find the hashes of all blocks that weren't previously in the best chain. std::vector vHashes; @@ -420,7 +418,7 @@ bool ActivateBestChainStep(CValidationState &state, if (fBlocksDisconnected) { mempool.removeForReorg( - pcoinsTip.get(), pnetMan->getChainActive()->chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + pcoinsTip.get(), g_chainman.chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); } @@ -443,7 +441,7 @@ bool ActivateBestChainStep(CValidationState &state, * or an activated best chain. pblock is either NULL or a pointer to a block * that is already loaded (to avoid loading it again from disk). */ -bool ActivateBestChain(CValidationState &state, const CNetworkTemplate &chainparams, const CBlock *pblock) +bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, const CBlock *pblock) { CBlockIndex *pindexMostWork = nullptr; LOCK(cs_main); @@ -462,9 +460,9 @@ bool ActivateBestChain(CValidationState &state, const CNetworkTemplate &chainpar } // Whether we have anything to do at all. - if (pnetMan->getChainActive()->chainActive.Tip() != nullptr) + if (g_chainman.chainActive.Tip() != nullptr) { - if (pindexMostWork->nChainWork <= pnetMan->getChainActive()->chainActive.Tip()->nChainWork) + if (pindexMostWork->nChainWork <= g_chainman.chainActive.Tip()->nChainWork) return true; } if (!ActivateBestChainStep(state, chainparams, pindexMostWork, @@ -476,7 +474,7 @@ bool ActivateBestChain(CValidationState &state, const CNetworkTemplate &chainpar if (!pindexMostWork) return false; pblock = nullptr; - } while (pindexMostWork->nChainWork > pnetMan->getChainActive()->chainActive.Tip()->nChainWork); + } while (pindexMostWork->nChainWork > g_chainman.chainActive.Tip()->nChainWork); CheckBlockIndex(chainparams.GetConsensus()); // Write changes periodically to disk if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) @@ -495,26 +493,26 @@ void CheckBlockIndex(const Consensus::Params &consensusParams) } LOCK(cs_main); - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain, // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when // iterating the block tree require that chainActive has been initialized.) - if (pnetMan->getChainActive()->chainActive.Height() < 0) + if (g_chainman.chainActive.Height() < 0) { - assert(pnetMan->getChainActive()->mapBlockIndex.size() <= 1); + assert(g_chainman.mapBlockIndex.size() <= 1); return; } // Build forward-pointing map of the entire block tree. std::multimap forward; - for (BlockMap::iterator it = pnetMan->getChainActive()->mapBlockIndex.begin(); - it != pnetMan->getChainActive()->mapBlockIndex.end(); it++) + for (BlockMap::iterator it = g_chainman.mapBlockIndex.begin(); + it != g_chainman.mapBlockIndex.end(); it++) { forward.insert(std::make_pair(it->second->pprev, it->second)); } - assert(forward.size() == pnetMan->getChainActive()->mapBlockIndex.size()); + assert(forward.size() == g_chainman.mapBlockIndex.size()); std::pair::iterator, std::multimap::iterator> @@ -567,7 +565,7 @@ void CheckBlockIndex(const Consensus::Params &consensusParams) // Genesis block checks. assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match. // The current active chain's genesis block must be this block. - assert(pindex == pnetMan->getChainActive()->chainActive.Genesis()); + assert(pindex == g_chainman.chainActive.Genesis()); } // nSequenceId can't be set for blocks that aren't linked if (pindex->nChainTx == 0) @@ -609,7 +607,7 @@ void CheckBlockIndex(const Consensus::Params &consensusParams) // The failed mask cannot be set for blocks without invalid parents. assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); } - if (!CBlockIndexWorkComparator()(pindex, pnetMan->getChainActive()->chainActive.Tip()) && + if (!CBlockIndexWorkComparator()(pindex, g_chainman.chainActive.Tip()) && pindexFirstNeverProcessed == NULL) { if (pindexFirstInvalid == NULL) @@ -618,7 +616,7 @@ void CheckBlockIndex(const Consensus::Params &consensusParams) // is valid and we have all data for its parents, it must be in // setBlockIndexCandidates. chainActive.Tip() must also be there // even if some data has been pruned. - if (pindexFirstMissing == NULL || pindex == pnetMan->getChainActive()->chainActive.Tip()) + if (pindexFirstMissing == NULL || pindex == g_chainman.chainActive.Tip()) { assert(setBlockIndexCandidates.count(pindex)); } @@ -759,7 +757,7 @@ CBlockIndex *FindMostWorkChain() // Just going until the active chain is an optimization, as we know all blocks in it are valid already. CBlockIndex *pindexTest = pindexNew; bool fInvalidAncestor = false; - while (pindexTest && !pnetMan->getChainActive()->chainActive.Contains(pindexTest)) + while (pindexTest && !g_chainman.chainActive.Contains(pindexTest)) { assert(pindexTest->nChainTx || pindexTest->nHeight == 0); @@ -814,10 +812,10 @@ void InvalidChainFound(CBlockIndex *pindexNew) LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__, pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, log(pindexNew->nChainWork.getdouble()) / log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime())); - CBlockIndex *tip = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *tip = g_chainman.chainActive.Tip(); assert(tip); LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__, tip->GetBlockHash().ToString(), - pnetMan->getChainActive()->chainActive.Height(), log(tip->nChainWork.getdouble()) / log(2.0), + g_chainman.chainActive.Height(), log(tip->nChainWork.getdouble()) / log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime())); CheckForkWarningConditions(); } @@ -882,13 +880,13 @@ bool ConnectBlock(const CBlock &block, CCoinsViewCache &view, bool fJustCheck) { - const CNetworkTemplate &chainparams = pnetMan->getActivePaymentNetwork(); + const CChainParams &chainparams = Params(); AssertLockHeld(cs_main); if (pindex->GetBlockHash() != chainparams.GetConsensus().hashGenesisBlock) { // need cs_mapBlockIndex to update the index - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); // once updateForPos runs the only flags that should be enabled are the ones that determine if PoS block or not // before this runs there should have been no flags set. so it is ok to reset the flags to 0 pindex->updateForPos(block); @@ -1087,7 +1085,7 @@ bool ConnectBlock(const CBlock &block, } { - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); // ppcoin: track money supply and mint amount info pindex->nMint = nValueOut - nValueIn + nFees; pindex->nMoneySupply = (pindex->pprev ? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn; @@ -1115,7 +1113,7 @@ bool ConnectBlock(const CBlock &block, } { - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); // ppcoin: record proof-of-stake hash value pindex->hashProofOfStake = hashProofOfStake; } @@ -1136,7 +1134,7 @@ bool ConnectBlock(const CBlock &block, "bad-stakemodifier-pow"); } { - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); pindex->SetStakeModifier(nStakeModifier); } if (fJustCheck) @@ -1296,7 +1294,7 @@ DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */ bool AcceptBlock(const CBlock *pblock, CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, CBlockIndex **ppindex, bool fRequested, CDiskBlockPos *dbp) @@ -1312,15 +1310,15 @@ bool AcceptBlock(const CBlock *pblock, // process an unrequested block if it's new and has enough work to // advance our tip, and isn't too many blocks ahead. bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA; - bool fHasMoreWork = (pnetMan->getChainActive()->chainActive.Tip() ? - pindex->nChainWork > pnetMan->getChainActive()->chainActive.Tip()->nChainWork : + bool fHasMoreWork = (g_chainman.chainActive.Tip() ? + pindex->nChainWork > g_chainman.chainActive.Tip()->nChainWork : true); // Blocks that are too out-of-order needlessly limit the effectiveness of // pruning, because pruning will not delete block files that contain any // blocks which are too close in height to the tip. Apply this test // regardless of whether pruning is enabled; it should generally be safe to // not process unrequested blocks. - bool fTooFarAhead = (pindex->nHeight > int(pnetMan->getChainActive()->chainActive.Height() + MIN_BLOCKS_TO_KEEP)); + bool fTooFarAhead = (pindex->nHeight > int(g_chainman.chainActive.Height() + MIN_BLOCKS_TO_KEEP)); // TODO: deal better with return value and error conditions for duplicate // and unrequested blocks. @@ -1349,8 +1347,8 @@ bool AcceptBlock(const CBlock *pblock, // Header is valid/has work, merkle tree and segwit merkle tree are // good...RELAY NOW (but if it does not build on our best tip, let the // SendMessages loop relay it) - if (!pnetMan->getChainActive()->IsInitialBlockDownload() && - pnetMan->getChainActive()->chainActive.Tip() == pindex->pprev) + if (!g_chainman.IsInitialBlockDownload() && + g_chainman.chainActive.Tip() == pindex->pprev) { GetMainSignals().NewPoWValidBlock(pindex, pblock); } @@ -1392,7 +1390,7 @@ bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bo } if (block.IsProofOfWork() && fCheckPOW && - !CheckProofOfWork(block.GetHash(), block.nBits, pnetMan->getActivePaymentNetwork()->GetConsensus())) + !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())) { return state.DoS(50, error("CheckBlockHeader(): proof of work failed"), REJECT_INVALID, "high-hash"); } @@ -1508,7 +1506,7 @@ bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bo } bool ProcessNewBlock(CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, const CNode *pfrom, const CBlock *pblock, bool fForceProcessing, @@ -1519,7 +1517,7 @@ bool ProcessNewBlock(CValidationState &state, { LOCK(cs_main); - RECURSIVEWRITELOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEWRITELOCK(g_chainman.cs_mapBlockIndex); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; if (!checked) diff --git a/src/processblock.h b/src/processblock.h index 5c587c54..103ed2a6 100644 --- a/src/processblock.h +++ b/src/processblock.h @@ -15,7 +15,7 @@ class CValidationState; class CNode; class CBlock; -class CNetworkTemplate; +class CChainParams; class CDiskBlockPos; class CBlockIndex; @@ -47,7 +47,7 @@ bool ConnectBlock(const CBlock &block, DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &coins); /** Find the best known block, and make it the tip of the block chain */ -bool ActivateBestChain(CValidationState &state, const CNetworkTemplate &chainparams, const CBlock *pblock = nullptr); +bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, const CBlock *pblock = nullptr); /** * Process an incoming block. This only returns after the best known valid @@ -68,7 +68,7 @@ bool ActivateBestChain(CValidationState &state, const CNetworkTemplate &chainpar * @return True if state.IsValid() */ bool ProcessNewBlock(CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, const CNode *pfrom, const CBlock *pblock, bool fForceProcessing, diff --git a/src/processheader.cpp b/src/processheader.cpp index 5a7b90eb..80b35904 100644 --- a/src/processheader.cpp +++ b/src/processheader.cpp @@ -14,14 +14,14 @@ bool AcceptBlockHeader(const CBlockHeader &block, CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, CBlockIndex **ppindex) { AssertLockHeld(cs_main); - // AssertRecursiveWriteLockHeld(pnetMan->getChainActive()->cs_mapBlockIndex); + // AssertRecursiveWriteLockHeld(g_chainman.cs_mapBlockIndex); // Check for duplicate uint256 hash = block.GetHash(); - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hash); if (hash != chainparams.GetConsensus().hashGenesisBlock) { if (pindex) @@ -38,7 +38,7 @@ bool AcceptBlockHeader(const CBlockHeader &block, return false; // Get prev block index - CBlockIndex *pindexPrev = pnetMan->getChainActive()->LookupBlockIndex(block.hashPrevBlock); + CBlockIndex *pindexPrev = g_chainman.LookupBlockIndex(block.hashPrevBlock); if (!pindexPrev) { return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk"); @@ -55,7 +55,7 @@ bool AcceptBlockHeader(const CBlockHeader &block, } if (pindex == nullptr) { - pindex = pnetMan->getChainActive()->AddToBlockIndex(block); + pindex = g_chainman.AddToBlockIndex(block); } if (ppindex) diff --git a/src/processheader.h b/src/processheader.h index 962a0dff..0d484aaa 100644 --- a/src/processheader.h +++ b/src/processheader.h @@ -8,14 +8,14 @@ #ifndef PROCESSHEADER_H #define PROCESSHEADER_H -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "validationinterface.h" bool CheckBlockHeader(const CBlockHeader &block, CValidationState &state); bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, CBlockIndex *pindexPrev); bool AcceptBlockHeader(const CBlockHeader &block, CValidationState &state, - const CNetworkTemplate &chainparams, + const CChainParams &chainparams, CBlockIndex **ppindex = NULL); #endif // PROCESSHEADER_H diff --git a/src/rpc/rpcblockchain.cpp b/src/rpc/rpcblockchain.cpp index 7f4b6520..fba2d3f9 100644 --- a/src/rpc/rpcblockchain.cpp +++ b/src/rpc/rpcblockchain.cpp @@ -15,8 +15,7 @@ #include "consensus/validation.h" #include "init.h" #include "main.h" -#include "networks/netman.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "policy/policy.h" #include "processblock.h" #include "rpcserver.h" @@ -31,7 +30,7 @@ #include -extern CNetworkManager *pnetMan; + extern void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry); void ScriptPubKeyToJSON(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex); @@ -42,10 +41,10 @@ double GetDifficulty(const CBlockIndex *blockindex) // minimum difficulty = 1.0. if (blockindex == NULL) { - if (pnetMan->getChainActive()->chainActive.Tip() == NULL) + if (g_chainman.chainActive.Tip() == NULL) return 1.0; else - blockindex = pnetMan->getChainActive()->chainActive.Tip(); + blockindex = g_chainman.chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; @@ -72,8 +71,8 @@ UniValue blockheaderToJSON(const CBlockIndex *blockindex) result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain - if (pnetMan->getChainActive()->chainActive.Contains(blockindex)) - confirmations = pnetMan->getChainActive()->chainActive.Height() - blockindex->nHeight + 1; + if (g_chainman.chainActive.Contains(blockindex)) + confirmations = g_chainman.chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); @@ -87,7 +86,7 @@ UniValue blockheaderToJSON(const CBlockIndex *blockindex) if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); - CBlockIndex *pnext = pnetMan->getChainActive()->chainActive.Next(blockindex); + CBlockIndex *pnext = g_chainman.chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; @@ -99,8 +98,8 @@ UniValue blockToJSON(const CBlock &block, const CBlockIndex *blockindex, bool tx result.push_back(Pair("hash", block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain - if (pnetMan->getChainActive()->chainActive.Contains(blockindex)) - confirmations = pnetMan->getChainActive()->chainActive.Height() - blockindex->nHeight + 1; + if (g_chainman.chainActive.Contains(blockindex)) + confirmations = g_chainman.chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); @@ -129,7 +128,7 @@ UniValue blockToJSON(const CBlock &block, const CBlockIndex *blockindex, bool tx if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); - CBlockIndex *pnext = pnetMan->getChainActive()->chainActive.Next(blockindex); + CBlockIndex *pnext = g_chainman.chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s", blockindex->IsProofOfStake() ? "proof-of-stake" : "proof-of-work"))); @@ -154,7 +153,7 @@ UniValue getblockcount(const UniValue ¶ms, bool fHelp) "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "")); - return pnetMan->getChainActive()->chainActive.Height(); + return g_chainman.chainActive.Height(); } UniValue getbestblockhash(const UniValue ¶ms, bool fHelp) @@ -167,7 +166,7 @@ UniValue getbestblockhash(const UniValue ¶ms, bool fHelp) "\nExamples\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "")); - return pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash().GetHex(); + return g_chainman.chainActive.Tip()->GetBlockHash().GetHex(); } UniValue getdifficulty(const UniValue ¶ms, bool fHelp) @@ -200,7 +199,7 @@ UniValue mempoolToJSON(bool fVerbose = false) info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); - info.push_back(Pair("currentpriority", e.GetPriority(pnetMan->getChainActive()->chainActive.Height()))); + info.push_back(Pair("currentpriority", e.GetPriority(g_chainman.chainActive.Height()))); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); @@ -296,11 +295,11 @@ UniValue getblockhash(const UniValue ¶ms, bool fHelp) HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000")); int nHeight = params[0].get_int(); - if (nHeight < 0 || nHeight > pnetMan->getChainActive()->chainActive.Height()) + if (nHeight < 0 || nHeight > g_chainman.chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - CBlockIndex *pblockindex = pnetMan->getChainActive()->chainActive[nHeight]; + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + CBlockIndex *pblockindex = g_chainman.chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } @@ -346,7 +345,7 @@ UniValue getblockheader(const UniValue ¶ms, bool fHelp) if (params.size() > 1) fVerbose = params[1].get_bool(); - CBlockIndex *pblockindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pblockindex = g_chainman.LookupBlockIndex(hash); if (!pblockindex) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); @@ -409,13 +408,13 @@ UniValue getblock(const UniValue ¶ms, bool fHelp) if (params.size() > 1) fVerbose = params[1].get_bool(); - pblockindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + pblockindex = g_chainman.LookupBlockIndex(hash); if (!pblockindex) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; { - if (!ReadBlockFromDisk(block, pblockindex, pnetMan->getActivePaymentNetwork()->GetConsensus())) + if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); } @@ -459,7 +458,7 @@ static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats) CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = pcursor->GetBestBlock(); - stats.nHeight = pnetMan->getChainActive()->LookupBlockIndex(stats.hashBlock)->nHeight; + stats.nHeight = g_chainman.LookupBlockIndex(stats.hashBlock)->nHeight; ss << stats.hashBlock; uint256 prevkey; std::map outputs; @@ -599,7 +598,7 @@ UniValue gettxout(const UniValue ¶ms, bool fHelp) } } - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(pcoinsTip->GetBestBlock()); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(pcoinsTip->GetBestBlock()); ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coin.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); @@ -638,7 +637,7 @@ UniValue verifychain(const UniValue ¶ms, bool fHelp) if (params.size() > 1) nCheckDepth = params[1].get_int(); - return CVerifyDB().VerifyDB(pnetMan->getActivePaymentNetwork(), pcoinsTip.get(), nCheckLevel, nCheckDepth); + return CVerifyDB().VerifyDB(Params(), pcoinsTip.get(), nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ @@ -727,20 +726,20 @@ UniValue getblockchaininfo(const UniValue ¶ms, bool fHelp) HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "")); UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("chain", pnetMan->getActivePaymentNetwork()->NetworkIDString())); - obj.push_back(Pair("blocks", (int)pnetMan->getChainActive()->chainActive.Height())); - obj.push_back(Pair("headers", pnetMan->getChainActive()->pindexBestHeader ? - pnetMan->getChainActive()->pindexBestHeader.load()->nHeight : + obj.push_back(Pair("chain", Params().NetworkIDString())); + obj.push_back(Pair("blocks", (int)g_chainman.chainActive.Height())); + obj.push_back(Pair("headers", g_chainman.pindexBestHeader ? + g_chainman.pindexBestHeader.load()->nHeight : -1)); - obj.push_back(Pair("bestblockhash", pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash().GetHex())); + obj.push_back(Pair("bestblockhash", g_chainman.chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); - obj.push_back(Pair("mediantime", (int64_t)pnetMan->getChainActive()->chainActive.Tip()->GetMedianTimePast())); - obj.push_back(Pair("initialblockdownload", pnetMan->getChainActive()->IsInitialBlockDownload())); - obj.push_back(Pair("chainwork", pnetMan->getChainActive()->chainActive.Tip()->nChainWork.GetHex())); + obj.push_back(Pair("mediantime", (int64_t)g_chainman.chainActive.Tip()->GetMedianTimePast())); + obj.push_back(Pair("initialblockdownload", g_chainman.IsInitialBlockDownload())); + obj.push_back(Pair("chainwork", g_chainman.chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair("size_on_disk", CalculateCurrentUsage())); - const Consensus::Params &consensusParams = pnetMan->getActivePaymentNetwork()->GetConsensus(); - CBlockIndex *tip = pnetMan->getChainActive()->chainActive.Tip(); + const Consensus::Params &consensusParams = Params().GetConsensus(); + CBlockIndex *tip = g_chainman.chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VARR); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); @@ -782,10 +781,10 @@ static std::set GetChainTips() std::set setOrphans; std::set setPrevs; - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - for (const std::pair &item : pnetMan->getChainActive()->mapBlockIndex) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + for (const std::pair &item : g_chainman.mapBlockIndex) { - if (!pnetMan->getChainActive()->chainActive.Contains(item.second)) + if (!g_chainman.chainActive.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); @@ -801,7 +800,7 @@ static std::set GetChainTips() } // Always report the currently active tip. - setTips.insert(pnetMan->getChainActive()->chainActive.Tip()); + setTips.insert(g_chainman.chainActive.Tip()); return setTips; } @@ -850,11 +849,11 @@ UniValue getchaintips(const UniValue ¶ms, bool fHelp) obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); - const int branchLen = block->nHeight - pnetMan->getChainActive()->chainActive.FindFork(block)->nHeight; + const int branchLen = block->nHeight - g_chainman.chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); std::string status; - if (pnetMan->getChainActive()->chainActive.Contains(block)) + if (g_chainman.chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; @@ -942,15 +941,15 @@ UniValue invalidateblock(const UniValue ¶ms, bool fHelp) uint256 hash(uint256S(strHash)); CValidationState state; - CBlockIndex *pblockindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pblockindex = g_chainman.LookupBlockIndex(hash); if (!pblockindex) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); - InvalidateBlock(state, pnetMan->getActivePaymentNetwork()->GetConsensus(), pblockindex); + InvalidateBlock(state, Params().GetConsensus(), pblockindex); if (state.IsValid()) { - ActivateBestChain(state, pnetMan->getActivePaymentNetwork()); + ActivateBestChain(state, Params()); } if (!state.IsValid()) @@ -978,7 +977,7 @@ UniValue reconsiderblock(const UniValue ¶ms, bool fHelp) uint256 hash(uint256S(strHash)); CValidationState state; - CBlockIndex *pblockindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pblockindex = g_chainman.LookupBlockIndex(hash); if (!pblockindex) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); @@ -989,7 +988,7 @@ UniValue reconsiderblock(const UniValue ¶ms, bool fHelp) if (state.IsValid()) { - ActivateBestChain(state, pnetMan->getActivePaymentNetwork()); + ActivateBestChain(state, Params()); } if (!state.IsValid()) diff --git a/src/rpc/rpcdump.cpp b/src/rpc/rpcdump.cpp index dd9cd5f6..d51e59b1 100644 --- a/src/rpc/rpcdump.cpp +++ b/src/rpc/rpcdump.cpp @@ -142,7 +142,7 @@ UniValue importprivkey(const UniValue ¶ms, bool fHelp) if (fRescan) { - pwalletMain->ScanForWalletTransactions(pnetMan->getChainActive()->chainActive.Genesis(), true); + pwalletMain->ScanForWalletTransactions(g_chainman.chainActive.Genesis(), true); } } @@ -232,7 +232,7 @@ UniValue importaddress(const UniValue ¶ms, bool fHelp) if (fRescan) { - pwalletMain->ScanForWalletTransactions(pnetMan->getChainActive()->chainActive.Genesis(), true); + pwalletMain->ScanForWalletTransactions(g_chainman.chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } @@ -278,7 +278,7 @@ UniValue importpubkey(const UniValue ¶ms, bool fHelp) if (fRescan) { - pwalletMain->ScanForWalletTransactions(pnetMan->getChainActive()->chainActive.Genesis(), true); + pwalletMain->ScanForWalletTransactions(g_chainman.chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } @@ -311,7 +311,7 @@ UniValue importwallet(const UniValue ¶ms, bool fHelp) if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); - int64_t nTimeBegin = pnetMan->getChainActive()->chainActive.Tip()->GetBlockTime(); + int64_t nTimeBegin = g_chainman.chainActive.Tip()->GetBlockTime(); bool fGood = true; @@ -370,14 +370,14 @@ UniValue importwallet(const UniValue ¶ms, bool fHelp) } file.close(); - CBlockIndex *pindex = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindex = g_chainman.chainActive.Tip(); while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; - LogPrintf("Rescanning last %i blocks\n", pnetMan->getChainActive()->chainActive.Height() - pindex->nHeight + 1); + LogPrintf("Rescanning last %i blocks\n", g_chainman.chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); @@ -463,10 +463,10 @@ UniValue dumpwallet(const UniValue ¶ms, bool fHelp) file << strprintf("# Wallet dump created by Eccoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", - pnetMan->getChainActive()->chainActive.Height(), - pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash().ToString()); + g_chainman.chainActive.Height(), + g_chainman.chainActive.Tip()->GetBlockHash().ToString()); file << strprintf( - "# mined on %s\n", EncodeDumpTime(pnetMan->getChainActive()->chainActive.Tip()->GetBlockTime())); + "# mined on %s\n", EncodeDumpTime(g_chainman.chainActive.Tip()->GetBlockTime())); file << "\n"; for (std::vector >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { diff --git a/src/rpc/rpcmining.cpp b/src/rpc/rpcmining.cpp index d61c2010..b4ce2639 100644 --- a/src/rpc/rpcmining.cpp +++ b/src/rpc/rpcmining.cpp @@ -16,7 +16,7 @@ #include "init.h" #include "main.h" #include "net/net.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "pow.h" #include "processblock.h" #include "processheader.h" @@ -42,17 +42,17 @@ */ UniValue GetNetworkHashPS(int lookup, int height) { - CBlockIndex *pb = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pb = g_chainman.chainActive.Tip(); - if (height >= 0 && height < pnetMan->getChainActive()->chainActive.Height()) - pb = pnetMan->getChainActive()->chainActive[height]; + if (height >= 0 && height < g_chainman.chainActive.Height()) + pb = g_chainman.chainActive[height]; if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) - lookup = pb->nHeight % pnetMan->getActivePaymentNetwork()->GetConsensus().DifficultyAdjustmentInterval() + 1; + lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) @@ -150,7 +150,7 @@ UniValue generateBlocks(boost::shared_ptr coinbaseScript, { // Don't keep cs_main locked LOCK(cs_main); - nHeightStart = pnetMan->getChainActive()->chainActive.Height(); + nHeightStart = g_chainman.chainActive.Height(); nHeight = nHeightStart; nHeightEnd = nHeightStart + nGenerate; } @@ -166,10 +166,10 @@ UniValue generateBlocks(boost::shared_ptr coinbaseScript, { // LOCK(cs_main); - IncrementExtraNonce(pblock, pnetMan->getChainActive()->chainActive.Tip(), nExtraNonce); + IncrementExtraNonce(pblock, g_chainman.chainActive.Tip(), nExtraNonce); } while (pblock->IsProofOfWork() && nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && - !CheckProofOfWork(pblock->GetHash(), pblock->nBits, pnetMan->getActivePaymentNetwork()->GetConsensus())) + !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) { ++pblock->nNonce; --nMaxTries; @@ -204,7 +204,7 @@ UniValue generateBlocks(boost::shared_ptr coinbaseScript, LogPrintf("generated %s\n", FormatMoney(vout.nValue).c_str()); } } - if (!ProcessNewBlock(state, pnetMan->getActivePaymentNetwork(), nullptr, pblock, true, nullptr)) + if (!ProcessNewBlock(state, Params(), nullptr, pblock, true, nullptr)) throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted"); ++nHeight; blockHashes.push_back(pblock->GetHash().GetHex()); @@ -234,7 +234,7 @@ UniValue generate(const UniValue ¶ms, bool fHelp) "\nGenerate 11 blocks\n" + HelpExampleCli("generate", "11")); - if (!pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + if (!Params().MineBlocksOnDemand()) { throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest"); } @@ -274,7 +274,7 @@ UniValue generatepos(const UniValue ¶ms, bool fHelp) "\nGenerate 11 blocks\n" + HelpExampleCli("generate", "11")); - if (!pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + if (!Params().MineBlocksOnDemand()) { throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest"); } @@ -318,7 +318,7 @@ UniValue generatetoaddress(const UniValue ¶ms, bool fHelp) HelpExampleCli("generate", "11 \"myaddress\"")); } - if (!pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + if (!Params().MineBlocksOnDemand()) { throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest"); } @@ -366,7 +366,7 @@ UniValue generatepostoaddress(const UniValue ¶ms, bool fHelp) HelpExampleCli("generate", "11 \"myaddress\"")); } - if (!pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + if (!Params().MineBlocksOnDemand()) { throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest"); } @@ -409,7 +409,7 @@ UniValue setgenerate(const UniValue ¶ms, bool fHelp) "\nToggle the pow generation\n" + HelpExampleCli("setgenerate", "")); - // if (pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + // if (Params().MineBlocksOnDemand()) // throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network"); ThreadGeneration(pwalletMain, false, false); @@ -429,7 +429,7 @@ UniValue setgeneratepos(const UniValue ¶ms, bool fHelp) "\nToggle the pos generation\n" + HelpExampleCli("setgeneratepos", "")); - if (pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + if (Params().MineBlocksOnDemand()) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgeneratepos on this network"); ThreadGeneration(pwalletMain, false, true); @@ -466,15 +466,15 @@ UniValue getmininginfo(const UniValue ¶ms, bool fHelp) LOCK(cs_main); UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("blocks", (int)pnetMan->getChainActive()->chainActive.Height())); + obj.push_back(Pair("blocks", (int)g_chainman.chainActive.Height())); obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); - obj.push_back(Pair("testnet", pnetMan->getActivePaymentNetwork()->TestnetToBeDeprecatedFieldRPC())); - obj.push_back(Pair("chain", pnetMan->getActivePaymentNetwork()->NetworkIDString())); + obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC())); + obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("generate", getgenerate(params, false))); obj.push_back(Pair("generatepos", getgeneratepos(params, false))); return obj; @@ -636,7 +636,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); uint256 hash = block.GetHash(); - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) @@ -646,7 +646,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) return "duplicate-inconclusive"; } - CBlockIndex *const pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *const pindexPrev = g_chainman.chainActive.Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; @@ -655,10 +655,10 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) while (true) { AssertLockHeld(cs_main); - assert(pindexPrev && pindexPrev == pnetMan->getChainActive()->chainActive.Tip()); + assert(pindexPrev && pindexPrev == g_chainman.chainActive.Tip()); if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint( - pindexPrev, state, pnetMan->getActivePaymentNetwork(), block.GetHash())) + pindexPrev, state, Params(), block.GetHash())) return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str()); CCoinsViewCache viewNew(pcoinsTip.get()); CBlockIndex indexDummy(block); @@ -688,7 +688,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Eccoind is not connected!"); } - if (pnetMan->getChainActive()->IsInitialBlockDownload()) + if (g_chainman.IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Eccoind is downloading blocks..."); static unsigned int nTransactionsUpdatedLast; @@ -711,7 +711,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier - hashWatchedChain = pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash(); + hashWatchedChain = g_chainman.chainActive.Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } @@ -721,7 +721,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) checktxtime = std::chrono::system_clock::now() + std::chrono::minutes(1); std::unique_lock lock(csBestBlock); - while (pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) + while (g_chainman.chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) { if (cvBlockChange.wait_until(lock, checktxtime) == std::cv_status::timeout) { @@ -744,7 +744,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) static CBlockIndex *pindexPrev; static int64_t nStart; static std::unique_ptr pblocktemplate; - if (pindexPrev != pnetMan->getChainActive()->chainActive.Tip() || + if (pindexPrev != g_chainman.chainActive.Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on @@ -752,7 +752,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - CBlockIndex *pindexPrevNew = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexPrevNew = g_chainman.chainActive.Tip(); nStart = GetTime(); // Create new block @@ -786,7 +786,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) CBlock *pblock = &pblocktemplate->block; // pointer for convenience // Update nTime - UpdateTime(pblock, pnetMan->getActivePaymentNetwork()->GetConsensus(), pindexPrev); + UpdateTime(pblock, Params().GetConsensus(), pindexPrev); pblock->nNonce = 0; UniValue aCaps(UniValue::VARR); @@ -846,7 +846,7 @@ UniValue getblocktemplate(const UniValue ¶ms, bool fHelp) result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue)); result.push_back(Pair("longpollid", - pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast))); + g_chainman.chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast))); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast() + 1)); result.push_back(Pair("mutable", aMutable)); @@ -963,7 +963,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); uint256 hash = block.GetHash(); - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) @@ -973,7 +973,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) return "duplicate-inconclusive"; } - CBlockIndex *const pindexPrev = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *const pindexPrev = g_chainman.chainActive.Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; @@ -982,10 +982,10 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) while (true) { AssertLockHeld(cs_main); - assert(pindexPrev && pindexPrev == pnetMan->getChainActive()->chainActive.Tip()); + assert(pindexPrev && pindexPrev == g_chainman.chainActive.Tip()); if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint( - pindexPrev, state, pnetMan->getActivePaymentNetwork(), block.GetHash())) + pindexPrev, state, Params(), block.GetHash())) return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str()); CCoinsViewCache viewNew(pcoinsTip.get()); CBlockIndex indexDummy(block); @@ -1015,7 +1015,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Eccoind is not connected!"); } - if (pnetMan->getChainActive()->IsInitialBlockDownload()) + if (g_chainman.IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Eccoind is downloading blocks..."); static unsigned int nTransactionsUpdatedLast; @@ -1038,7 +1038,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier - hashWatchedChain = pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash(); + hashWatchedChain = g_chainman.chainActive.Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } @@ -1048,7 +1048,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) checktxtime = std::chrono::system_clock::now() + std::chrono::minutes(1); std::unique_lock lock(csBestBlock); - while (pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) + while (g_chainman.chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) { if (cvBlockChange.wait_until(lock, checktxtime) == std::cv_status::timeout) { @@ -1071,7 +1071,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) static CBlockIndex *pindexPrev; static int64_t nStart; static std::unique_ptr pblocktemplate; - if (pindexPrev != pnetMan->getChainActive()->chainActive.Tip() || + if (pindexPrev != g_chainman.chainActive.Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on @@ -1079,7 +1079,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - CBlockIndex *pindexPrevNew = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexPrevNew = g_chainman.chainActive.Tip(); nStart = GetTime(); // Create new block @@ -1112,7 +1112,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) CBlock *pblock = &pblocktemplate->block; // pointer for convenience // Update nTime - UpdateTime(pblock, pnetMan->getActivePaymentNetwork()->GetConsensus(), pindexPrev); + UpdateTime(pblock, Params().GetConsensus(), pindexPrev); pblock->nNonce = 0; UniValue aCaps(UniValue::VARR); @@ -1172,7 +1172,7 @@ UniValue getposblocktemplate(const UniValue ¶ms, bool fHelp) result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue)); result.push_back(Pair("longpollid", - pnetMan->getChainActive()->chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast))); + g_chainman.chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast))); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast() + 1)); result.push_back(Pair("mutable", aMutable)); @@ -1232,7 +1232,7 @@ UniValue submitblock(const UniValue ¶ms, bool fHelp) uint256 hash = block.GetHash(); bool fBlockPresent = false; { - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hash); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) @@ -1248,7 +1248,7 @@ UniValue submitblock(const UniValue ¶ms, bool fHelp) submitblock_StateCatcher sc(block.GetHash()); RegisterValidationInterface(&sc); const CBlock *spblock(&block); - bool fAccepted = ProcessNewBlock(state, pnetMan->getActivePaymentNetwork(), NULL, spblock, true, NULL); + bool fAccepted = ProcessNewBlock(state, Params(), NULL, spblock, true, NULL); UnregisterValidationInterface(&sc); if (fBlockPresent) { diff --git a/src/rpc/rpcmisc.cpp b/src/rpc/rpcmisc.cpp index 95549441..748c431b 100644 --- a/src/rpc/rpcmisc.cpp +++ b/src/rpc/rpcmisc.cpp @@ -89,14 +89,14 @@ UniValue getinfo(const UniValue ¶ms, bool fHelp) obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint()))); obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake()))); } - obj.push_back(Pair("blocks", (int)pnetMan->getChainActive()->chainActive.Height())); - obj.push_back(Pair("headers", (int)pnetMan->getChainActive()->pindexBestHeader.load()->nHeight)); - obj.push_back(Pair("moneysupply", ValueFromAmount(pnetMan->getChainActive()->chainActive.Tip()->nMoneySupply))); + obj.push_back(Pair("blocks", (int)g_chainman.chainActive.Height())); + obj.push_back(Pair("headers", (int)g_chainman.pindexBestHeader.load()->nHeight)); + obj.push_back(Pair("moneysupply", ValueFromAmount(g_chainman.chainActive.Tip()->nMoneySupply))); obj.push_back(Pair("timeoffset", GetTimeOffset())); obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL))); obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); - obj.push_back(Pair("testnet", pnetMan->getActivePaymentNetwork()->TestnetToBeDeprecatedFieldRPC())); + obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC())); if (pwalletMain) { obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); @@ -371,7 +371,7 @@ UniValue setmocktime(const UniValue ¶ms, bool fHelp) "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n" " Pass 0 to go back to using the system time."); - if (!pnetMan->getActivePaymentNetwork()->MineBlocksOnDemand()) + if (!Params().MineBlocksOnDemand()) throw std::runtime_error("setmocktime for regression testing (-regtest mode) only"); // cs_vNodes is locked and node send/receive times are updated diff --git a/src/rpc/rpcnet.cpp b/src/rpc/rpcnet.cpp index e72dccf8..da44776c 100644 --- a/src/rpc/rpcnet.cpp +++ b/src/rpc/rpcnet.cpp @@ -13,7 +13,7 @@ #include "net/net.h" #include "net/netbase.h" #include "net/protocol.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "sync.h" #include "timedata.h" diff --git a/src/rpc/rpcrawtransaction.cpp b/src/rpc/rpcrawtransaction.cpp index aebfd840..f375190e 100644 --- a/src/rpc/rpcrawtransaction.cpp +++ b/src/rpc/rpcrawtransaction.cpp @@ -103,13 +103,13 @@ void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry) if (!hashBlock.IsNull()) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hashBlock); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hashBlock); if (pindex) { - if (pnetMan->getChainActive()->chainActive.Contains(pindex)) + if (g_chainman.chainActive.Contains(pindex)) { entry.push_back( - Pair("confirmations", 1 + pnetMan->getChainActive()->chainActive.Height() - pindex->nHeight)); + Pair("confirmations", 1 + g_chainman.chainActive.Height() - pindex->nHeight)); entry.push_back(Pair("time", pindex->GetBlockTime())); entry.push_back(Pair("blocktime", pindex->GetBlockTime())); } @@ -196,7 +196,7 @@ UniValue getrawtransaction(const UniValue ¶ms, bool fHelp) CTransaction tx; uint256 hashBlock; - if (!GetTransaction(hash, tx, pnetMan->getActivePaymentNetwork()->GetConsensus(), hashBlock, true)) + if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); std::string strHex = EncodeHexTx(tx); @@ -252,38 +252,38 @@ UniValue gettxoutproof(const UniValue ¶ms, bool fHelp) uint256 hashBlock; if (params.size() > 1) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); hashBlock = uint256S(params[1].get_str()); - if (!pnetMan->getChainActive()->mapBlockIndex.count(hashBlock)) + if (!g_chainman.mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); - pblockindex = pnetMan->getChainActive()->mapBlockIndex[hashBlock]; + pblockindex = g_chainman.mapBlockIndex[hashBlock]; } else { LOCK(cs_main); CoinAccessor coin(*pcoinsTip, oneTxid); if (coin && !coin->IsSpent() && coin->nHeight > 0 && - coin->nHeight <= (unsigned int)pnetMan->getChainActive()->chainActive.Height()) + coin->nHeight <= (unsigned int)g_chainman.chainActive.Height()) { - pblockindex = pnetMan->getChainActive()->chainActive[coin->nHeight]; + pblockindex = g_chainman.chainActive[coin->nHeight]; } } if (pblockindex == NULL) { CTransaction tx; - if (!GetTransaction(oneTxid, tx, pnetMan->getActivePaymentNetwork()->GetConsensus(), hashBlock, false) || + if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - if (!pnetMan->getChainActive()->mapBlockIndex.count(hashBlock)) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + if (!g_chainman.mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); - pblockindex = pnetMan->getChainActive()->mapBlockIndex[hashBlock]; + pblockindex = g_chainman.mapBlockIndex[hashBlock]; } CBlock block; { - if (!ReadBlockFromDisk(block, pblockindex, pnetMan->getActivePaymentNetwork()->GetConsensus())) + if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); } @@ -330,11 +330,11 @@ UniValue verifytxoutproof(const UniValue ¶ms, bool fHelp) if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot) return res; - auto *pindex = pnetMan->getChainActive()->LookupBlockIndex(merkleBlock.header.GetHash()); + auto *pindex = g_chainman.LookupBlockIndex(merkleBlock.header.GetHash()); { LOCK(cs_main); - if (!pindex || !pnetMan->getChainActive()->chainActive.Contains(pindex)) + if (!pindex || !g_chainman.chainActive.Contains(pindex)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } diff --git a/src/rpc/rpcwallet.cpp b/src/rpc/rpcwallet.cpp index 6cac4795..7248608e 100644 --- a/src/rpc/rpcwallet.cpp +++ b/src/rpc/rpcwallet.cpp @@ -67,10 +67,10 @@ void WalletTxToJSON(const CWalletTx &wtx, UniValue &entry) } if (confirms > 0) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); - entry.push_back(Pair("blocktime", pnetMan->getChainActive()->mapBlockIndex[wtx.hashBlock]->GetBlockTime())); + entry.push_back(Pair("blocktime", g_chainman.mapBlockIndex[wtx.hashBlock]->GetBlockTime())); } else { @@ -1090,7 +1090,7 @@ UniValue listsinceblock(const UniValue ¶ms, bool fHelp) uint256 blockId; blockId.SetHex(params[0].get_str()); - pindex = pnetMan->getChainActive()->LookupBlockIndex(blockId); + pindex = g_chainman.LookupBlockIndex(blockId); } if (params.size() > 1) @@ -1105,7 +1105,7 @@ UniValue listsinceblock(const UniValue ¶ms, bool fHelp) if (params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; - int depth = pindex ? (1 + pnetMan->getChainActive()->chainActive.Height() - pindex->nHeight) : -1; + int depth = pindex ? (1 + g_chainman.chainActive.Height() - pindex->nHeight) : -1; UniValue transactions(UniValue::VARR); @@ -1119,7 +1119,7 @@ UniValue listsinceblock(const UniValue ¶ms, bool fHelp) } CBlockIndex *pblockLast = - pnetMan->getChainActive()->chainActive[pnetMan->getChainActive()->chainActive.Height() + 1 - target_confirms]; + g_chainman.chainActive[g_chainman.chainActive.Height() + 1 - target_confirms]; uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256(); UniValue ret(UniValue::VOBJ); diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 721efeca..07261451 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -972,7 +972,7 @@ bool EvalScript(std::vector > &stack, // TODO: for backwards compatability, this should be implemented in a different way but for now it // will do - if (pnetMan->getChainActive()->chainActive.Tip()->nHeight > 1600000) + if (g_chainman.chainActive.Tip()->nHeight > 1600000) { if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) @@ -1052,7 +1052,7 @@ bool EvalScript(std::vector > &stack, // See the script_(in)valid tests for details. // TODO: for backwards compatability, this should be implemented in a different way but for now // it will do - if (pnetMan->getChainActive()->chainActive.Tip()->nHeight > 1600000) + if (g_chainman.chainActive.Tip()->nHeight > 1600000) { if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) diff --git a/src/test/base58_tests.cpp b/src/test/base58_tests.cpp index b0cd6945..259dbfec 100644 --- a/src/test/base58_tests.cpp +++ b/src/test/base58_tests.cpp @@ -10,7 +10,7 @@ #include "data/base58_keys_valid.json.h" #include "key.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "script/script.h" #include "test/test_bitcoin.h" #include "uint256.h" @@ -23,7 +23,7 @@ #include extern UniValue read_json(const std::string &jsondata); -extern CNetworkManager *pnetMan; + BOOST_FIXTURE_TEST_SUITE(base58_tests, BasicTestingSetup) // Goal: test low-level base58 encoding functionality diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp index ea77eed9..6634cfba 100644 --- a/src/test/net_tests.cpp +++ b/src/test/net_tests.cpp @@ -62,7 +62,7 @@ class CAddrManCorrupted : public CAddrManSerializationMock CDataStream AddrmanToStream(CAddrManSerializationMock &_addrman) { CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION); - ssPeersIn << FLATDATA(pnetMan->getActivePaymentNetwork()->MessageStart()); + ssPeersIn << FLATDATA(Params().MessageStart()); ssPeersIn << _addrman; std::string str = ssPeersIn.str(); std::vector vchData(str.begin(), str.end()); diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp index 2f42f5e7..cc7a6425 100644 --- a/src/test/test_bitcoin.cpp +++ b/src/test/test_bitcoin.cpp @@ -9,6 +9,8 @@ #include "blockgeneration/blockgeneration.h" +#include "chain/chainman.h" +#include "chain/chainparams.h" #include "consensus/consensus.h" #include "consensus/validation.h" #include "crypto/sha256.h" @@ -39,9 +41,8 @@ BasicTestingSetup::BasicTestingSetup(const std::string &chainName) SetupNetworking(); g_logger->fPrintToDebugLog = false; // don't want to write to debug.log file fCheckBlockIndex = true; - pnetMan = new CNetworkManager(); pwallet = new CWallet("walletFile"); - pnetMan->SetParams(chainName); + CheckAndSetParams(chainName); // Deterministic randomness for tests. g_connman = std::make_unique(0x1337, 0x1337); } @@ -51,7 +52,7 @@ TestingSetup::TestingSetup(const std::string &chainName) : BasicTestingSetup(cha { // Ideally we'd move all the RPC tests to the functional testing framework // instead of unit tests, but for now we need these here. - const CNetworkTemplate &chainparams = pnetMan->getActivePaymentNetwork(); + const CChainParams &chainparams = Params(); // RegisterAllCoreRPCCommands(tableRPC); ClearDatadirCache(); pathTemp = GetTempPathTest() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); @@ -59,7 +60,7 @@ TestingSetup::TestingSetup(const std::string &chainName) : BasicTestingSetup(cha pblocktree.reset(new CBlockTreeDB(1 << 20, true)); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview)); - bool worked = pnetMan->getChainActive()->InitBlockIndex(chainparams); + bool worked = g_chainman.InitBlockIndex(chainparams); assert(worked); RegisterNodeSignals(GetNodeSignals()); } @@ -69,7 +70,7 @@ TestingSetup::~TestingSetup() UnregisterNodeSignals(GetNodeSignals()); threadGroup.interrupt_all(); threadGroup.join_all(); - pnetMan->getChainActive()->UnloadBlockIndex(); + g_chainman.UnloadBlockIndex(); pcoinsTip.reset(); pcoinsdbview = nullptr; pblocktree.reset(); @@ -106,13 +107,13 @@ CBlock TestChain100Setup::CreateAndProcessBlock(const std::vectorvtx.push_back(tx); // IncrementExtraNonce creates a valid coinbase and merkleRoot unsigned int extraNonce = 0; - IncrementExtraNonce(pblock, pnetMan->getChainActive()->chainActive.Tip(), extraNonce); + IncrementExtraNonce(pblock, g_chainman.chainActive.Tip(), extraNonce); - while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, pnetMan->getActivePaymentNetwork()->GetConsensus())) + while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) ++pblock->nNonce; CValidationState state; - ProcessNewBlock(state, pnetMan->getActivePaymentNetwork(), NULL, pblock, true, NULL); + ProcessNewBlock(state, Params(), NULL, pblock, true, NULL); CBlock result = *pblock; pblocktemplate.reset(); diff --git a/src/test/test_bitcoin.h b/src/test/test_bitcoin.h index 2cc0f360..7da5b0f2 100644 --- a/src/test/test_bitcoin.h +++ b/src/test/test_bitcoin.h @@ -3,7 +3,7 @@ #include "fs.h" #include "key.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "pubkey.h" #include "txdb.h" #include "txmempool.h" @@ -13,7 +13,7 @@ class CConnman; class CNode; -extern CNetworkManager *pnetman; + /** Basic testing setup. * This just configures logging and chain parameters. diff --git a/src/txdb.cpp b/src/txdb.cpp index 92b27747..36dea9bb 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -14,7 +14,7 @@ #include "crypto/hash.h" #include "init.h" #include "main.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" #include "pow.h" #include "uint256.h" @@ -274,8 +274,8 @@ bool CBlockTreeDB::LoadBlockIndexGuts() if (pcursor->GetValue(diskindex)) { // Construct block index object - CBlockIndex *pindexNew = pnetMan->getChainActive()->InsertBlockIndex(diskindex.hashBlock); - pindexNew->pprev = pnetMan->getChainActive()->InsertBlockIndex(diskindex.hashPrev); + CBlockIndex *pindexNew = g_chainman.InsertBlockIndex(diskindex.hashBlock); + pindexNew->pprev = g_chainman.InsertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; diff --git a/src/util/util.cpp b/src/util/util.cpp index 2c9435d2..2174be1c 100644 --- a/src/util/util.cpp +++ b/src/util/util.cpp @@ -9,7 +9,7 @@ #include "args.h" #include "init.h" -#include "networks/netman.h" +#include "chain/chainparams.h" #include "random.h" #include "serialize.h" #include "sync.h" @@ -247,7 +247,7 @@ const fs::path &GetDataDir(bool fNetSpecific) } if (fNetSpecific) { - path /= pnetMan->getActivePaymentNetwork()->DataDir(); + path /= Params().NetworkDataDir(); } fs::create_directories(path); diff --git a/src/verifydb.cpp b/src/verifydb.cpp index 60f4e65c..fe6a3105 100644 --- a/src/verifydb.cpp +++ b/src/verifydb.cpp @@ -16,26 +16,26 @@ CVerifyDB::CVerifyDB() {} CVerifyDB::~CVerifyDB() {} -bool CVerifyDB::VerifyDB(const CNetworkTemplate &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth) +bool CVerifyDB::VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth) { - if (pnetMan->getChainActive()->chainActive.Tip() == nullptr || - pnetMan->getChainActive()->chainActive.Tip()->pprev == nullptr) + if (g_chainman.chainActive.Tip() == nullptr || + g_chainman.chainActive.Tip()->pprev == nullptr) return true; // Verify blocks in the best chain if (nCheckDepth <= 0) nCheckDepth = 1000000000; // suffices until the year 19000 - if (nCheckDepth > pnetMan->getChainActive()->chainActive.Height()) - nCheckDepth = pnetMan->getChainActive()->chainActive.Height(); + if (nCheckDepth > g_chainman.chainActive.Height()) + nCheckDepth = g_chainman.chainActive.Height(); nCheckLevel = std::max(0, std::min(4, nCheckLevel)); LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); CCoinsViewCache coins(coinsview); - CBlockIndex *pindexState = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexState = g_chainman.chainActive.Tip(); CBlockIndex *pindexFailure = nullptr; int nGoodTransactions = 0; CValidationState state; LOCK(cs_main); - for (CBlockIndex *pindex = pnetMan->getChainActive()->chainActive.Tip(); pindex && pindex->pprev; + for (CBlockIndex *pindex = g_chainman.chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { if (shutdown_threads.load()) @@ -43,7 +43,7 @@ bool CVerifyDB::VerifyDB(const CNetworkTemplate &chainparams, CCoinsView *coinsv LogPrintf("VerifyDB(): Shutdown requested. Exiting.\n"); return false; } - if (pindex->nHeight < pnetMan->getChainActive()->chainActive.Height() - nCheckDepth) + if (pindex->nHeight < g_chainman.chainActive.Height() - nCheckDepth) break; CBlock block; // check level 0: read from disk @@ -95,20 +95,20 @@ bool CVerifyDB::VerifyDB(const CNetworkTemplate &chainparams, CCoinsView *coinsv if (pindexFailure) return error( "VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", - pnetMan->getChainActive()->chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); + g_chainman.chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { CBlockIndex *pindex = pindexState; - while (pindex != pnetMan->getChainActive()->chainActive.Tip()) + while (pindex != g_chainman.chainActive.Tip()) { if (shutdown_threads.load()) { LogPrintf("VerifyDB(): [lower] Shutdown requested. Exiting.\n"); return false; } - pindex = pnetMan->getChainActive()->chainActive.Next(pindex); + pindex = g_chainman.chainActive.Next(pindex); CBlock block; { if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) @@ -122,7 +122,7 @@ bool CVerifyDB::VerifyDB(const CNetworkTemplate &chainparams, CCoinsView *coinsv } LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", - pnetMan->getChainActive()->chainActive.Height() - pindexState->nHeight, nGoodTransactions); + g_chainman.chainActive.Height() - pindexState->nHeight, nGoodTransactions); return true; } diff --git a/src/verifydb.h b/src/verifydb.h index 5d3e745c..400cdceb 100644 --- a/src/verifydb.h +++ b/src/verifydb.h @@ -9,7 +9,7 @@ #define VERIFYDB_H #include "coins.h" -#include "networks/networktemplate.h" +#include "chain/chainparams.h" /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */ class CVerifyDB @@ -17,7 +17,7 @@ class CVerifyDB public: CVerifyDB(); ~CVerifyDB(); - bool VerifyDB(const CNetworkTemplate &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth); + bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth); }; #endif // VERIFYDB_H diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index a8f27d4c..9683cbcb 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -674,8 +674,8 @@ bool CWallet::AddToWallet(const CWalletTx &wtxIn, bool fFromLoadWallet, CWalletD wtx.nTimeSmart = wtx.nTimeReceived; if (!wtxIn.hashUnset()) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - if (pnetMan->getChainActive()->mapBlockIndex.count(wtxIn.hashBlock)) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + if (g_chainman.mapBlockIndex.count(wtxIn.hashBlock)) { int64_t latestNow = wtx.nTimeReceived; int64_t latestEntry = 0; @@ -705,7 +705,7 @@ bool CWallet::AddToWallet(const CWalletTx &wtxIn, bool fFromLoadWallet, CWalletD } } - int64_t blocktime = pnetMan->getChainActive()->mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); + int64_t blocktime = g_chainman.mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else @@ -888,13 +888,13 @@ void CWallet::MarkConflicted(const uint256 &hashBlock, const uint256 &hashTx) { LOCK(cs_wallet); int conflictconfirms = 0; - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hashBlock); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hashBlock); if (pindex) { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - if (pnetMan->getChainActive()->chainActive.Contains(pindex)) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + if (g_chainman.chainActive.Contains(pindex)) { - conflictconfirms = -(pnetMan->getChainActive()->chainActive.Height() - pindex->nHeight + 1); + conflictconfirms = -(g_chainman.chainActive.Height() - pindex->nHeight + 1); } } // If number of conflict confirms cannot be determined, this means @@ -1233,7 +1233,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate) int ret = 0; int64_t nNow = GetTime(); CBlockIndex *pindex = pindexStart; - int nEndHeight = pnetMan->getChainActive()->chainActive.Tip()->nHeight; + int nEndHeight = g_chainman.chainActive.Tip()->nHeight; { LOCK(cs_wallet); @@ -1241,14 +1241,14 @@ int CWallet::ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate) // our wallet birthday (as adjusted for block time variability) while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) { - pindex = pnetMan->getChainActive()->chainActive.Next(pindex); + pindex = g_chainman.chainActive.Next(pindex); } GetMainSignals().SystemMessage("RESCAN: STARTED"); while (pindex) { CBlock block; { - ReadBlockFromDisk(block, pindex, pnetMan->getActivePaymentNetwork()->GetConsensus()); + ReadBlockFromDisk(block, pindex, Params().GetConsensus()); } for (auto &ptx : block.vtx) { @@ -1257,7 +1257,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate) ret++; } } - pindex = pnetMan->getChainActive()->chainActive.Next(pindex); + pindex = g_chainman.chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); @@ -2129,7 +2129,7 @@ bool CWallet::CreateTransaction(const std::vector &vecSend, // enough, that fee sniping isn't a problem yet, but by implementing a fix // now we ensure code won't be written that makes assumptions about // nLockTime that preclude a fix later. - txNew.nLockTime = pnetMan->getChainActive()->chainActive.Height(); + txNew.nLockTime = g_chainman.chainActive.Height(); // Secondly occasionally randomly pick a nLockTime even further back, so // that transactions that are delayed after signing for whatever reason, @@ -2138,7 +2138,7 @@ bool CWallet::CreateTransaction(const std::vector &vecSend, if (GetRandInt(10) == 0) txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100)); - assert(txNew.nLockTime <= (unsigned int)(pnetMan->getChainActive()->chainActive.Height())); + assert(txNew.nLockTime <= (unsigned int)(g_chainman.chainActive.Height())); assert(txNew.nLockTime < LOCKTIME_THRESHOLD); { @@ -2996,7 +2996,7 @@ void CWallet::GetKeyBirthTimes(std::map &mapKeyBirth) const // map in which we'll infer heights of other keys // the tip can be reorganised; use a 144-block safety margin CBlockIndex *pindexMax = - pnetMan->getChainActive()->chainActive[std::max(0, pnetMan->getChainActive()->chainActive.Height() - 144)]; + g_chainman.chainActive[std::max(0, g_chainman.chainActive.Height() - 144)]; std::map mapKeyFirstBlock; std::set setKeys; GetKeys(setKeys); @@ -3017,8 +3017,8 @@ void CWallet::GetKeyBirthTimes(std::map &mapKeyBirth) const { // iterate over all wallet transactions... const CWalletTx &wtx = (*it).second; - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(wtx.hashBlock); - if (pindex && pnetMan->getChainActive()->chainActive.Contains(pindex)) + CBlockIndex *pindex = g_chainman.LookupBlockIndex(wtx.hashBlock); + if (pindex && g_chainman.chainActive.Contains(pindex)) { // ... which are already in a block int nHeight = pindex->nHeight; @@ -3078,13 +3078,13 @@ int CMerkleTx::SetMerkleBranch(const CBlock &block) } // Is the tx in a block that's in the main chain - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - const CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hashBlock); - if (!pindex || !pnetMan->getChainActive()->chainActive.Contains(pindex)) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + const CBlockIndex *pindex = g_chainman.LookupBlockIndex(hashBlock); + if (!pindex || !g_chainman.chainActive.Contains(pindex)) { return 0; } - return pnetMan->getChainActive()->chainActive.Height() - pindex->nHeight + 1; + return g_chainman.chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(const CBlockIndex *&pindexRet) const @@ -3094,16 +3094,16 @@ int CMerkleTx::GetDepthInMainChain(const CBlockIndex *&pindexRet) const return 0; } // Find the block it claims to be in - CBlockIndex *pindex = pnetMan->getChainActive()->LookupBlockIndex(hashBlock); + CBlockIndex *pindex = g_chainman.LookupBlockIndex(hashBlock); { - RECURSIVEREADLOCK(pnetMan->getChainActive()->cs_mapBlockIndex); - if (!pindex || !pnetMan->getChainActive()->chainActive.Contains(pindex)) + RECURSIVEREADLOCK(g_chainman.cs_mapBlockIndex); + if (!pindex || !g_chainman.chainActive.Contains(pindex)) { return 0; } } pindexRet = pindex; - return ((nIndex == -1) ? (-1) : 1) * (pnetMan->getChainActive()->chainActive.Height() - pindex->nHeight + 1); + return ((nIndex == -1) ? (-1) : 1) * (g_chainman.chainActive.Height() - pindex->nHeight + 1); } int CMerkleTx::GetBlocksToMaturity() const @@ -3255,7 +3255,7 @@ bool CWallet::CreateCoinStake(const CKeyStore &keystore, // The following split & combine thresholds are important to security // Should not be adjusted if you don't understand the consequences static unsigned int nStakeSplitAge = (60 * 60 * 24 * 30); - const CBlockIndex *pIndex0 = GetLastBlockIndex(pnetMan->getChainActive()->chainActive.Tip(), false); + const CBlockIndex *pIndex0 = GetLastBlockIndex(g_chainman.chainActive.Tip(), false); int64_t nCombineThreshold = 0; if (pIndex0->pprev) nCombineThreshold = @@ -3303,7 +3303,7 @@ bool CWallet::CreateCoinStake(const CKeyStore &keystore, CBlock block; { CDiskBlockPos blockPos(txindex.nFile, txindex.nPos); - if (!ReadBlockFromDisk(block, blockPos, pnetMan->getActivePaymentNetwork()->GetConsensus())) + if (!ReadBlockFromDisk(block, blockPos, Params().GetConsensus())) continue; } @@ -3311,7 +3311,7 @@ bool CWallet::CreateCoinStake(const CKeyStore &keystore, // LogPrintf(">> block.GetBlockTime() = %"PRI64d", nStakeMinAge = %d, txNew.nTime = %d\n", block.GetBlockTime(), // nStakeMinAge,txNew.nTime); - if (block.GetBlockTime() + pnetMan->getActivePaymentNetwork()->getStakeMinAge() > + if (block.GetBlockTime() + Params().getStakeMinAge() > txNew.nTime - nMaxStakeSearchInterval) continue; // only count coins meeting min age requirement @@ -3322,7 +3322,7 @@ bool CWallet::CreateCoinStake(const CKeyStore &keystore, uint256 hashProofOfStake; hashProofOfStake.SetNull(); COutPoint prevoutStake = COutPoint(pcoin.first->tx->GetHash(), pcoin.second); - if (CheckStakeKernelHash(pnetMan->getChainActive()->chainActive.Tip()->nHeight + 1, block, + if (CheckStakeKernelHash(g_chainman.chainActive.Tip()->nHeight + 1, block, txindex.nTxOffset, *(pcoin.first->tx), prevoutStake, txNew.nTime, hashProofOfStake)) { // Found a kernel @@ -3406,7 +3406,7 @@ bool CWallet::CreateCoinStake(const CKeyStore &keystore, // Do not add input that is still too young /// using stake max age here isnt a bug, its a feature i swear /// TODO fix that - 2017/10/29 - if (pcoin.first->tx->nTime + pnetMan->getActivePaymentNetwork()->getStakeMaxAge() > txNew.nTime) + if (pcoin.first->tx->nTime + Params().getStakeMaxAge() > txNew.nTime) continue; txNew.vin.push_back(CTxIn(pcoin.first->tx->GetHash(), pcoin.second)); nCredit += pcoin.first->tx->vout[pcoin.second].nValue; @@ -3416,7 +3416,7 @@ bool CWallet::CreateCoinStake(const CKeyStore &keystore, // Calculate coin age reward { uint64_t nCoinAge; - const CBlockIndex *_pIndex0 = GetLastBlockIndex(pnetMan->getChainActive()->chainActive.Tip(), false); + const CBlockIndex *_pIndex0 = GetLastBlockIndex(g_chainman.chainActive.Tip(), false); if (!txNew.GetCoinAge(nCoinAge)) { @@ -3549,31 +3549,31 @@ bool CWallet::InitLoadWallet() return UIError("Cannot write default address \n"); } - walletInstance->SetBestChain(pnetMan->getChainActive()->chainActive.GetLocator()); + walletInstance->SetBestChain(g_chainman.chainActive.GetLocator()); } LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart); RegisterValidationInterface(walletInstance); - CBlockIndex *pindexRescan = pnetMan->getChainActive()->chainActive.Tip(); + CBlockIndex *pindexRescan = g_chainman.chainActive.Tip(); if (gArgs.GetBoolArg("-rescan", false)) - pindexRescan = pnetMan->getChainActive()->chainActive.Genesis(); + pindexRescan = g_chainman.chainActive.Genesis(); else { CWalletDB walletdb(walletFile); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) pindexRescan = - pnetMan->getChainActive()->FindForkInGlobalIndex(pnetMan->getChainActive()->chainActive, locator); + g_chainman.FindForkInGlobalIndex(g_chainman.chainActive, locator); else - pindexRescan = pnetMan->getChainActive()->chainActive.Genesis(); + pindexRescan = g_chainman.chainActive.Genesis(); } - if (pnetMan->getChainActive()->chainActive.Tip() && pnetMan->getChainActive()->chainActive.Tip() != pindexRescan) + if (g_chainman.chainActive.Tip() && g_chainman.chainActive.Tip() != pindexRescan) { LogPrintf("Rescanning last %i blocks (from block %i)...\n", - pnetMan->getChainActive()->chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); + g_chainman.chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); walletInstance->ScanForWalletTransactions(pindexRescan, true); LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); - walletInstance->SetBestChain(pnetMan->getChainActive()->chainActive.GetLocator()); + walletInstance->SetBestChain(g_chainman.chainActive.GetLocator()); nWalletDBUpdated++; // Restore wallet transaction metadata after -zapwallettxes=1 diff --git a/src/zmq/zmqpublishnotifier.cpp b/src/zmq/zmqpublishnotifier.cpp index a4d38468..eab1e62a 100644 --- a/src/zmq/zmqpublishnotifier.cpp +++ b/src/zmq/zmqpublishnotifier.cpp @@ -147,7 +147,7 @@ bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex) { LogPrint("zmq", "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex()); - const Consensus::Params &consensusParams = pnetMan->getActivePaymentNetwork()->GetConsensus(); + const Consensus::Params &consensusParams = Params().GetConsensus(); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); { CBlock block;