From 4b729ec5776abe84c21feb310bb0dc9a99e5ce2b Mon Sep 17 00:00:00 2001 From: miketout Date: Fri, 28 Sep 2018 01:38:14 -0700 Subject: [PATCH] Changes for most chain power rule --- src/cc/{CC made easy => CC made easy.md} | 0 src/cc/CCutils.cpp | 10 +- src/cc/betprotocol.cpp | 2 +- src/cc/disputepayout.cpp | 2 +- src/cc/eval.cpp | 2 +- src/chain.cpp | 68 +++- src/chain.h | 128 +++++- src/chainparams.cpp | 9 +- src/consensus/params.h | 2 + src/crosschain.cpp | 12 +- src/gtest/test_checkblock.cpp | 2 +- src/gtest/test_pow.cpp | 4 +- src/gtest/test_rpc.cpp | 2 +- src/init.cpp | 2 +- src/komodo.h | 32 +- src/komodo_bitcoind.h | 60 +-- src/komodo_gateway.h | 2 +- src/komodo_globals.h | 3 + src/komodo_jumblr.h | 2 +- src/komodo_pax.h | 4 +- src/komodo_utils.h | 10 +- src/main.cpp | 379 +++++++++--------- src/metrics.cpp | 2 +- src/miner.cpp | 64 +-- src/pow.cpp | 41 +- src/pow.h | 3 +- src/primitives/block.cpp | 6 +- src/primitives/block.h | 1 + src/primitives/transaction.cpp | 1 + src/rpc/blockchain.cpp | 57 +-- src/rpc/crosschain.cpp | 2 +- src/rpc/mining.cpp | 20 +- src/rpc/misc.cpp | 4 +- src/rpc/rawtransaction.cpp | 10 +- src/test-komodo/test_eval_bet.cpp | 2 +- src/test-komodo/test_eval_notarisation.cpp | 2 +- src/test/alert_tests.cpp | 2 +- src/test/miner_tests.cpp | 12 +- src/test/pow_tests.cpp | 6 +- src/test/rpc_wallet_tests.cpp | 2 +- src/test/skiplist_tests.cpp | 20 +- src/txdb.cpp | 8 +- src/txmempool.cpp | 2 +- src/wallet-utility.cpp | 2 + .../asyncrpcoperation_mergetoaddress.cpp | 2 +- src/wallet/asyncrpcoperation_sendmany.cpp | 2 +- src/wallet/gtest/test_wallet.cpp | 16 +- src/wallet/rpcdump.cpp | 2 +- src/wallet/rpcwallet.cpp | 26 +- src/wallet/wallet.cpp | 48 +-- src/zcbenchmarks.cpp | 8 +- 51 files changed, 666 insertions(+), 444 deletions(-) rename src/cc/{CC made easy => CC made easy.md} (100%) diff --git a/src/cc/CC made easy b/src/cc/CC made easy.md similarity index 100% rename from src/cc/CC made easy rename to src/cc/CC made easy.md diff --git a/src/cc/CCutils.cpp b/src/cc/CCutils.cpp index a91d6ffdd..5b7e01304 100644 --- a/src/cc/CCutils.cpp +++ b/src/cc/CCutils.cpp @@ -385,19 +385,19 @@ int64_t CCduration(int32_t &numblocks,uint256 txid) fprintf(stderr,"CCduration no hashBlock for txid %s\n",uint256_str(str,txid)); return(0); } - else if ( (pindex= mapBlockIndex[hashBlock]) == 0 || (txtime= pindex->nTime) == 0 || (txheight= pindex->nHeight) <= 0 ) + else if ( (pindex= mapBlockIndex[hashBlock]) == 0 || (txtime= pindex->nTime) == 0 || (txheight= pindex->GetHeight()) <= 0 ) { fprintf(stderr,"CCduration no txtime %u or txheight.%d %p for txid %s\n",txtime,txheight,pindex,uint256_str(str,txid)); return(0); } - else if ( (pindex= chainActive.LastTip()) == 0 || pindex->nTime < txtime || pindex->nHeight <= txheight ) + else if ( (pindex= chainActive.LastTip()) == 0 || pindex->nTime < txtime || pindex->GetHeight() <= txheight ) { - fprintf(stderr,"CCduration backwards timestamps %u %u for txid %s hts.(%d %d)\n",(uint32_t)pindex->nTime,txtime,uint256_str(str,txid),txheight,(int32_t)pindex->nHeight); + fprintf(stderr,"CCduration backwards timestamps %u %u for txid %s hts.(%d %d)\n",(uint32_t)pindex->nTime,txtime,uint256_str(str,txid),txheight,(int32_t)pindex->GetHeight()); return(0); } - numblocks = (pindex->nHeight - txheight); + numblocks = (pindex->GetHeight() - txheight); duration = (pindex->nTime - txtime); - fprintf(stderr,"duration %d (%u - %u) numblocks %d (%d - %d)\n",(int32_t)duration,(uint32_t)pindex->nTime,txtime,numblocks,pindex->nHeight,txheight); + fprintf(stderr,"duration %d (%u - %u) numblocks %d (%d - %d)\n",(int32_t)duration,(uint32_t)pindex->nTime,txtime,numblocks,pindex->GetHeight(),txheight); return(duration); } diff --git a/src/cc/betprotocol.cpp b/src/cc/betprotocol.cpp index a6ccfc972..41a05a797 100644 --- a/src/cc/betprotocol.cpp +++ b/src/cc/betprotocol.cpp @@ -263,7 +263,7 @@ bool Eval::DisputePayout(AppVM &vm, std::vector params, const CTransact if (!GetTxConfirmed(disputeTx.vin[0].prevout.hash, sessionTx, sessionBlock)) return Error("couldnt-get-parent"); - if (GetCurrentHeight() < sessionBlock.nHeight + waitBlocks) + if (GetCurrentHeight() < sessionBlock.GetHeight() + waitBlocks) return Invalid("dispute-too-soon"); // Not yet } diff --git a/src/cc/disputepayout.cpp b/src/cc/disputepayout.cpp index 610342274..1271b0da5 100644 --- a/src/cc/disputepayout.cpp +++ b/src/cc/disputepayout.cpp @@ -46,7 +46,7 @@ bool Eval::DisputePayout(AppVM &vm, std::vector params, const CTransact if (!GetTxConfirmed(disputeTx.vin[0].prevout.hash, sessionTx, sessionBlock)) return Error("couldnt-get-parent"); - if (GetCurrentHeight() < sessionBlock.nHeight + waitBlocks) + if (GetCurrentHeight() < sessionBlock.GetHeight() + waitBlocks) return Invalid("dispute-too-soon"); // Not yet } diff --git a/src/cc/eval.cpp b/src/cc/eval.cpp index ec6c6b1e0..1731436af 100644 --- a/src/cc/eval.cpp +++ b/src/cc/eval.cpp @@ -191,7 +191,7 @@ bool Eval::GetNotarisationData(const uint256 notaryHash, NotarisationData &data) CTransaction notarisationTx; CBlockIndex block; if (!GetTxConfirmed(notaryHash, notarisationTx, block)) return false; - if (!CheckNotaryInputs(notarisationTx, block.nHeight, block.nTime)) return false; + if (!CheckNotaryInputs(notarisationTx, block.GetHeight(), block.nTime)) return false; if (!ParseNotarisationOpReturn(notarisationTx, data)) return false; return true; } diff --git a/src/chain.cpp b/src/chain.cpp index 8a5a42777..0d4ac7f2a 100644 --- a/src/chain.cpp +++ b/src/chain.cpp @@ -16,9 +16,9 @@ void CChain::SetTip(CBlockIndex *pindex) { vChain.clear(); return; } - vChain.resize(pindex->nHeight + 1); - while (pindex && vChain[pindex->nHeight] != pindex) { - vChain[pindex->nHeight] = pindex; + vChain.resize(pindex->GetHeight() + 1); + while (pindex && vChain[pindex->GetHeight()] != pindex) { + vChain[pindex->GetHeight()] = pindex; pindex = pindex->pprev; } } @@ -33,10 +33,10 @@ CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. - if (pindex->nHeight == 0) + if (pindex->GetHeight() == 0) break; // Exponentially larger steps back, plus the genesis block. - int nHeight = std::max(pindex->nHeight - nStep, 0); + int nHeight = std::max(pindex->GetHeight() - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; @@ -54,13 +54,63 @@ CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if ( pindex == 0 ) return(0); - if (pindex->nHeight > Height()) + if (pindex->GetHeight() > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } +CChainPower::CChainPower(CBlockIndex *pblockIndex) +{ + nHeight = pblockIndex->GetHeight(); + chainStake = arith_uint256(0); + chainWork = arith_uint256(0); +} + +CChainPower::CChainPower(CBlockIndex *pblockIndex, const arith_uint256 &stake, const arith_uint256 &work) +{ + nHeight = pblockIndex->GetHeight(); + chainStake = stake; + chainWork = work; +} + +bool operator==(const CChainPower &p1, const CChainPower &p2) +{ + arith_uint256 bigZero = arith_uint256(0); + arith_uint256 workDivisor = p1.chainWork > p2.chainWork ? p1.chainWork : (p2.chainWork != bigZero ? p2.chainWork : 1); + arith_uint256 stakeDivisor = p1.chainStake > p2.chainStake ? p1.chainStake : (p2.chainStake != bigZero ? p2.chainStake : 1); + + // use up 16 bits for precision + return ((p1.chainWork << 16) / workDivisor + (p1.chainStake << 16) / stakeDivisor) == + ((p2.chainWork << 16) / workDivisor + (p2.chainStake << 16) / stakeDivisor); +} + +bool operator<(const CChainPower &p1, const CChainPower &p2) +{ + arith_uint256 bigZero = arith_uint256(0); + arith_uint256 workDivisor = p1.chainWork > p2.chainWork ? p1.chainWork : (p2.chainWork != bigZero ? p2.chainWork : 1); + arith_uint256 stakeDivisor = p1.chainStake > p2.chainStake ? p1.chainStake : (p2.chainStake != bigZero ? p2.chainStake : 1); + + // use up 16 bits for precision + return ((p1.chainWork << 16) / workDivisor + (p1.chainStake << 16) / stakeDivisor) < + ((p2.chainWork << 16) / workDivisor + (p2.chainStake << 16) / stakeDivisor); +} + +bool operator<=(const CChainPower &p1, const CChainPower &p2) +{ + arith_uint256 bigZero = arith_uint256(0); + arith_uint256 workDivisor = p1.chainWork > p2.chainWork ? p1.chainWork : (p2.chainWork != bigZero ? p2.chainWork : 1); + arith_uint256 stakeDivisor = p1.chainStake > p2.chainStake ? p1.chainStake : (p2.chainStake != bigZero ? p2.chainStake : 1); + + // use up 16 bits for precision + return ((p1.chainWork << 16) / workDivisor + (p1.chainStake << 16) / stakeDivisor) <= + ((p2.chainWork << 16) / workDivisor + (p2.chainStake << 16) / stakeDivisor); +} + + + + /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } @@ -77,11 +127,11 @@ int static inline GetSkipHeight(int height) { CBlockIndex* CBlockIndex::GetAncestor(int height) { - if (height > nHeight || height < 0) + if (height > GetHeight() || height < 0) return NULL; CBlockIndex* pindexWalk = this; - int heightWalk = nHeight; + int heightWalk = GetHeight(); while ( heightWalk > height && pindexWalk != 0 ) { int heightSkip = GetSkipHeight(heightWalk); @@ -110,5 +160,5 @@ const CBlockIndex* CBlockIndex::GetAncestor(int height) const void CBlockIndex::BuildSkip() { if (pprev) - pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); + pskip = pprev->GetAncestor(GetSkipHeight(GetHeight())); } diff --git a/src/chain.h b/src/chain.h index 45e478aef..9532fb15c 100644 --- a/src/chain.h +++ b/src/chain.h @@ -6,6 +6,8 @@ #ifndef BITCOIN_CHAIN_H #define BITCOIN_CHAIN_H +class CChainPower; + #include "arith_uint256.h" #include "primitives/block.h" #include "pow.h" @@ -103,6 +105,101 @@ enum BlockStatus: uint32_t { //! Blocks with this validity are assumed to satisfy all consensus rules. static const BlockStatus BLOCK_VALID_CONSENSUS = BLOCK_VALID_SCRIPTS; +class CBlockIndex; + +// This class provides an accumulator for both the chainwork and the chainPOS value +// CChainPower's can be compared, and the comparison ensures that work and proof of stake power +// are both used equally to determine which chain has the most work. This makes an attack +// that involves mining in secret completely ineffective, even before dPOW, unless a large part +// of the staking supply is also controlled. It also enables a faster deterministic convergence, +// aided by both POS and POW. +class CChainPower +{ + public: + arith_uint256 chainWork; + arith_uint256 chainStake; + int32_t nHeight; + + CChainPower() : nHeight(0), chainStake(0), chainWork(0) {} + CChainPower(CBlockIndex *pblockIndex); + CChainPower(CBlockIndex *pblockIndex, const arith_uint256 &stake, const arith_uint256 &work); + CChainPower(int32_t height) : nHeight(height), chainStake(0), chainWork(0) {} + CChainPower(int32_t height, const arith_uint256 &stake, const arith_uint256 &work) : + nHeight(height), chainStake(stake), chainWork(work) {} + + CChainPower &operator=(const CChainPower &chainPower) + { + chainWork = chainPower.chainWork; + chainStake = chainPower.chainStake; + nHeight = chainPower.nHeight; + return *this; + } + + CChainPower &operator+=(const CChainPower &chainPower) + { + this->chainWork += chainPower.chainWork; + this->chainStake += chainPower.chainStake; + return *this; + } + + friend CChainPower operator+(const CChainPower &chainPowerA, const CChainPower &chainPowerB) + { + CChainPower result = CChainPower(chainPowerA); + result.chainWork += chainPowerB.chainWork; + result.chainStake += chainPowerB.chainStake; + return result; + } + + friend CChainPower operator-(const CChainPower &chainPowerA, const CChainPower &chainPowerB) + { + CChainPower result = CChainPower(chainPowerA); + result.chainWork -= chainPowerB.chainWork; + result.chainStake -= chainPowerB.chainStake; + return result; + } + + friend CChainPower operator*(const CChainPower &chainPower, int32_t x) + { + CChainPower result = CChainPower(chainPower); + result.chainWork *= x; + result.chainStake *= x; + return result; + } + + CChainPower &addStake(const arith_uint256 &nChainStake) + { + chainStake += nChainStake; + return *this; + } + + CChainPower &addWork(const arith_uint256 &nChainWork) + { + chainWork += nChainWork; + return *this; + } + + friend bool operator==(const CChainPower &p1, const CChainPower &p2); + + friend bool operator!=(const CChainPower &p1, const CChainPower &p2) + { + return !(p1 == p2); + } + + friend bool operator<(const CChainPower &p1, const CChainPower &p2); + + friend bool operator<=(const CChainPower &p1, const CChainPower &p2); + + friend bool operator>(const CChainPower &p1, const CChainPower &p2) + { + return !(p1 <= p2); + } + + friend bool operator>=(const CChainPower &p1, const CChainPower &p2) + { + return !(p1 < p2); + } +}; + /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. A blockindex may have multiple pprev pointing @@ -121,7 +218,6 @@ public: CBlockIndex* pskip; //! height of the entry in the chain. The genesis block has height 0 - int nHeight; int64_t newcoins,zfunds; int8_t segid; // jl777 fields //! Which # file this block is stored in (blk?????.dat) int nFile; @@ -133,7 +229,7 @@ public: unsigned int nUndoPos; //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block - arith_uint256 nChainWork; + CChainPower chainPower; //! Number of transactions in this block. //! Note: in a potential headers-first mode, this number cannot be relied upon @@ -195,11 +291,10 @@ public: segid = -2; pprev = NULL; pskip = NULL; - nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; - nChainWork = arith_uint256(); + chainPower = CChainPower(); nTx = 0; nChainTx = 0; nStatus = 0; @@ -239,6 +334,16 @@ public: nSolution = block.nSolution; } + int32_t SetHeight(int32_t height) + { + this->chainPower.nHeight = height; + } + + inline int32_t GetHeight() const + { + return this->chainPower.nHeight; + } + CDiskBlockPos GetBlockPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_DATA) { @@ -301,7 +406,7 @@ public: std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", - pprev, nHeight, + pprev, this->chainPower.nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } @@ -353,7 +458,7 @@ class CDiskBlockIndex : public CBlockIndex public: uint256 hashPrev; - CDiskBlockIndex() { + CDiskBlockIndex() : CBlockIndex() { hashPrev = uint256(); } @@ -369,7 +474,10 @@ public: if (!(s.GetType() & SER_GETHASH)) READWRITE(VARINT(nVersion)); - READWRITE(VARINT(nHeight)); + if (ser_action.ForRead()) { + chainPower = CChainPower(); + } + READWRITE(VARINT(chainPower.nHeight)); READWRITE(VARINT(nStatus)); READWRITE(VARINT(nTx)); if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) @@ -478,18 +586,18 @@ public: /** Efficiently check whether a block is present in this chain. */ bool Contains(const CBlockIndex *pindex) const { - return (*this)[pindex->nHeight] == pindex; + return (*this)[pindex->GetHeight()] == pindex; } /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */ CBlockIndex *Next(const CBlockIndex *pindex) const { if (Contains(pindex)) - return (*this)[pindex->nHeight + 1]; + return (*this)[pindex->GetHeight() + 1]; else return NULL; } - /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ + /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->GetHeight() : -1. */ int Height() const { return vChain.size() - 1; } diff --git a/src/chainparams.cpp b/src/chainparams.cpp index d4b9772f8..b4b5ed45a 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -80,7 +80,7 @@ void *chainparams_commandline(void *ptr); extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; extern uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT; extern uint32_t ASSETCHAIN_INIT, ASSETCHAINS_MAGIC; -extern int32_t VERUS_BLOCK_POSUNITS, ASSETCHAINS_LWMAPOS; +extern int32_t VERUS_BLOCK_POSUNITS, ASSETCHAINS_LWMAPOS, ASSETCHAINS_SAPLING, ASSETCHAINS_OVERWINTER; extern uint64_t ASSETCHAINS_SUPPLY, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH; const arith_uint256 maxUint = UintToArith256(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); @@ -115,9 +115,9 @@ public: consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight = Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; consensus.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion = 170005; - consensus.vUpgrades[Consensus::UPGRADE_OVERWINTER].nActivationHeight = 1; + consensus.vUpgrades[Consensus::UPGRADE_OVERWINTER].nActivationHeight = 227520 - 120; consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nProtocolVersion = 170007; - consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight = 1; + consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight = 227520; // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000000000281b32ff3198a1"); @@ -266,6 +266,9 @@ void *chainparams_commandline(void *ptr) mainParams.consensus.nLwmaPOSAjustedWeight = 46531; } + mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight = ASSETCHAINS_SAPLING; + mainParams.consensus.vUpgrades[Consensus::UPGRADE_OVERWINTER].nActivationHeight = ASSETCHAINS_OVERWINTER; + // only require coinbase protection on Verus from the Komodo family of coins if (strcmp(ASSETCHAINS_SYMBOL,"VRSC") == 0) { diff --git a/src/consensus/params.h b/src/consensus/params.h index 7f860388c..feff46e03 100644 --- a/src/consensus/params.h +++ b/src/consensus/params.h @@ -112,6 +112,8 @@ struct Params { int64_t AveragingWindowTimespan() const { return nPowAveragingWindow * nPowTargetSpacing; } int64_t MinActualTimespan() const { return (AveragingWindowTimespan() * (100 - nPowMaxAdjustUp )) / 100; } int64_t MaxActualTimespan() const { return (AveragingWindowTimespan() * (100 + nPowMaxAdjustDown)) / 100; } + int32_t SetSaplingHeight(int32_t height) { vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight = height; } + int32_t SetOverwinterHeight(int32_t height) { vUpgrades[Consensus::UPGRADE_OVERWINTER].nActivationHeight = height; } uint256 nMinimumChainWork; }; } // namespace Consensus diff --git a/src/crosschain.cpp b/src/crosschain.cpp index 831c7bcae..c0e5cfa9b 100644 --- a/src/crosschain.cpp +++ b/src/crosschain.cpp @@ -133,7 +133,7 @@ TxProof GetCrossChainProof(const uint256 txid, const char* targetSymbol, uint32_ CBlockIndex blockIdx; if (!eval->GetTxConfirmed(assetChainProof.first, sourceNotarisation, blockIdx)) throw std::runtime_error("Notarisation not found"); - kmdHeight = blockIdx.nHeight; + kmdHeight = blockIdx.GetHeight(); } // We now have a kmdHeight of the notarisation from chain A. So we know that a MoM exists @@ -241,7 +241,7 @@ bool GetNextBacknotarisation(uint256 kmdNotarisationTxid, Notarisation &out) return false; } - return (bool) ScanNotarisationsFromHeight(block.nHeight+1, &IsSameAssetChain, out); + return (bool) ScanNotarisationsFromHeight(block.GetHeight()+1, &IsSameAssetChain, out); } @@ -267,19 +267,19 @@ TxProof GetAssetchainProof(uint256 hash) throw std::runtime_error("tx still in mempool"); blockIndex = mapBlockIndex[blockHash]; - int h = blockIndex->nHeight; + int h = blockIndex->GetHeight(); // The assumption here is that the first notarisation for a height GTE than // the transaction block height will contain the corresponding MoM. If there // are sequence issues with the notarisations this may fail. auto isTarget = [&](Notarisation ¬a) { if (!IsSameAssetChain(nota)) return false; - return nota.second.height >= blockIndex->nHeight; + return nota.second.height >= blockIndex->GetHeight(); }; - if (!ScanNotarisationsFromHeight(blockIndex->nHeight, isTarget, nota)) + if (!ScanNotarisationsFromHeight(blockIndex->GetHeight(), isTarget, nota)) throw std::runtime_error("backnotarisation not yet confirmed"); // index of block in MoM leaves - nIndex = nota.second.height - blockIndex->nHeight; + nIndex = nota.second.height - blockIndex->GetHeight(); } // build merkle chain from blocks to MoM diff --git a/src/gtest/test_checkblock.cpp b/src/gtest/test_checkblock.cpp index 7c13535c2..01f098004 100644 --- a/src/gtest/test_checkblock.cpp +++ b/src/gtest/test_checkblock.cpp @@ -165,7 +165,7 @@ TEST_F(ContextualCheckBlockTest, BadCoinbaseHeight) { block.vtx[0] = tx2; CBlock prev; CBlockIndex indexPrev {prev}; - indexPrev.nHeight = 0; + indexPrev.SetHeight(0); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-height", false)).Times(1); EXPECT_FALSE(ContextualCheckBlock(block, state, &indexPrev)); diff --git a/src/gtest/test_pow.cpp b/src/gtest/test_pow.cpp index ac3ce59e1..c09314395 100644 --- a/src/gtest/test_pow.cpp +++ b/src/gtest/test_pow.cpp @@ -15,10 +15,10 @@ TEST(PoW, DifficultyAveraging) { std::vector blocks(lastBlk+1); for (int i = 0; i <= lastBlk; i++) { blocks[i].pprev = i ? &blocks[i - 1] : nullptr; - blocks[i].nHeight = i; + blocks[i].SetHeight(i); blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing; blocks[i].nBits = 0x1e7fffff; /* target 0x007fffff000... */ - blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0); + blocks[i].chainPower = i ? (CChainPower(&blocks[i]) + blocks[i - 1].chainPower) + GetBlockProof(blocks[i - 1]) : CChainPower(&blocks[i]); } // Result should be the same as if last difficulty was used diff --git a/src/gtest/test_rpc.cpp b/src/gtest/test_rpc.cpp index 3733379a8..202b2e3ab 100644 --- a/src/gtest/test_rpc.cpp +++ b/src/gtest/test_rpc.cpp @@ -21,7 +21,7 @@ TEST(rpc, check_blockToJSON_returns_minified_solution) { ss >> block; CBlockIndex index {block}; - index.nHeight = 1391; + index.SetHeight(1391); UniValue obj = blockToJSON(block, &index); EXPECT_EQ("009f44ff7505d789b964d6817734b8ce1377d456255994370d06e59ac99bd5791b6ad174a66fd71c70e60cfc7fd88243ffe06f80b1ad181625f210779c745524629448e25348a5fce4f346a1735e60fdf53e144c0157dbc47c700a21a236f1efb7ee75f65b8d9d9e29026cfd09048233175202b211b9a49de4ab46f1cac71b6ea57a686377bd612378746e70c61a659c9cd683269e9c2a5cbc1d19f1149345302bbd0a1e62bf4bab01e9caeea789a1519441a61b146de35a4cc75dbdf01029127e311ad5073e7e96397f47226a7df9df66b2086b70756db013bbaeb068260157014b2602fc7dc71336e1439c887d2742d9730b4e79b08ec7839c3e2a037ae1565d04e05e351bb3531e5ef42cf7b71ca1482a9205245dd41f4db0f71644f8bdb88e845558537c03834c06ac83f336651e54e2edfc12e15ea9b7ea2c074e6155654d44c4d3bd90d9511050e9ad87d170db01448e5be6f45419cd86008978db5e3ceab79890234f992648d69bf1053855387db646ccdee5575c65f81dd0f670b016d9f9a84707d91f77b862f697b8bb08365ba71fbe6bfa47af39155a75ebdcb1e5d69f59c40c9e3a64988c1ec26f7f5159eef5c244d504a9e46125948ecc389c2ec3028ac4ff39ffd66e7743970819272b21e0c2df75b308bc62896873952147e57ed79446db4cdb5a563e76ec4c25899d41128afb9a5f8fc8063621efb7a58b9dd666d30c73e318cdcf3393bfec200e160f500e645f7baac263db99fa4a7c1cb4fea219fc512193102034d379f244c21a81821301b8d47c90247713a3e902c762d7bafa6cdb744eeb6d3b50dd175599d02b6e9f5bbda59366e04862aa765135968426e7ac0116de7351940dc57c0ae451d63f667e39891bc81e09e6c76f6f8a7582f7447c6f5945f717b0e52a7e3dd0c6db4061362123cc53fd8ede4abed4865201dc4d8eb4e5d48baa565183b69a5304a44c0600bb24dcaeee9d95ceebd27c1b0a33e0b46f23797d7d7907300b2bb7d62ef2fc5aa139250c73930c621bb5f41fc235534ee8014dfaddd5245aeb01198420ba7b5c076545329c94d54fa725a8e807579f5f0cc9d98170598023268f5930893620190275e6b3c6f5181e36310a9a475208316911d78f917d724c5946c553b7ec042c563c540114b6b78bd4c6e808ee391a4a9d93e127032983c5b3708037b14aa604cfb034e7c8b0ffdd6936446fe80216178506a87402653a373926eeff66e704daf992a0a9a5c3ad80566c0339be9e5b8e35b3b3226b2f7767e20d992ea6c3d6e322eca37b0c7f7e60060802f5abcc1975841365cadbdc3867063addfc803766ae525375ecddee61f9df9ffcd20343c83ab82b0e91de039c59cb435c8d3159cc338b4901f40c9b5c27043bcf2bd5fa9b685b65c9ba5a1e11a51dd3f773051560341f9ec81d05bf259e2d4b7161f896fbb6812cfc924a32120b7367d5e40439e267adda6a1315bb0d6200ce6a503174c8d2a638ea6fd6b1f486d68db11bdca63c4f4a725d1ab6231ea875484e70b27d293c05803386924f283d4c12bb953474d92b7dd43d2d97193bd96281ebb63fa075d2f9ecd310c70ee1d97b5330bd8fb5791c5943ecf084e5f2c83915acac57519c46b166136068d6f9ec0dd598616e32c591128ce13705a283ca39d5b211409600e07b3713113374d9700207a45394eac5b3b7afc9b1b2bad7d89fd3f35f6b2413ce615ee7869b3569009403b96fdacdb32ef0a7e5229e2b666d51e95bdfb009b892e88bde70621a9b6509f068781392df4bdbc5723bb15071993f0d9a11575af5ff6ef85eaea39bc86805b35d8beee91b779354147f2d85304b8b49d053e7444fdd3deb9d16de331f2552af5b3be7766bb8f3f6a78c62148efb231f2268", find_value(obj, "solution").get_str()); diff --git a/src/init.cpp b/src/init.cpp index 120879e88..0c4bdedc8 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1734,7 +1734,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) if (chainActive.Tip() && chainActive.Tip() != pindexRescan) { uiInterface.InitMessage(_("Rescanning...")); - LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); + LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->GetHeight(), pindexRescan->GetHeight()); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); diff --git a/src/komodo.h b/src/komodo.h index df82953db..6d67e1b33 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -510,7 +510,7 @@ int32_t komodo_validate_chain(uint256 srchash,int32_t notarized_height) static int32_t last_rewind; int32_t rewindtarget; CBlockIndex *pindex; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) return(0); - if ( IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != notarized_height) ) + if ( IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->GetHeight() != notarized_height) ) { if ( sp->NOTARIZED_HEIGHT > 0 && sp->NOTARIZED_HEIGHT < notarized_height ) rewindtarget = sp->NOTARIZED_HEIGHT - 1; @@ -800,33 +800,33 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) uint8_t scriptbuf[10001],pubkeys[64][33],rmd160[20],scriptPubKey[35]; uint256 zero,btctxid,txhash; int32_t i,j,k,numnotaries,notarized,scriptlen,isratification,nid,numvalid,specialtx,notarizedheight,notaryid,len,numvouts,numvins,height,txn_count; memset(&zero,0,sizeof(zero)); - komodo_init(pindex->nHeight); + komodo_init(pindex->GetHeight()); KOMODO_INITDONE = (uint32_t)time(NULL); if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) { fprintf(stderr,"unexpected null komodostateptr.[%s]\n",ASSETCHAINS_SYMBOL); return; } - //fprintf(stderr,"%s connect.%d\n",ASSETCHAINS_SYMBOL,pindex->nHeight); - numnotaries = komodo_notaries(pubkeys,pindex->nHeight,pindex->GetBlockTime()); + //fprintf(stderr,"%s connect.%d\n",ASSETCHAINS_SYMBOL,pindex->GetHeight()); + numnotaries = komodo_notaries(pubkeys,pindex->GetHeight(),pindex->GetBlockTime()); calc_rmd160_sha256(rmd160,pubkeys[0],33); - if ( pindex->nHeight > hwmheight ) - hwmheight = pindex->nHeight; + if ( pindex->GetHeight() > hwmheight ) + hwmheight = pindex->GetHeight(); else { - if ( pindex->nHeight != hwmheight ) + if ( pindex->GetHeight() != hwmheight ) { - printf("%s hwmheight.%d vs pindex->nHeight.%d t.%u reorg.%d\n",ASSETCHAINS_SYMBOL,hwmheight,pindex->nHeight,(uint32_t)pindex->nTime,hwmheight-pindex->nHeight); - komodo_purge_ccdata((int32_t)pindex->nHeight); - hwmheight = pindex->nHeight; + printf("%s hwmheight.%d vs pindex->GetHeight().%d t.%u reorg.%d\n",ASSETCHAINS_SYMBOL,hwmheight,pindex->GetHeight(),(uint32_t)pindex->nTime,hwmheight-pindex->GetHeight()); + komodo_purge_ccdata((int32_t)pindex->GetHeight()); + hwmheight = pindex->GetHeight(); } - komodo_event_rewind(sp,symbol,pindex->nHeight); - komodo_stateupdate(pindex->nHeight,0,0,0,zero,0,0,0,0,-pindex->nHeight,pindex->nTime,0,0,0,0,zero,0); + komodo_event_rewind(sp,symbol,pindex->GetHeight()); + komodo_stateupdate(pindex->GetHeight(),0,0,0,zero,0,0,0,0,-pindex->GetHeight(),pindex->nTime,0,0,0,0,zero,0); } - komodo_currentheight_set(chainActive.LastTip()->nHeight); + komodo_currentheight_set(chainActive.LastTip()->GetHeight()); if ( pindex != 0 ) { - height = pindex->nHeight; + height = pindex->GetHeight(); txn_count = block.vtx.size(); for (i=0; inHeight == hwmheight ) + if ( pindex->GetHeight() == hwmheight ) komodo_stateupdate(height,0,0,0,zero,0,0,0,0,height,(uint32_t)pindex->nTime,0,0,0,0,zero,0); } else fprintf(stderr,"komodo_connectblock: unexpected null pindex\n"); //KOMODO_INITDONE = (uint32_t)time(NULL); - //fprintf(stderr,"%s end connect.%d\n",ASSETCHAINS_SYMBOL,pindex->nHeight); + //fprintf(stderr,"%s end connect.%d\n",ASSETCHAINS_SYMBOL,pindex->GetHeight()); } diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 263c79e43..87ea945c3 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -630,13 +630,13 @@ int32_t komodo_isPoS(CBlock *pblock) void komodo_disconnect(CBlockIndex *pindex,CBlock& block) { char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; struct komodo_state *sp; - //fprintf(stderr,"disconnect ht.%d\n",pindex->nHeight); - komodo_init(pindex->nHeight); + //fprintf(stderr,"disconnect ht.%d\n",pindex->GetHeight()); + komodo_init(pindex->GetHeight()); if ( (sp= komodo_stateptr(symbol,dest)) != 0 ) { - //sp->rewinding = pindex->nHeight; - //fprintf(stderr,"-%d ",pindex->nHeight); - } else printf("komodo_disconnect: ht.%d cant get komodo_state.(%s)\n",pindex->nHeight,ASSETCHAINS_SYMBOL); + //sp->rewinding = pindex->GetHeight(); + //fprintf(stderr,"-%d ",pindex->GetHeight()); + } else printf("komodo_disconnect: ht.%d cant get komodo_state.(%s)\n",pindex->GetHeight(),ASSETCHAINS_SYMBOL); } int32_t komodo_is_notarytx(const CTransaction& tx) @@ -665,7 +665,7 @@ int32_t komodo_block2height(CBlock *block) int32_t i,n,height2=-1,height = 0; uint8_t *ptr; CBlockIndex *pindex; if ( (pindex= mapBlockIndex[block->GetHash()]) != 0 ) { - height2 = (int32_t)pindex->nHeight; + height2 = (int32_t)pindex->GetHeight(); if ( height2 >= 0 ) return(height2); } @@ -750,9 +750,9 @@ CBlockIndex *komodo_chainactive(int32_t height) { if ( chainActive.LastTip() != 0 ) { - if ( height <= chainActive.LastTip()->nHeight ) + if ( height <= chainActive.LastTip()->GetHeight() ) return(chainActive[height]); - // else fprintf(stderr,"komodo_chainactive height %d > active.%d\n",height,chainActive.LastTip()->nHeight); + // else fprintf(stderr,"komodo_chainactive height %d > active.%d\n",height,chainActive.LastTip()->GetHeight()); } //fprintf(stderr,"komodo_chainactive null chainActive.LastTip() height %d\n",height); return(0); @@ -772,7 +772,7 @@ uint32_t komodo_heightstamp(int32_t height) int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; if ( pindex->didinit != 0 ) return; - //printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); + //printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->GetHeight(),pindex->notaryid,height); if ( pindex->didinit == 0 ) { pindex->notaryid = -1; @@ -784,12 +784,12 @@ uint32_t komodo_heightstamp(int32_t height) komodo_block2pubkey33(pindex->pubkey33,&block); //for (i=0; i<33; i++) // fprintf(stderr,"%02x",pindex->pubkey33[i]); - //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); + //fprintf(stderr," set pubkey at height %d/%d\n",pindex->GetHeight(),height); //if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) // pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); - } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); + } // else fprintf(stderr,"error loading block at %d/%d",pindex->GetHeight(),height); } - if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + if ( pindex->didinit != 0 && pindex->GetHeight() >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->GetHeight(),(uint32_t)pindex->nTime)) > 0 ) { for (i=0; ipubkey33[i]); - fprintf(stderr," unmatched pubkey at height %d/%d\n",pindex->nHeight,height); + fprintf(stderr," unmatched pubkey at height %d/%d\n",pindex->GetHeight(),height); } } }*/ @@ -986,12 +986,12 @@ int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 has int32_t notarized_height,MoMdepth; uint256 MoM,notarized_hash,notarized_desttxid; CBlockIndex *notary,*pindex; if ( (pindex= chainActive.LastTip()) == 0 ) return(-1); - notarized_height = komodo_notarizeddata(pindex->nHeight,¬arized_hash,¬arized_desttxid); + notarized_height = komodo_notarizeddata(pindex->GetHeight(),¬arized_hash,¬arized_desttxid); *notarized_heightp = notarized_height; - if ( notarized_height >= 0 && notarized_height <= pindex->nHeight && (notary= mapBlockIndex[notarized_hash]) != 0 ) + if ( notarized_height >= 0 && notarized_height <= pindex->GetHeight() && (notary= mapBlockIndex[notarized_hash]) != 0 ) { - //printf("nHeight.%d -> (%d %s)\n",pindex->Tip()->nHeight,notarized_height,notarized_hash.ToString().c_str()); - if ( notary->nHeight == notarized_height ) // if notarized_hash not in chain, reorg + //printf("nHeight.%d -> (%d %s)\n",pindex->Tip()->GetHeight(),notarized_height,notarized_hash.ToString().c_str()); + if ( notary->GetHeight() == notarized_height ) // if notarized_hash not in chain, reorg { if ( nHeight < notarized_height ) { @@ -1003,10 +1003,10 @@ int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 has fprintf(stderr,"[%s] nHeight.%d == NOTARIZED_HEIGHT.%d, diff hash\n",ASSETCHAINS_SYMBOL,nHeight,notarized_height); return(-1); } - } //else fprintf(stderr,"[%s] unexpected error notary_hash %s ht.%d at ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,notary->nHeight); + } //else fprintf(stderr,"[%s] unexpected error notary_hash %s ht.%d at ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,notary->GetHeight()); } //else if ( notarized_height > 0 && notarized_height != 73880 && notarized_height >= 170000 ) - // fprintf(stderr,"[%s] couldnt find notarized.(%s %d) ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,pindex->nHeight); + // fprintf(stderr,"[%s] couldnt find notarized.(%s %d) ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,pindex->GetHeight()); return(0); } @@ -1024,7 +1024,7 @@ uint32_t komodo_interest_args(uint32_t *txheighttimep,int32_t *txheightp,uint32_ if ( (pindex= mapBlockIndex[hashBlock]) != 0 ) { *valuep = tx.vout[n].nValue; - *txheightp = pindex->nHeight; + *txheightp = pindex->GetHeight(); *txheighttimep = pindex->nTime; if ( *tiptimep == 0 && (tipindex= chainActive.LastTip()) != 0 ) *tiptimep = (uint32_t)tipindex->nTime; @@ -1059,7 +1059,7 @@ int32_t komodo_isrealtime(int32_t *kmdheightp) if ( (sp= komodo_stateptrget((char *)"KMD")) != 0 ) *kmdheightp = sp->CURRENT_HEIGHT; else *kmdheightp = 0; - if ( (pindex= chainActive.LastTip()) != 0 && pindex->nHeight >= (int32_t)komodo_longestchain() ) + if ( (pindex= chainActive.LastTip()) != 0 && pindex->GetHeight() >= (int32_t)komodo_longestchain() ) return(1); else return(0); } @@ -1546,12 +1546,18 @@ bool verusCheckPOSBlock(int32_t slowflag, CBlock *pblock, int32_t height) //printf("after nNonce: %s, height: %d\n", nonce.GetHex().c_str(), height); //printf("POShash: %s\n\n", hash.GetHex().c_str()); + if (newPOSActive && posHash != hash) + { + printf("blk hash: %s\nnonce: %s\ncorrect: %s\n", pblock->GetHash().GetHex().c_str(), pblock->nNonce.GetHex().c_str(), nonce.GetHex().c_str()); + } + + //if ((!newPOSActive || posHash == hash) && hash <= target) if (hash <= target) { if ((mapBlockIndex.count(blkHash) == 0) || !(pastBlockIndex = mapBlockIndex[blkHash]) || - (height - pastBlockIndex->nHeight) < VERUS_MIN_STAKEAGE) + (height - pastBlockIndex->GetHeight()) < VERUS_MIN_STAKEAGE) { fprintf(stderr,"ERROR: invalid PoS block %s - stake transaction too new\n",blkHash.ToString().c_str()); } @@ -1660,7 +1666,7 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) return(0); } if ( (pprev= mapBlockIndex[pblock->hashPrevBlock]) != 0 ) - height = pprev->nHeight + 1; + height = pprev->GetHeight() + 1; if ( height == 0 ) return(0); } @@ -1800,21 +1806,21 @@ int64_t komodo_coinsupply(int64_t *zfundsp,int32_t height) *zfundsp = 0; if ( (pindex= komodo_chainactive(height)) != 0 ) { - while ( pindex != 0 && pindex->nHeight > 0 ) + while ( pindex != 0 && pindex->GetHeight() > 0 ) { if ( pindex->newcoins == 0 && pindex->zfunds == 0 ) { if ( komodo_blockload(block,pindex) == 0 ) - pindex->newcoins = komodo_newcoins(&pindex->zfunds,pindex->nHeight,&block); + pindex->newcoins = komodo_newcoins(&pindex->zfunds,pindex->GetHeight(),&block); else { - fprintf(stderr,"error loading block.%d\n",pindex->nHeight); + fprintf(stderr,"error loading block.%d\n",pindex->GetHeight()); return(0); } } supply += pindex->newcoins; zfunds += pindex->zfunds; - //printf("start ht.%d new %.8f -> supply %.8f zfunds %.8f -> %.8f\n",pindex->nHeight,dstr(pindex->newcoins),dstr(supply),dstr(pindex->zfunds),dstr(zfunds)); + //printf("start ht.%d new %.8f -> supply %.8f zfunds %.8f -> %.8f\n",pindex->GetHeight(),dstr(pindex->newcoins),dstr(supply),dstr(pindex->zfunds),dstr(zfunds)); pindex = pindex->pprev; } } diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 44f4acdbf..16e165534 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -1494,7 +1494,7 @@ void komodo_passport_iteration() komodo_statefname(fname,baseid<32?base:(char *)"",(char *)"realtime"); if ( (fp= fopen(fname,"wb")) != 0 ) { - buf[0] = (uint32_t)chainActive.LastTip()->nHeight; + buf[0] = (uint32_t)chainActive.LastTip()->GetHeight(); buf[1] = (uint32_t)komodo_longestchain(); if ( buf[0] != 0 && buf[0] == buf[1] ) { diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 3520af551..121b5ead6 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -86,6 +86,9 @@ int32_t VERUS_MIN_STAKEAGE = 150; // 1/2 this should also be a cap on the int32_t VERUS_CONSECUTIVE_POS_THRESHOLD = 7; int32_t VERUS_NOPOS_THRESHHOLD = 150; // if we have no POS blocks in this many blocks, set to default difficulty +int32_t ASSETCHAINS_SAPLING; +int32_t ASSETCHAINS_OVERWINTER; + uint64_t KOMODO_INTERESTSUM,KOMODO_WALLETBALANCE; uint64_t ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED,ASSETCHAINS_SUPPLY = 10; diff --git a/src/komodo_jumblr.h b/src/komodo_jumblr.h index fa44425fd..794e35d75 100755 --- a/src/komodo_jumblr.h +++ b/src/komodo_jumblr.h @@ -648,7 +648,7 @@ void jumblr_iteration() free(retstr); } } - height = (int32_t)chainActive.LastTip()->nHeight; + height = (int32_t)chainActive.LastTip()->GetHeight(); if ( time(NULL) < lasttime+40 ) return; lasttime = (uint32_t)time(NULL); diff --git a/src/komodo_pax.h b/src/komodo_pax.h index 35d226fc3..6f408042e 100644 --- a/src/komodo_pax.h +++ b/src/komodo_pax.h @@ -637,13 +637,13 @@ uint64_t komodo_paxpriceB(uint64_t seed,int32_t height,char *base,char *rel,uint uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uint64_t basevolume) { int32_t i,nonz=0; int64_t diff; uint64_t price,seed,sum = 0; - if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.LastTip() != 0 && height > chainActive.LastTip()->nHeight ) + if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.LastTip() != 0 && height > chainActive.LastTip()->GetHeight() ) { if ( height < 100000000 ) { static uint32_t counter; if ( counter++ < 3 ) - printf("komodo_paxprice height.%d vs tip.%d\n",height,chainActive.LastTip()->nHeight); + printf("komodo_paxprice height.%d vs tip.%d\n",height,chainActive.LastTip()->GetHeight()); } return(0); } diff --git a/src/komodo_utils.h b/src/komodo_utils.h index e1d05a750..c1040b595 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1759,8 +1759,14 @@ void komodo_args(char *argv0) ASSETCHAINS_OVERRIDE_PUBKEY = GetArg("-ac_pubkey",""); if ( (ASSETCHAINS_STAKED= GetArg("-ac_staked",0)) > 100 ) ASSETCHAINS_STAKED = 100; - if ( (ASSETCHAINS_LWMAPOS = GetArg("-ac_veruspos",0)) > 100 ) - ASSETCHAINS_LWMAPOS = 100; + + // for now, we only support 50% PoS due to other parts of the algorithm needing adjustment for + // other values + if ( (ASSETCHAINS_LWMAPOS = GetArg("-ac_veruspos",0)) != 0 ) + ASSETCHAINS_LWMAPOS = 50; + + ASSETCHAINS_SAPLING = GetArg("-ac_sapling", 227520); + ASSETCHAINS_OVERWINTER = GetArg("-ac_overwinter", (ASSETCHAINS_SAPLING - 120)); if ( strlen(ASSETCHAINS_OVERRIDE_PUBKEY.c_str()) == 66 && ASSETCHAINS_COMMISSION > 0 && ASSETCHAINS_COMMISSION <= 100000000 ) decode_hex(ASSETCHAINS_OVERRIDE_PUBKEY33,33,(char *)ASSETCHAINS_OVERRIDE_PUBKEY.c_str()); diff --git a/src/main.cpp b/src/main.cpp index e31456e4b..670aa299c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -127,8 +127,8 @@ namespace { { bool operator()(CBlockIndex *pa, CBlockIndex *pb) const { // First sort by most total work, ... - if (pa->nChainWork > pb->nChainWork) return false; - if (pa->nChainWork < pb->nChainWork) return true; + if (pa->chainPower > pb->chainPower) return false; + if (pa->chainPower < pb->chainPower) return true; // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; @@ -305,7 +305,7 @@ namespace { int GetHeight() { - return chainActive.LastTip()->nHeight; + return chainActive.LastTip()->GetHeight(); } void UpdatePreferredDownload(CNode* node, CNodeState* state) @@ -403,9 +403,9 @@ namespace { if (!state->hashLastUnknownBlock.IsNull()) { BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); - if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) + if (itOld != mapBlockIndex.end() && itOld->second->chainPower > CChainPower()) { - if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) + if (state->pindexBestKnownBlock == NULL || itOld->second->chainPower >= state->pindexBestKnownBlock->chainPower) state->pindexBestKnownBlock = itOld->second; state->hashLastUnknownBlock.SetNull(); } @@ -434,10 +434,10 @@ namespace { /** Find the last common ancestor two blocks have. * Both pa and pb must be non-NULL. */ CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { - if (pa->nHeight > pb->nHeight) { - pa = pa->GetAncestor(pb->nHeight); - } else if (pb->nHeight > pa->nHeight) { - pb = pb->GetAncestor(pa->nHeight); + if (pa->GetHeight() > pb->GetHeight()) { + pa = pa->GetAncestor(pb->GetHeight()); + } else if (pb->GetHeight() > pa->GetHeight()) { + pb = pb->GetAncestor(pa->GetHeight()); } while (pa != pb && pa && pb) { @@ -463,7 +463,7 @@ namespace { // Make sure pindexBestKnownBlock is up to date, we'll need it. ProcessBlockAvailability(nodeid); - if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { + if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->chainPower < chainActive.Tip()->chainPower) { // This peer has nothing interesting. return; } @@ -471,7 +471,7 @@ namespace { if (state->pindexLastCommonBlock == NULL) { // 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 = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; + state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->GetHeight(), chainActive.Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor @@ -485,16 +485,16 @@ namespace { // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to // download that next block if the window were 1 larger. - int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; - int nMaxHeight = std::min(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); + int nWindowEnd = state->pindexLastCommonBlock->GetHeight() + BLOCK_DOWNLOAD_WINDOW; + int nMaxHeight = std::min(state->pindexBestKnownBlock->GetHeight(), nWindowEnd + 1); NodeId waitingfor = -1; - while (pindexWalk->nHeight < nMaxHeight) { + while (pindexWalk->GetHeight() < nMaxHeight) { // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive // as iterating over ~100 CBlockIndex* entries anyway. - int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max(count - vBlocks.size(), 128)); + int nToFetch = std::min(nMaxHeight - pindexWalk->GetHeight(), std::max(count - vBlocks.size(), 128)); vToFetch.resize(nToFetch); - pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); + pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->GetHeight() + nToFetch); vToFetch[nToFetch - 1] = pindexWalk; for (unsigned int i = nToFetch - 1; i > 0; i--) { vToFetch[i - 1] = vToFetch[i]->pprev; @@ -514,7 +514,7 @@ namespace { state->pindexLastCommonBlock = pindex; } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { // The block is not already downloaded, and not yet in flight. - if (pindex->nHeight > nWindowEnd) { + if (pindex->GetHeight() > nWindowEnd) { // We reached the end of the window. if (vBlocks.size() == 0 && waitingfor != nodeid) { // We aren't able to fetch anything, but we would be if the download window was one larger. @@ -542,11 +542,11 @@ bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) { if (state == NULL) return false; stats.nMisbehavior = state->nMisbehavior; - stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; - stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1; + stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->GetHeight() : -1; + stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->GetHeight() : -1; BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) { if (queue.pindex) - stats.vHeightInFlight.push_back(queue.pindex->nHeight); + stats.vHeightInFlight.push_back(queue.pindex->GetHeight()); } return true; } @@ -1199,7 +1199,7 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state, { static uint32_t counter; if ( counter++ < 100 ) - printf("MEMPOOL: banned tx.%d being used at ht.%d vout.%d\n",k,(int32_t)chainActive.Tip()->nHeight,j); + printf("MEMPOOL: banned tx.%d being used at ht.%d vout.%d\n",k,(int32_t)chainActive.Tip()->GetHeight(),j); return(false); } } @@ -1528,7 +1528,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa } auto verifier = libzcash::ProofVerifier::Strict(); - if ( komodo_validate_interest(tx,chainActive.LastTip()->nHeight+1,chainActive.LastTip()->GetMedianTimePast() + 777,0) < 0 ) + if ( komodo_validate_interest(tx,chainActive.LastTip()->GetHeight()+1,chainActive.LastTip()->GetMedianTimePast() + 777,0) < 0 ) { //fprintf(stderr,"AcceptToMemoryPool komodo_validate_interest failure\n"); return error("AcceptToMemoryPool: komodo_validate_interest failed"); @@ -1656,7 +1656,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa // Bring the best block into scope view.GetBestBlock(); - nValueIn = view.GetValueIn(chainActive.LastTip()->nHeight,&interest,tx,chainActive.LastTip()->nTime); + nValueIn = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime); if ( 0 && interest != 0 ) fprintf(stderr,"add interest %.8f\n",(double)interest/COIN); // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool @@ -1781,7 +1781,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa if ( KOMODO_CONNECTING <= 0 && chainActive.LastTip() != 0 ) { flag = 1; - KOMODO_CONNECTING = (1<<30) + (int32_t)chainActive.LastTip()->nHeight + 1; + KOMODO_CONNECTING = (1<<30) + (int32_t)chainActive.LastTip()->GetHeight() + 1; } if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) { @@ -2069,7 +2069,7 @@ bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW) { if ( pindex == 0 ) return false; - if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos(),checkPOW)) + if (!ReadBlockFromDisk(pindex->GetHeight(),block, pindex->GetBlockPos(),checkPOW)) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", @@ -2152,17 +2152,19 @@ bool IsInitialBlockDownload() } bool state; + arith_uint256 bigZero = arith_uint256(); + arith_uint256 minWork = UintToArith256(chainParams.GetConsensus().nMinimumChainWork); CBlockIndex *ptr = chainActive.Tip(); if (ptr == NULL) return true; - if (ptr->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork)) + if (ptr->chainPower < CChainPower(ptr, bigZero, minWork)) return true; - state = ((chainActive.Height() < ptr->nHeight - 24*60) || + state = ((chainActive.Height() < ptr->GetHeight() - 24*60) || ptr->GetBlockTime() < (GetTime() - nMaxTipAge)); - //fprintf(stderr,"state.%d ht.%d vs %d, t.%u %u\n",state,(int32_t)chainActive.Height(),(uint32_t)ptr->nHeight,(int32_t)ptr->GetBlockTime(),(uint32_t)(GetTime() - chainParams.MaxTipAge())); + //fprintf(stderr,"state.%d ht.%d vs %d, t.%u %u\n",state,(int32_t)chainActive.Height(),(uint32_t)ptr->GetHeight(),(int32_t)ptr->GetBlockTime(),(uint32_t)(GetTime() - chainParams.MaxTipAge())); if (!state) { LogPrintf("Leaving InitialBlockDownload (latching to false)\n"); @@ -2195,8 +2197,8 @@ bool IsInSync() int longestchain = komodo_longestchain(); if ( !pbi || (pindexBestHeader == 0) || - ((pindexBestHeader->nHeight - 1) > pbi->nHeight) || - (longestchain != 0 && longestchain > pbi->nHeight) ) + ((pindexBestHeader->GetHeight() - 1) > pbi->GetHeight()) || + (longestchain != 0 && longestchain > pbi->GetHeight()) ) return false; return true; @@ -2217,10 +2219,10 @@ void CheckForkWarningConditions() // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it) // of our head, drop it - if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288) + if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->GetHeight() >= 288) pindexBestForkTip = NULL; - if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.LastTip()->nChainWork + (GetBlockProof(*chainActive.LastTip()) * 6))) + if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->chainPower > (chainActive.LastTip()->chainPower + (GetBlockProof(*chainActive.LastTip()) * 6)))) { if (!fLargeWorkForkFound && pindexBestForkBase) { @@ -2231,8 +2233,8 @@ void CheckForkWarningConditions() if (pindexBestForkTip && pindexBestForkBase) { LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__, - pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(), - pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString()); + pindexBestForkBase->GetHeight(), pindexBestForkBase->phashBlock->ToString(), + pindexBestForkTip->GetHeight(), pindexBestForkTip->phashBlock->ToString()); fLargeWorkForkFound = true; } else @@ -2258,7 +2260,7 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) CBlockIndex* plonger = chainActive.LastTip(); while (pfork && pfork != plonger) { - while (plonger && plonger->nHeight > pfork->nHeight) + while (plonger && plonger->GetHeight() > pfork->GetHeight()) plonger = plonger->pprev; if (pfork == plonger) break; @@ -2272,9 +2274,9 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) // or a chain that is entirely longer than ours and invalid (note that this should be detected by both) // We define it this way because it allows us to only store the highest fork tip (+ base) which meets // the 7-block condition and from this always have the most-likely-to-cause-warning fork - if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) && - pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && - chainActive.Height() - pindexNewForkTip->nHeight < 72) + if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->GetHeight() > pindexBestForkTip->GetHeight())) && + pindexNewForkTip->chainPower - pfork->chainPower > (GetBlockProof(*pfork) * 7) && + chainActive.Height() - pindexNewForkTip->GetHeight() < 72) { pindexBestForkTip = pindexNewForkTip; pindexBestForkBase = pfork; @@ -2305,17 +2307,20 @@ void Misbehaving(NodeId pnode, int howmuch) void static InvalidChainFound(CBlockIndex* pindexNew) { - if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork) + if (!pindexBestInvalid || pindexNew->chainPower > pindexBestInvalid->chainPower) pindexBestInvalid = 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())); + + LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g log2_stake=%.8g date=%s\n", __func__, + pindexNew->GetBlockHash().ToString(), pindexNew->GetHeight(), + log(pindexNew->chainPower.chainWork.getdouble())/log(2.0), + log(pindexNew->chainPower.chainStake.getdouble())/log(2.0), + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime())); CBlockIndex *tip = chainActive.LastTip(); assert (tip); - LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__, - tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), + LogPrintf("%s: current best=%s height=%d log2_work=%.8g log2_stake=%.8g date=%s\n", __func__, + tip->GetBlockHash().ToString(), chainActive.Height(), + log(tip->chainPower.chainWork.getdouble())/log(2.0), + log(tip->chainPower.chainStake.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime())); CheckForkWarningConditions(); } @@ -2393,7 +2398,7 @@ int GetSpendHeight(const CCoinsViewCache& inputs) { LOCK(cs_main); CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; - return pindexPrev->nHeight + 1; + return pindexPrev->GetHeight() + 1; } namespace Consensus { @@ -2447,7 +2452,7 @@ namespace Consensus { // Check for negative or overflow input values nValueIn += coins->vout[prevout.n].nValue; #ifdef KOMODO_ENABLE_INTEREST - if ( ASSETCHAINS_SYMBOL[0] == 0 && nSpendHeight > 60000 )//chainActive.LastTip() != 0 && chainActive.LastTip()->nHeight >= 60000 ) + if ( ASSETCHAINS_SYMBOL[0] == 0 && nSpendHeight > 60000 )//chainActive.LastTip() != 0 && chainActive.LastTip()->GetHeight() >= 60000 ) { if ( coins->vout[prevout.n].nValue >= 10*COIN ) { @@ -2577,7 +2582,7 @@ bool ContextualCheckInputs( // While checking, GetBestBlock() refers to the parent block. // This is also true for mempool checks. CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; - int nSpendHeight = pindexPrev->nHeight + 1; + int nSpendHeight = pindexPrev->GetHeight() + 1; for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; @@ -2777,7 +2782,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22); // undo receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->GetHeight(), i, hash, k, false), out.nValue)); // undo unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(2, uint160(hashBytes), hash, k), CAddressUnspentValue())); @@ -2787,7 +2792,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23); // undo receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->GetHeight(), i, hash, k, false), out.nValue)); // undo unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, uint160(hashBytes), hash, k), CAddressUnspentValue())); @@ -2797,7 +2802,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(out.scriptPubKey.begin()+1, out.scriptPubKey.begin()+34); // undo receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->GetHeight(), i, hash, k, false), out.nValue)); // undo unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), hash, k), CAddressUnspentValue())); @@ -2807,7 +2812,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(out.scriptPubKey.begin(), out.scriptPubKey.end()); // undo receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->GetHeight(), i, hash, k, false), out.nValue)); // undo unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), hash, k), CAddressUnspentValue())); @@ -2827,7 +2832,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex CCoinsModifier outs = view.ModifyCoins(hash); outs->ClearUnspendable(); - CCoins outsBlock(tx, pindex->nHeight); + CCoins outsBlock(tx, pindex->GetHeight()); // The CCoins serialization does not serialize negative numbers. // No network rules currently depend on the version here, so an inconsistency is harmless // but it must be corrected before txout nversion ever influences a network rule. @@ -2867,7 +2872,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22); // undo spending activity - addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1)); + addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->GetHeight(), i, hash, j, true), prevout.nValue * -1)); // restore unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(2, uint160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undo.nHeight))); @@ -2878,7 +2883,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23); // undo spending activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->GetHeight(), i, hash, j, true), prevout.nValue * -1)); // restore unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, uint160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undo.nHeight))); @@ -2888,7 +2893,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34); // undo spending activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->GetHeight(), i, hash, j, true), prevout.nValue * -1)); // restore unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undo.nHeight))); @@ -2898,7 +2903,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex vector hashBytes(prevout.scriptPubKey.begin(), prevout.scriptPubKey.end()); // undo spending activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->GetHeight(), i, hash, j, true), prevout.nValue * -1)); // restore unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undo.nHeight))); @@ -2924,7 +2929,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex // However, this is only reliable if the last block was on or after // the Sapling activation height. Otherwise, the last anchor was the // empty root. - if (NetworkUpgradeActive(pindex->pprev->nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) { + if (NetworkUpgradeActive(pindex->pprev->GetHeight(), Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) { view.PopAnchor(pindex->pprev->hashFinalSaplingRoot, SAPLING); } else { view.PopAnchor(SaplingMerkleTree::empty_root(), SAPLING); @@ -3024,7 +3029,7 @@ void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const const int FIFTY_YEARS = 50*365*24*60*60; double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS); - if (bestHeader->nHeight > BLOCKS_EXPECTED) + if (bestHeader->GetHeight() > BLOCKS_EXPECTED) { if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED) { @@ -3057,14 +3062,14 @@ static int64_t nTimeTotal = 0; bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) { const CChainParams& chainparams = Params(); - if ( KOMODO_STOPAT != 0 && pindex->nHeight > KOMODO_STOPAT ) + if ( KOMODO_STOPAT != 0 && pindex->GetHeight() > KOMODO_STOPAT ) return(false); - //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight); + //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->GetHeight()); AssertLockHeld(cs_main); bool fExpensiveChecks = true; if (fCheckpointsEnabled) { CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints()); - if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) { + if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->GetHeight()) == pindex) { // This block is an ancestor of a checkpoint: disable script checks fExpensiveChecks = false; } @@ -3073,7 +3078,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin auto disabledVerifier = libzcash::ProofVerifier::Disabled(); int32_t futureblock; // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in - if (!CheckBlock(&futureblock,pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, fCheckPOW, !fJustCheck) || futureblock != 0 ) + if (!CheckBlock(&futureblock,pindex->GetHeight(),pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, fCheckPOW, !fJustCheck) || futureblock != 0 ) { //fprintf(stderr,"checkblock failure in connectblock futureblock.%d\n",futureblock); return false; @@ -3103,8 +3108,8 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return true; } - bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); - //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet" + bool fScriptChecks = (!fCheckpointsEnabled || pindex->GetHeight() >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); + //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->GetHeight() > KOMODO_TESTNET_EXPIRATION ) // "testnet" // return(false); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. @@ -3167,7 +3172,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree)); // Grab the consensus branch ID for the block's height - auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus()); + auto consensusBranchId = CurrentEpochBranchId(pindex->GetHeight(), Params().GetConsensus()); std::vector txdata; txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated @@ -3180,7 +3185,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("ConnectBlock(): too many sigops"), REJECT_INVALID, "bad-blk-sigops"); - //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime); + //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->GetHeight(),tx.nLockTime); if (!tx.IsMint()) { if (!view.HaveInputs(tx)) @@ -3224,7 +3229,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (fAddressIndex && addressType > 0) { // record spending activity - addressIndex.push_back(make_pair(CAddressIndexKey(addressType, hashBytes, pindex->nHeight, i, txhash, j, true), prevout.nValue * -1)); + addressIndex.push_back(make_pair(CAddressIndexKey(addressType, hashBytes, pindex->GetHeight(), i, txhash, j, true), prevout.nValue * -1)); // remove address from unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(addressType, hashBytes, input.prevout.hash, input.prevout.n), CAddressUnspentValue())); @@ -3233,7 +3238,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (fSpentIndex) { // add the spent index to determine the txid and input that spent an output // and to find the amount and address from an input - spentIndex.push_back(make_pair(CSpentIndexKey(input.prevout.hash, input.prevout.n), CSpentIndexValue(txhash, j, pindex->nHeight, prevout.nValue, addressType, hashBytes))); + spentIndex.push_back(make_pair(CSpentIndexKey(input.prevout.hash, input.prevout.n), CSpentIndexValue(txhash, j, pindex->GetHeight(), prevout.nValue, addressType, hashBytes))); } } @@ -3251,7 +3256,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (!tx.IsCoinBase()) { - nFees += view.GetValueIn(chainActive.LastTip()->nHeight,&interest,tx,chainActive.LastTip()->nTime) - tx.GetValueOut(); + nFees += view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime) - tx.GetValueOut(); sum += interest; std::vector vChecks; @@ -3268,40 +3273,40 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin vector hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22); // record receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->GetHeight(), i, txhash, k, false), out.nValue)); // record unspent output - addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(2, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight))); + addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(2, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->GetHeight()))); } else if (out.scriptPubKey.IsPayToPublicKeyHash()) { vector hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23); // record receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->GetHeight(), i, txhash, k, false), out.nValue)); // record unspent output - addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight))); + addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->GetHeight()))); } else if (out.scriptPubKey.IsPayToPublicKey()) { vector hashBytes(out.scriptPubKey.begin()+1, out.scriptPubKey.begin()+34); // record receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->GetHeight(), i, txhash, k, false), out.nValue)); // record unspent output - addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight))); + addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->GetHeight()))); } else if (out.scriptPubKey.IsPayToCryptoCondition()) { vector hashBytes(out.scriptPubKey.begin(), out.scriptPubKey.end()); // record receiving activity - addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue)); + addressIndex.push_back(make_pair(CAddressIndexKey(1, Hash160(hashBytes), pindex->GetHeight(), i, txhash, k, false), out.nValue)); // record unspent output - addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight))); + addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, Hash160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->GetHeight()))); } else { @@ -3312,12 +3317,12 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } //if ( ASSETCHAINS_SYMBOL[0] == 0 ) - // komodo_earned_interest(pindex->nHeight,sum); + // komodo_earned_interest(pindex->GetHeight(),sum); CTxUndo undoDummy; if (i > 0) { blockundo.vtxundo.push_back(CTxUndo()); } - UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight); + UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->GetHeight()); BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) { @@ -3344,7 +3349,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin // If Sapling is active, block.hashFinalSaplingRoot must be the // same as the root of the Sapling tree - if (NetworkUpgradeActive(pindex->nHeight, chainparams.GetConsensus(), Consensus::UPGRADE_SAPLING)) { + if (NetworkUpgradeActive(pindex->GetHeight(), chainparams.GetConsensus(), Consensus::UPGRADE_SAPLING)) { if (block.hashFinalSaplingRoot != sapling_tree.root()) { return state.DoS(100, error("ConnectBlock(): block's hashFinalSaplingRoot is incorrect"), @@ -3354,7 +3359,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart; LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001); - CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus()) + sum; + CAmount blockReward = nFees + GetBlockSubsidy(pindex->GetHeight(), chainparams.GetConsensus()) + sum; if ( ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 ) { uint64_t checktoshis; @@ -3365,21 +3370,21 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin else fprintf(stderr,"checktoshis %.8f numvouts %d\n",dstr(checktoshis),(int32_t)block.vtx[0].vout.size()); } } - if (ASSETCHAINS_SYMBOL[0] != 0 && pindex->nHeight == 1 && block.vtx[0].GetValueOut() != blockReward) + if (ASSETCHAINS_SYMBOL[0] != 0 && pindex->GetHeight() == 1 && block.vtx[0].GetValueOut() != blockReward) { return state.DoS(100, error("ConnectBlock(): coinbase for block 1 pays wrong amount (actual=%d vs correct=%d)", block.vtx[0].GetValueOut(), blockReward), REJECT_INVALID, "bad-cb-amount"); } if ( block.vtx[0].GetValueOut() > blockReward+1 ) { - if ( ASSETCHAINS_SYMBOL[0] != 0 || pindex->nHeight >= KOMODO_NOTARIES_HEIGHT1 || block.vtx[0].vout[0].nValue > blockReward ) + if ( ASSETCHAINS_SYMBOL[0] != 0 || pindex->GetHeight() >= KOMODO_NOTARIES_HEIGHT1 || block.vtx[0].vout[0].nValue > blockReward ) { return state.DoS(100, error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)", block.vtx[0].GetValueOut(), blockReward), REJECT_INVALID, "bad-cb-amount"); } else if ( IS_KOMODO_NOTARY != 0 ) - fprintf(stderr,"allow nHeight.%d coinbase %.8f vs %.8f interest %.8f\n",(int32_t)pindex->nHeight,dstr(block.vtx[0].GetValueOut()),dstr(blockReward),dstr(sum)); + fprintf(stderr,"allow nHeight.%d coinbase %.8f vs %.8f interest %.8f\n",(int32_t)pindex->GetHeight(),dstr(block.vtx[0].GetValueOut()),dstr(blockReward),dstr(sum)); } if (!control.Wait()) return state.DoS(100, false); @@ -3408,9 +3413,9 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin // Move this if BLOCK_VALID_CONSENSUS is ever altered. static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS, "nCachedBranchId must be set after all consensus rules have been validated."); - if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) { + if (IsActivationHeightForAnyUpgrade(pindex->GetHeight(), Params().GetConsensus())) { pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE; - pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus()); + pindex->nCachedBranchId = CurrentEpochBranchId(pindex->GetHeight(), chainparams.GetConsensus()); } else if (pindex->pprev) { pindex->nCachedBranchId = pindex->pprev->nCachedBranchId; } @@ -3419,7 +3424,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin setDirtyBlockIndex.insert(pindex); } - ConnectNotarisations(block, pindex->nHeight); + ConnectNotarisations(block, pindex->GetHeight()); if (fTxIndex) if (!pblocktree->WriteTxIndex(vPos)) @@ -3615,9 +3620,11 @@ void static UpdateTip(CBlockIndex *pindexNew) { progress = (longestchain > 0 ) ? (double) chainActive.Height() / longestchain : 1.0; } - LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__, + LogPrintf("%s: new best=%s height=%d log2_work=%.8g log2_stake=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__, chainActive.LastTip()->GetBlockHash().ToString(), chainActive.Height(), - log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.LastTip()->nChainTx, + log(chainActive.Tip()->chainPower.chainWork.getdouble())/log(2.0), + log(chainActive.Tip()->chainPower.chainStake.getdouble())/log(2.0), + (unsigned long)chainActive.LastTip()->nChainTx, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.LastTip()->GetBlockTime()), progress, pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); @@ -3755,7 +3762,7 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * return AbortNode(state, "Failed to read block"); pblock = █ } - KOMODO_CONNECTING = (int32_t)pindexNew->nHeight; + KOMODO_CONNECTING = (int32_t)pindexNew->GetHeight(); // Get the current commitment tree SproutMerkleTree oldSproutTree; SaplingMerkleTree oldSaplingTree; @@ -3789,10 +3796,10 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001); // Remove conflicting transactions from the mempool. list txConflicted; - mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload()); + mempool.removeForBlock(pblock->vtx, pindexNew->GetHeight(), txConflicted, !IsInitialBlockDownload()); // Remove transactions that expire at new block height from mempool - mempool.removeExpired(pindexNew->nHeight); + mempool.removeExpired(pindexNew->GetHeight()); // Update chainActive & related variables. UpdateTip(pindexNew); @@ -3808,15 +3815,15 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * // Update cached incremental witnesses GetMainSignals().ChainTip(pindexNew, pblock, oldSproutTree, oldSaplingTree, true); - EnforceNodeDeprecation(pindexNew->nHeight); + EnforceNodeDeprecation(pindexNew->GetHeight()); int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1; LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001); LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001); - if ( KOMODO_LONGESTCHAIN != 0 && pindexNew->nHeight >= KOMODO_LONGESTCHAIN ) + if ( KOMODO_LONGESTCHAIN != 0 && pindexNew->GetHeight() >= KOMODO_LONGESTCHAIN ) KOMODO_INSYNC = 1; else KOMODO_INSYNC = 0; - //fprintf(stderr,"connect.%d insync.%d\n",(int32_t)pindexNew->nHeight,KOMODO_INSYNC); + //fprintf(stderr,"connect.%d insync.%d\n",(int32_t)pindexNew->GetHeight(),KOMODO_INSYNC); if ( ASSETCHAINS_SYMBOL[0] == 0 && KOMODO_INSYNC != 0 ) komodo_broadcast(pblock,8); return true; @@ -3843,7 +3850,7 @@ static CBlockIndex* FindMostWorkChain() { CBlockIndex *pindexTest = pindexNew; bool fInvalidAncestor = false; while (pindexTest && !chainActive.Contains(pindexTest)) { - assert(pindexTest->nChainTx || pindexTest->nHeight == 0); + assert(pindexTest->nChainTx || pindexTest->GetHeight() == 0); // Pruned nodes may have entries in setBlockIndexCandidates for // which block files have been deleted. Remove those as candidates @@ -3853,7 +3860,7 @@ static CBlockIndex* FindMostWorkChain() { bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA); if (fFailedChain || fMissingData) { // Candidate chain is not usable (either invalid or missing data) - if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)) + if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->chainPower > pindexBestInvalid->chainPower)) pindexBestInvalid = pindexNew; CBlockIndex *pindexFailed = pindexNew; // Remove the entire chain from the set. @@ -3906,7 +3913,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain, // then pindexFork will be null, and we would need to remove the entire chain including // our genesis block. In practice this (probably) won't happen because of checks elsewhere. - auto reorgLength = pindexOldTip ? pindexOldTip->nHeight - (pindexFork ? pindexFork->nHeight : -1) : 0; + auto reorgLength = pindexOldTip ? pindexOldTip->GetHeight() - (pindexFork ? pindexFork->GetHeight() : -1) : 0; static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance"); if (reorgLength > MAX_REORG_LENGTH) { auto msg = strprintf(_( @@ -3914,12 +3921,14 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." ), reorgLength, MAX_REORG_LENGTH) + "\n\n" + _("Reorganization details") + ":\n" + - "- " + strprintf(_("Current tip: %s, height %d, work %s"), - pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" + - "- " + strprintf(_("New tip: %s, height %d, work %s"), - pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" + + "- " + strprintf(_("Current tip: %s, height %d, work %s\nstake %s"), + pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight(), pindexOldTip->chainPower.chainWork.GetHex(), + pindexOldTip->chainPower.chainStake.GetHex()) + "\n" + + "- " + strprintf(_("New tip: %s, height %d, work %s\nstake %s"), + pindexMostWork->phashBlock->GetHex(), pindexMostWork->GetHeight(), pindexMostWork->chainPower.chainWork.GetHex(), + pindexMostWork->chainPower.chainStake.GetHex()) + "\n" + "- " + strprintf(_("Fork point: %s %s, height %d"), - ASSETCHAINS_SYMBOL,pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" + + ASSETCHAINS_SYMBOL,pindexFork->phashBlock->GetHex(), pindexFork->GetHeight()) + "\n\n" + _("Please help, human!"); LogPrintf("*** %s\n", msg); uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); @@ -3937,11 +3946,11 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo if ( KOMODO_REWIND != 0 ) { CBlockIndex *tipindex; - fprintf(stderr,">>>>>>>>>>> rewind start ht.%d -> KOMODO_REWIND.%d\n",chainActive.LastTip()->nHeight,KOMODO_REWIND); - while ( KOMODO_REWIND > 0 && (tipindex= chainActive.LastTip()) != 0 && tipindex->nHeight > KOMODO_REWIND ) + fprintf(stderr,">>>>>>>>>>> rewind start ht.%d -> KOMODO_REWIND.%d\n",chainActive.LastTip()->GetHeight(),KOMODO_REWIND); + while ( KOMODO_REWIND > 0 && (tipindex= chainActive.LastTip()) != 0 && tipindex->GetHeight() > KOMODO_REWIND ) { fBlocksDisconnected = true; - fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); + fprintf(stderr,"%d ",(int32_t)tipindex->GetHeight()); InvalidateBlock(state,tipindex); if ( !DisconnectTip(state) ) break; @@ -3955,15 +3964,15 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo // Build list of new blocks to connect. std::vector vpindexToConnect; bool fContinue = true; - int nHeight = pindexFork ? pindexFork->nHeight : -1; - while (fContinue && nHeight != pindexMostWork->nHeight) { + int nHeight = pindexFork ? pindexFork->GetHeight() : -1; + while (fContinue && nHeight != pindexMostWork->GetHeight()) { // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need // a few blocks along the way. - int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight); + int nTargetHeight = std::min(nHeight + 32, pindexMostWork->GetHeight()); vpindexToConnect.clear(); vpindexToConnect.reserve(nTargetHeight - nHeight); CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight); - while (pindexIter && pindexIter->nHeight != nHeight) { + while (pindexIter && pindexIter->GetHeight() != nHeight) { vpindexToConnect.push_back(pindexIter); pindexIter = pindexIter->pprev; } @@ -3986,7 +3995,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo } } else { PruneBlockIndexCandidates(); - if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) { + if (!pindexOldTip || chainActive.Tip()->chainPower > pindexOldTip->chainPower) { // We're in a better position than we were. Return temporarily to release the lock. fContinue = false; break; @@ -3996,10 +4005,10 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo } if (fBlocksDisconnected) { - mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + mempool.removeForReorg(pcoinsTip, chainActive.Tip()->GetHeight() + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); } mempool.removeWithoutBranchId( - CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); + CurrentEpochBranchId(chainActive.Tip()->GetHeight() + 1, Params().GetConsensus())); mempool.check(pcoinsTip); // Callbacks/notifications for a new best chain. @@ -4085,9 +4094,9 @@ bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { // ActivateBestChain considers blocks already in chainActive // unconditionally valid already, so force disconnect away from it. if (!DisconnectTip(state)) { - mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + mempool.removeForReorg(pcoinsTip, chainActive.Tip()->GetHeight() + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); mempool.removeWithoutBranchId( - CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); + CurrentEpochBranchId(chainActive.Tip()->GetHeight() + 1, Params().GetConsensus())); return false; } } @@ -4104,16 +4113,16 @@ bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { } InvalidChainFound(pindex); - mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + mempool.removeForReorg(pcoinsTip, chainActive.Tip()->GetHeight() + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); mempool.removeWithoutBranchId( - CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); + CurrentEpochBranchId(chainActive.Tip()->GetHeight() + 1, Params().GetConsensus())); return true; } bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) { AssertLockHeld(cs_main); - int nHeight = pindex->nHeight; + int nHeight = pindex->GetHeight(); // Remove the invalidity flag from this block and all its descendants. BlockMap::iterator it = mapBlockIndex.begin(); @@ -4160,7 +4169,7 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) if ( miPrev != mapBlockIndex.end() && (*miPrev).second == 0 ) { //fprintf(stderr,"edge case of both block and prevblock in the strange state\n"); - return(0); // return here to avoid the state of pindex->nHeight not set and pprev NULL + return(0); // return here to avoid the state of pindex->GetHeight() not set and pprev NULL } } // Construct new block index object @@ -4175,13 +4184,13 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) if (miPrev != mapBlockIndex.end()) { if ( (pindexNew->pprev= (*miPrev).second) != 0 ) - pindexNew->nHeight = pindexNew->pprev->nHeight + 1; + pindexNew->SetHeight(pindexNew->pprev->GetHeight() + 1); else fprintf(stderr,"unexpected null pprev %s\n",hash.ToString().c_str()); pindexNew->BuildSkip(); } - pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew); + pindexNew->chainPower = (pindexNew->pprev ? CChainPower(pindexNew) + pindexNew->pprev->chainPower : CChainPower(pindexNew)) + GetBlockProof(*pindexNew); pindexNew->RaiseValidity(BLOCK_VALID_TREE); - if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork) + if (pindexBestHeader == NULL || pindexBestHeader->chainPower < pindexNew->chainPower) pindexBestHeader = pindexNew; setDirtyBlockIndex.insert(pindexNew); @@ -4547,7 +4556,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta assert(pindexPrev); - int nHeight = pindexPrev->nHeight+1; + int nHeight = pindexPrev->GetHeight()+1; // Check proof of work if ( (ASSETCHAINS_SYMBOL[0] != 0 || nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams)) @@ -4588,7 +4597,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta // Don't accept any forks from the main chain prior to last checkpoint CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints()); int32_t notarized_height; - if ( nHeight == 1 && chainActive.LastTip() != 0 && chainActive.LastTip()->nHeight > 1 ) + if ( nHeight == 1 && chainActive.LastTip() != 0 && chainActive.LastTip()->GetHeight() > 1 ) { CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) @@ -4597,8 +4606,8 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta } if ( nHeight != 0 ) { - if ( pcheckpoint != 0 && nHeight < pcheckpoint->nHeight ) - return state.DoS(1, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight)); + if ( pcheckpoint != 0 && nHeight < pcheckpoint->GetHeight() ) + return state.DoS(1, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->GetHeight())); if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 ) { CBlockIndex *heightblock = chainActive[nHeight]; @@ -4620,7 +4629,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev) { - const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; + const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->GetHeight() + 1; const Consensus::Params& consensusParams = Params().GetConsensus(); // Check that all transactions are finalized @@ -4685,7 +4694,7 @@ bool AcceptBlockHeader(int32_t *futureblockp,const CBlockHeader& block, CValidat // fprintf(stderr,"accepthdr %s already known but no pindex\n",hash.ToString().c_str()); return true; } - if (!CheckBlockHeader(futureblockp,*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) + if (!CheckBlockHeader(futureblockp,*ppindex!=0?(*ppindex)->GetHeight():0,*ppindex, block, state,0)) { if ( *futureblockp == 0 ) { @@ -4764,13 +4773,13 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C // 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 = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true); + bool fHasMoreWork = (chainActive.Tip() ? pindex->chainPower > chainActive.Tip()->chainPower : 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(chainActive.Height() + BLOCK_DOWNLOAD_WINDOW)); //MIN_BLOCKS_TO_KEEP)); + bool fTooFarAhead = (pindex->GetHeight() > int(chainActive.Height() + BLOCK_DOWNLOAD_WINDOW)); //MIN_BLOCKS_TO_KEEP)); // TODO: deal better with return value and error conditions for duplicate // and unrequested blocks. @@ -4784,7 +4793,7 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C // See method docstring for why this is always disabled auto verifier = libzcash::ProofVerifier::Disabled(); - if ((!CheckBlock(futureblockp,pindex->nHeight,pindex,block, state, verifier,0)) || !ContextualCheckBlock(block, state, pindex->pprev)) + if ((!CheckBlock(futureblockp,pindex->GetHeight(),pindex,block, state, verifier,0)) || !ContextualCheckBlock(block, state, pindex->pprev)) { if ( *futureblockp == 0 ) { @@ -4797,7 +4806,7 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C } } - int nHeight = pindex->nHeight; + int nHeight = pindex->GetHeight(); // Write block to history file try { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); @@ -4923,11 +4932,11 @@ bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNo bool checked; uint256 hash; int32_t futureblock=0; auto verifier = libzcash::ProofVerifier::Disabled(); hash = pblock->GetHash(); - //fprintf(stderr,"ProcessBlock %d\n",(int32_t)chainActive.LastTip()->nHeight); + //fprintf(stderr,"ProcessBlock %d\n",(int32_t)chainActive.LastTip()->GetHeight()); { LOCK(cs_main); if ( chainActive.LastTip() != 0 ) - komodo_currentheight_set(chainActive.LastTip()->nHeight); + komodo_currentheight_set(chainActive.LastTip()->GetHeight()); checked = CheckBlock(&futureblock,height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier,0); bool fRequested = MarkBlockAsReceived(hash); fRequested |= fForceProcessing; @@ -4963,7 +4972,7 @@ bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNo if (futureblock == 0 && !ActivateBestChain(state, pblock)) return error("%s: ActivateBestChain failed", __func__); - //fprintf(stderr,"finished ProcessBlock %d\n",(int32_t)chainActive.LastTip()->nHeight); + //fprintf(stderr,"finished ProcessBlock %d\n",(int32_t)chainActive.LastTip()->GetHeight()); return true; } @@ -4976,7 +4985,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex CCoinsViewCache viewNew(pcoinsTip); CBlockIndex indexDummy(block); indexDummy.pprev = pindexPrev; - indexDummy.nHeight = pindexPrev->nHeight + 1; + indexDummy.SetHeight(pindexPrev->GetHeight() + 1); // JoinSplit proofs are verified in ConnectBlock auto verifier = libzcash::ProofVerifier::Disabled(); // NOTE: CheckBlockHeader is called by CheckBlock @@ -4986,7 +4995,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex return false; } int32_t futureblock; - if (!CheckBlock(&futureblock,indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) + if (!CheckBlock(&futureblock,indexDummy.GetHeight(),0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { //fprintf(stderr,"TestBlockValidity failure B checkPOW.%d\n",fCheckPOW); return false; @@ -5071,10 +5080,10 @@ void FindFilesToPrune(std::set& setFilesToPrune) if (chainActive.Tip() == NULL || nPruneTarget == 0) { return; } - if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) { + if (chainActive.Tip()->GetHeight() <= Params().PruneAfterHeight()) { return; } - unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP; + unsigned int nLastBlockWeCanPrune = chainActive.Tip()->GetHeight() - MIN_BLOCKS_TO_KEEP; uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files // So we should leave a buffer under our target to account for another allocation @@ -5196,14 +5205,14 @@ bool static LoadBlockIndexDB() LogPrintf("%s: loaded guts\n", __func__); boost::this_thread::interruption_point(); - // Calculate nChainWork + // Calculate chainPower vector > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; - vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + vSortedByHeight.push_back(make_pair(pindex->GetHeight(), pindex)); + //komodo_pindex_init(pindex,(int32_t)pindex->GetHeight()); } //fprintf(stderr,"load blockindexDB paired %u\n",(uint32_t)time(NULL)); sort(vSortedByHeight.begin(), vSortedByHeight.end()); @@ -5211,7 +5220,7 @@ bool static LoadBlockIndexDB() BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) { CBlockIndex* pindex = item.second; - pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex); + pindex->chainPower = (pindex->pprev ? CChainPower(pindex) + pindex->pprev->chainPower : CChainPower(pindex)) + GetBlockProof(*pindex); // We can link the chain of blocks for which we've received transactions at some point. // Pruned nodes may have deleted the block. if (pindex->nTx > 0) { @@ -5255,13 +5264,13 @@ bool static LoadBlockIndexDB() } if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL)) setBlockIndexCandidates.insert(pindex); - if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork)) + if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->chainPower > pindexBestInvalid->chainPower)) pindexBestInvalid = pindex; if (pindex->pprev) pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->GetHeight()); } //fprintf(stderr,"load blockindexDB chained %u\n",(uint32_t)time(NULL)); @@ -5291,7 +5300,7 @@ bool static LoadBlockIndexDB() if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->GetHeight()); } //fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) @@ -5339,7 +5348,7 @@ bool static LoadBlockIndexDB() if (pindex->pprev) { pindex->pprev->hashFinalSproutRoot = pindex->hashSproutAnchor; } - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->GetHeight()); } // Load pointer to end of best chain @@ -5408,31 +5417,31 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); - uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))))); - if (pindex->nHeight < chainActive.Height()-nCheckDepth) + uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->GetHeight())) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))))); + if (pindex->GetHeight() < chainActive.Height()-nCheckDepth) break; CBlock block; // check level 0: read from disk if (!ReadBlockFromDisk(block, pindex,0)) - return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); + return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->GetHeight(), pindex->GetBlockHash().ToString()); // check level 1: verify block validity int32_t futureblock; - if (nCheckLevel >= 1 && !CheckBlock(&futureblock,pindex->nHeight,pindex,block, state, verifier,0) ) - return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); + if (nCheckLevel >= 1 && !CheckBlock(&futureblock,pindex->GetHeight(),pindex,block, state, verifier,0) ) + return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->GetHeight(), pindex->GetBlockHash().ToString()); // check level 2: verify undo validity if (nCheckLevel >= 2 && pindex) { CBlockUndo undo; CDiskBlockPos pos = pindex->GetUndoPos(); if (!pos.IsNull()) { if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash())) - return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); + return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->GetHeight(), pindex->GetBlockHash().ToString()); } } // check level 3: check for inconsistencies during memory-only disconnect of tip blocks if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) { bool fClean = true; if (!DisconnectBlock(block, state, pindex, coins, &fClean)) - return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); + return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->GetHeight(), pindex->GetBlockHash().ToString()); pindexState = pindex->pprev; if (!fClean) { nGoodTransactions = 0; @@ -5445,24 +5454,24 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth } //fprintf(stderr,"end VerifyDB %u\n",(uint32_t)time(NULL)); if (pindexFailure) - return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); + return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->GetHeight() + 1, nGoodTransactions); // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { CBlockIndex *pindex = pindexState; while (pindex != chainActive.Tip()) { boost::this_thread::interruption_point(); - uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)))); + uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->GetHeight())) / (double)nCheckDepth * 50)))); pindex = chainActive.Next(pindex); CBlock block; if (!ReadBlockFromDisk(block, pindex,0)) - return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); + return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->GetHeight(), pindex->GetBlockHash().ToString()); if (!ConnectBlock(block, state, pindex, coins,false, true)) - return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); + return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->GetHeight(), pindex->GetBlockHash().ToString()); } } - LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions); + LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->GetHeight(), nGoodTransactions); return true; } @@ -5483,10 +5492,10 @@ bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches) auto sufficientlyValidated = [¶ms](const CBlockIndex* pindex) { auto consensus = params.GetConsensus(); bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE; - bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus); + bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->GetHeight(), consensus); return fFlagSet == fFlagExpected && pindex->nCachedBranchId && - *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus); + *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->GetHeight(), consensus); }; int nHeight = 1; @@ -5509,9 +5518,9 @@ bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches) ), rewindLength, MAX_REORG_LENGTH) + "\n\n" + _("Rewind details") + ":\n" + "- " + strprintf(_("Current tip: %s, height %d"), - pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" + + pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight()) + "\n" + "- " + strprintf(_("Rewinding to: %s, height %d"), - pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" + + pindexRewind->phashBlock->GetHex(), pindexRewind->GetHeight()) + "\n\n" + _("Please help, human!"); LogPrintf("*** %s\n", msg); uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); @@ -5531,7 +5540,7 @@ bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches) break; } if (!DisconnectTip(state, true)) { - return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight); + return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->GetHeight()); } // Occasionally flush state to disk. if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) @@ -5799,8 +5808,8 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) nLoaded++; if (state.IsError()) break; - } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) { - LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight); + } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->GetHeight() % 1000 == 0) { + LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->GetHeight()); } // Recursively process earlier encountered successors of this block @@ -5812,7 +5821,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) std::pair::iterator, std::multimap::iterator> range = mapBlocksUnknownParent.equal_range(head); while (range.first != range.second) { std::multimap::iterator it = range.first; - if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second,1)) + if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->GetHeight():0,block, it->second,1)) { LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(), head.ToString()); @@ -5914,9 +5923,9 @@ void static CheckBlockIndex() // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set. assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned). assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0)); - assert(pindex->nHeight == nHeight); // nHeight must be consistent. - assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's. - assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks. + assert(pindex->GetHeight() == nHeight); // nHeight must be consistent. + assert(pindex->pprev == NULL || pindex->chainPower >= pindex->pprev->chainPower); // For every block except the genesis block, the chainwork must be larger than the parent's. + assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->GetHeight() < nHeight))); // The pskip pointer must point back for all but the first 2 blocks. assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid @@ -6572,7 +6581,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // later (within the same cs_main lock, though). MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus()); } - LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id); + LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->GetHeight(), inv.hash.ToString(), pfrom->id); } } @@ -6626,12 +6635,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (pindex) pindex = chainActive.Next(pindex); int nLimit = 500; - LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id); + LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->GetHeight() : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id); for (; pindex; pindex = chainActive.Next(pindex)) { if (pindex->GetBlockHash() == hashStop) { - LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); + LogPrint("net", " getblocks stopping at %d %s\n", pindex->GetHeight(), pindex->GetBlockHash().ToString()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); @@ -6639,7 +6648,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, { // When this block is requested, we'll send an inv that'll // trigger the peer to getblocks the next batch of inventory. - LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); + LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->GetHeight(), pindex->GetBlockHash().ToString()); pfrom->hashContinue = pindex->GetBlockHash(); break; } @@ -6678,10 +6687,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // we must use CNetworkBlockHeader, as CBlockHeader won't include the 0x00 nTx count at the end for compatibility vector vHeaders; int nLimit = MAX_HEADERS_RESULTS; - LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id); - //if ( pfrom->lasthdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pfrom->lasthdrsreq != (int32_t)(pindex ? pindex->nHeight : -1) )// no need to ever suppress this + LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->GetHeight() : -1), hashStop.ToString(), pfrom->id); + //if ( pfrom->lasthdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pfrom->lasthdrsreq != (int32_t)(pindex ? pindex->GetHeight() : -1) )// no need to ever suppress this { - pfrom->lasthdrsreq = (int32_t)(pindex ? pindex->nHeight : -1); + pfrom->lasthdrsreq = (int32_t)(pindex ? pindex->GetHeight() : -1); for (; pindex; pindex = chainActive.Next(pindex)) { CBlockHeader h = pindex->GetBlockHeader(); @@ -6697,7 +6706,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, { static uint32_t counter; if ( counter++ < 3 ) - fprintf(stderr,"you can ignore redundant getheaders from peer.%d %d prev.%d\n",(int32_t)pfrom->id,(int32_t)(pindex ? pindex->nHeight : -1),pfrom->lasthdrsreq); + fprintf(stderr,"you can ignore redundant getheaders from peer.%d %d prev.%d\n",(int32_t)pfrom->id,(int32_t)(pindex ? pindex->GetHeight() : -1),pfrom->lasthdrsreq); }*/ } @@ -6883,10 +6892,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // Headers message had its maximum size; the peer may have more headers. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue // from there instead. - if ( pfrom->sendhdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pindexLast->nHeight != pfrom->sendhdrsreq ) + if ( pfrom->sendhdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pindexLast->GetHeight() != pfrom->sendhdrsreq ) { - pfrom->sendhdrsreq = (int32_t)pindexLast->nHeight; - LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight); + pfrom->sendhdrsreq = (int32_t)pindexLast->GetHeight(); + LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->GetHeight(), pfrom->id, pfrom->nStartingHeight); pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256()); } } @@ -7420,7 +7429,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) state.fSyncStarted = true; nSyncStarted++; CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader; - LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight); + LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->GetHeight(), pto->id, pto->nStartingHeight); pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256()); } } @@ -7526,7 +7535,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex); LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), - pindex->nHeight, pto->id); + pindex->GetHeight(), pto->id); } if (state.nBlocksInFlight == 0 && staller != -1) { if (State(staller)->nStallingSince == 0) { diff --git a/src/metrics.cpp b/src/metrics.cpp index 889fad109..0c158dfa9 100644 --- a/src/metrics.cpp +++ b/src/metrics.cpp @@ -351,7 +351,7 @@ int printMetrics(size_t cols, bool mining) auto hash = *it; if (mapBlockIndex.count(hash) > 0 && chainActive.Contains(mapBlockIndex[hash])) { - int height = mapBlockIndex[hash]->nHeight; + int height = mapBlockIndex[hash]->GetHeight(); CAmount subsidy = GetBlockSubsidy(height, consensusParams); if ((height > 0) && (height <= consensusParams.GetLastFoundersRewardBlockHeight())) { subsidy -= subsidy/5; diff --git a/src/miner.cpp b/src/miner.cpp index 7fe1412fd..72eb3f6f9 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -176,7 +176,7 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, { LOCK2(cs_main, mempool.cs); pindexPrev = chainActive.LastTip(); - const int nHeight = pindexPrev->nHeight + 1; + const int nHeight = pindexPrev->GetHeight() + 1; uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus()); const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); @@ -360,7 +360,7 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, //fprintf(stderr,"dont have inputs\n"); continue; } - CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->nHeight,&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut(); + CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut(); nTxSigOps += GetP2SHSigOpCount(tx, view); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) @@ -450,14 +450,14 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, if ( siglen > 0 ) { CAmount txfees = 0; - //if ( (int32_t)chainActive.LastTip()->nHeight+1 > 100 && GetAdjustedTime() < blocktime-157 ) + //if ( (int32_t)chainActive.LastTip()->GetHeight()+1 > 100 && GetAdjustedTime() < blocktime-157 ) // return(0); pblock->vtx.push_back(txStaked); pblocktemplate->vTxFees.push_back(txfees); pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked)); nFees += txfees; pblock->nTime = blocktime; - //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->nHeight+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13))); + //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->GetHeight()+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13))); } else return(0); //fprintf(stderr,"no utxos eligible for staking\n"); } @@ -644,7 +644,7 @@ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; - unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 + unsigned int nHeight = pindexPrev->GetHeight()+1; // Height first in coinbase required for block.version=2 CMutableTransaction txCoinbase(pblock->vtx[0]); txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; assert(txCoinbase.vin[0].scriptSig.size() <= 100); @@ -715,7 +715,7 @@ static bool ProcessBlockFound(CBlock* pblock) #endif // ENABLE_WALLET { LogPrintf("%s\n", pblock->ToString()); - LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->nHeight+1); + LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->GetHeight()+1); // Found a solution { @@ -757,7 +757,7 @@ static bool ProcessBlockFound(CBlock* pblock) // Process this block the same as if we had received it from another node CValidationState state; - if (!ProcessNewBlock(1,chainActive.LastTip()->nHeight+1,state, NULL, pblock, true, NULL)) + if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL)) return error("KomodoMiner: ProcessNewBlock, block not accepted"); TrackMinedBlock(pblock->GetHash()); @@ -803,12 +803,12 @@ CBlockIndex *get_chainactive(int32_t height) { if ( chainActive.LastTip() != 0 ) { - if ( height <= chainActive.LastTip()->nHeight ) + if ( height <= chainActive.LastTip()->GetHeight() ) { LOCK(cs_main); return(chainActive[height]); } - // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->nHeight); + // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight()); } //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height); return(0); @@ -833,7 +833,7 @@ void static VerusStaker(CWallet *pwallet) solnPlaceholder.resize(Eh200_9.SolutionWidth); uint8_t *script; uint64_t total,checktoshis; int32_t i,j; - while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 && + while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && { sleep(1); if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) @@ -854,13 +854,13 @@ void static VerusStaker(CWallet *pwallet) { waitForPeers(chainparams); CBlockIndex* pindexPrev = chainActive.LastTip(); - printf("Staking height %d for %s\n", pindexPrev->nHeight + 1, ASSETCHAINS_SYMBOL); + printf("Staking height %d for %s\n", pindexPrev->GetHeight() + 1, ASSETCHAINS_SYMBOL); // Create new block unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - if ( Mining_height != pindexPrev->nHeight+1 ) + if ( Mining_height != pindexPrev->GetHeight()+1 ) { - Mining_height = pindexPrev->nHeight+1; + Mining_height = pindexPrev->GetHeight()+1; Mining_start = (uint32_t)time(NULL); } @@ -924,7 +924,7 @@ void static VerusStaker(CWallet *pwallet) if ( pindexPrev != chainActive.LastTip() ) { - printf("Block %d added to chain\n", chainActive.LastTip()->nHeight); + printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight()); MilliSleep(250); continue; } @@ -997,7 +997,7 @@ void static BitcoinMiner_noeq() solnPlaceholder.resize(Eh200_9.SolutionWidth); uint8_t *script; uint64_t total,checktoshis; int32_t i,j; - while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 && + while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && { sleep(1); if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) @@ -1032,7 +1032,7 @@ void static BitcoinMiner_noeq() sleep(1); // prevent forking on startup before the diff algorithm kicks in - if (pindexPrev->nHeight < 50 || pindexPrev != chainActive.LastTip()) + if (pindexPrev->GetHeight() < 50 || pindexPrev != chainActive.LastTip()) { do { pindexPrev = chainActive.LastTip(); @@ -1042,9 +1042,9 @@ void static BitcoinMiner_noeq() // Create new block unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - if ( Mining_height != pindexPrev->nHeight+1 ) + if ( Mining_height != pindexPrev->GetHeight()+1 ) { - Mining_height = pindexPrev->nHeight+1; + Mining_height = pindexPrev->GetHeight()+1; Mining_start = (uint32_t)time(NULL); } @@ -1116,7 +1116,7 @@ void static BitcoinMiner_noeq() if (lastChainTipPrinted != chainActive.LastTip()) { lastChainTipPrinted = chainActive.LastTip(); - printf("Block %d added to chain\n", lastChainTipPrinted->nHeight); + printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); } MilliSleep(250); continue; @@ -1191,7 +1191,7 @@ void static BitcoinMiner_noeq() if (lastChainTipPrinted != chainActive.LastTip()) { lastChainTipPrinted = chainActive.LastTip(); - printf("Block %d added to chain\n", lastChainTipPrinted->nHeight); + printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); } break; } @@ -1227,7 +1227,7 @@ void static BitcoinMiner_noeq() if (lastChainTipPrinted != chainActive.LastTip()) { lastChainTipPrinted = chainActive.LastTip(); - printf("Block %d added to chain\n", lastChainTipPrinted->nHeight); + printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); } break; } @@ -1285,7 +1285,7 @@ void static BitcoinMiner() break; } if ( ASSETCHAINS_SYMBOL[0] == 0 ) - komodo_chosennotary(¬aryid,chainActive.LastTip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime()); + komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime()); if ( notaryid != My_notaryid ) My_notaryid = notaryid; std::string solver; @@ -1311,9 +1311,9 @@ void static BitcoinMiner() fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); while (true) { - if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->nHeight != 235300 && + if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 && { - //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->nHeight < 100 ) + //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 ) // break; // Busy-wait for the network to come online so we don't waste time mining // on an obsolete chain. In regtest mode we expect to fly solo. @@ -1338,9 +1338,9 @@ void static BitcoinMiner() // unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrev = chainActive.LastTip(); - if ( Mining_height != pindexPrev->nHeight+1 ) + if ( Mining_height != pindexPrev->GetHeight()+1 ) { - Mining_height = pindexPrev->nHeight+1; + Mining_height = pindexPrev->GetHeight()+1; Mining_start = (uint32_t)time(NULL); } if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 ) @@ -1351,7 +1351,7 @@ void static BitcoinMiner() #ifdef ENABLE_WALLET // notaries always default to staking - CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->nHeight+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0); + CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0); #else CBlockTemplate *ptr = CreateNewBlockWithKey(); #endif @@ -1409,7 +1409,7 @@ void static BitcoinMiner() int32_t dispflag = 0; if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 ) dispflag = 1; - komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight); + komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight()); if ( nonzpkeys > 0 ) { for (i=0; i<33; i++) @@ -1437,7 +1437,7 @@ void static BitcoinMiner() gpucount++; } if ( dispflag != 0 ) - fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL)); + fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->GetHeight(),notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL)); } for (j=0; j<65; j++) if ( mids[j] == notaryid ) @@ -1448,7 +1448,7 @@ void static BitcoinMiner() if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) ) { HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS); - fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1); + fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1); } //else fprintf(stderr,"duplicate at j.%d\n",j); } else Mining_start = 0; } else Mining_start = 0; @@ -1529,7 +1529,7 @@ void static BitcoinMiner() while ( GetAdjustedTime() < B.nTime-2 ) { sleep(1); - if ( chainActive.LastTip()->nHeight >= Mining_height ) + if ( chainActive.LastTip()->GetHeight() >= Mining_height ) { fprintf(stderr,"new block arrived\n"); return(false); @@ -1550,7 +1550,7 @@ void static BitcoinMiner() while ( B.nTime-57 > GetAdjustedTime() ) { sleep(1); - if ( chainActive.LastTip()->nHeight >= Mining_height ) + if ( chainActive.LastTip()->GetHeight() >= Mining_height ) return(false); } uint256 tmp = B.GetHash(); diff --git a/src/pow.cpp b/src/pow.cpp index 1445f81dc..2c75fef5f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -4,6 +4,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" +#include "consensus/upgrades.h" #include "arith_uint256.h" #include "chain.h" @@ -21,7 +22,7 @@ #endif // ENABLE_RUST uint32_t komodo_chainactive_timestamp(); -extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_STAKED; +extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_STAKED, ASSETCHAINS_LWMAPOS; extern char ASSETCHAINS_SYMBOL[65]; extern int32_t VERUS_BLOCK_POSUNITS, VERUS_CONSECUTIVE_POS_THRESHOLD, VERUS_NOPOS_THRESHHOLD; unsigned int lwmaGetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params); @@ -229,7 +230,7 @@ uint32_t lwmaGetNextPOSRequired(const CBlockIndex* pindexLast, const Consensus:: if (x) { idx[i].consecutive = false; - if (!memcmp(ASSETCHAINS_SYMBOL, "VRSC", 4) && pindexLast->nHeight < 67680) + if (!memcmp(ASSETCHAINS_SYMBOL, "VRSC", 4) && pindexLast->GetHeight() < 67680) { idx[i].solveTime = VERUS_BLOCK_POSUNITS * (x + 1); } @@ -444,33 +445,49 @@ bool CheckProofOfWork(const CBlockHeader &blkHeader, uint8_t *pubkey33, int32_t return true; } -arith_uint256 GetBlockProof(const CBlockIndex& block) +CChainPower GetBlockProof(const CBlockIndex& block) { - arith_uint256 bnTarget; + arith_uint256 bnWorkTarget, bnStakeTarget = arith_uint256(); + bool fNegative; bool fOverflow; - bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); + bnWorkTarget.SetCompact(block.nBits, &fNegative, &fOverflow); + + if (fNegative || fOverflow || bnWorkTarget == 0) + return CChainPower(0); + + CBlockHeader header = block.GetBlockHeader(); + + // if POS block, add stake + if (!NetworkUpgradeActive(block.GetHeight(), Params().GetConsensus(), Consensus::UPGRADE_SAPLING) || !header.IsVerusPOSBlock()) + { + return CChainPower(0, bnStakeTarget, (~bnWorkTarget / (bnWorkTarget + 1)) + 1); + } + else + { + bnStakeTarget.SetCompact(header.GetVerusPOSTarget(), &fNegative, &fOverflow); + if (fNegative || fOverflow || bnWorkTarget == 0) + return CChainPower(0); + } - if (fNegative || fOverflow || bnTarget == 0) - return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. - return (~bnTarget / (bnTarget + 1)) + 1; + return CChainPower(0, (~bnStakeTarget / (bnStakeTarget + 1)) + 1, (~bnWorkTarget / (bnWorkTarget + 1)) + 1); } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; - if (to.nChainWork > from.nChainWork) { - r = to.nChainWork - from.nChainWork; + if (to.chainPower.chainWork > from.chainPower.chainWork) { + r = to.chainPower.chainWork - from.chainPower.chainWork; } else { - r = from.nChainWork - to.nChainWork; + r = from.chainPower.chainWork - to.chainPower.chainWork; sign = -1; } - r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); + r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip).chainWork; if (r.bits() > 63) { return sign * std::numeric_limits::max(); } diff --git a/src/pow.h b/src/pow.h index 8221e8336..0c6c899b8 100644 --- a/src/pow.h +++ b/src/pow.h @@ -6,6 +6,7 @@ #ifndef BITCOIN_POW_H #define BITCOIN_POW_H +#include "chain.h" #include "consensus/params.h" #include @@ -28,7 +29,7 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams&); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ bool CheckProofOfWork(const CBlockHeader &blkHeader, uint8_t *pubkey33, int32_t height, const Consensus::Params& params); -arith_uint256 GetBlockProof(const CBlockIndex& block); +CChainPower GetBlockProof(const CBlockIndex& block); /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&); diff --git a/src/primitives/block.cpp b/src/primitives/block.cpp index 83a283170..5c0770ff0 100644 --- a/src/primitives/block.cpp +++ b/src/primitives/block.cpp @@ -45,7 +45,8 @@ void CBlockHeader::SetVerusHash() CBlockHeader::hashFunction = &CBlockHeader::GetVerusHash; } -// returns false if unable to fast calculate the VerusPOSHash from the header. it can still be calculated from the block +// returns false if unable to fast calculate the VerusPOSHash from the header. +// if it returns false, value is set to 0, but it can still be calculated from the full block // in that case. the only difference between this and the POS hash for the contest is that it is not divided by the value out // this is used as a source of entropy bool CBlockHeader::GetRawVerusPOSHash(uint256 &value, int32_t nHeight) const @@ -53,7 +54,10 @@ bool CBlockHeader::GetRawVerusPOSHash(uint256 &value, int32_t nHeight) const // if below the required height or no storage space in the solution, we can't get // a cached txid value to calculate the POSHash from the header if (!(CPOSNonce::NewNonceActive(nHeight) && IsVerusPOSBlock())) + { + value = uint256(); return false; + } // if we can calculate, this assumes the protocol that the POSHash calculation is: // hashWriter << ASSETCHAINS_MAGIC; diff --git a/src/primitives/block.h b/src/primitives/block.h index aad5f705c..77be88cf0 100644 --- a/src/primitives/block.h +++ b/src/primitives/block.h @@ -85,6 +85,7 @@ public: static void SetVerusHash(); bool GetRawVerusPOSHash(uint256 &value, int32_t nHeight) const; + uint256 GetVerusEntropyHash(int32_t nHeight) const; uint256 GetVerusV2Hash() const; diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp index 064d7c7f0..fff573496 100644 --- a/src/primitives/transaction.cpp +++ b/src/primitives/transaction.cpp @@ -302,6 +302,7 @@ CAmount CTransaction::GetValueOut() const return nValueOut; } +// SAPLINGTODO: make this accurate for all transactions, including sapling CAmount CTransaction::GetShieldedValueIn() const { CAmount nValue = 0; diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index d9b462fdd..280e7a173 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -117,9 +117,9 @@ UniValue blockheaderToJSON(const CBlockIndex* blockindex) int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) - confirmations = chainActive.Height() - blockindex->nHeight + 1; + confirmations = chainActive.Height() - blockindex->GetHeight() + 1; result.push_back(Pair("confirmations", confirmations)); - result.push_back(Pair("height", blockindex->nHeight)); + result.push_back(Pair("height", blockindex->GetHeight())); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("finalsaplingroot", blockindex->hashFinalSaplingRoot.GetHex())); @@ -128,7 +128,7 @@ UniValue blockheaderToJSON(const CBlockIndex* blockindex) result.push_back(Pair("solution", HexStr(blockindex->nSolution))); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); - result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); + result.push_back(Pair("chainwork", blockindex->chainPower.chainWork.GetHex())); result.push_back(Pair("segid", (int64_t)blockindex->segid)); if (blockindex->pprev) @@ -146,13 +146,13 @@ UniValue blockToDeltasJSON(const CBlock& block, const CBlockIndex* blockindex) int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) { - confirmations = chainActive.Height() - blockindex->nHeight + 1; + confirmations = chainActive.Height() - blockindex->GetHeight() + 1; } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block is an orphan"); } 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)); + result.push_back(Pair("height", blockindex->GetHeight())); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("segid", (int64_t)blockindex->segid)); @@ -249,7 +249,7 @@ UniValue blockToDeltasJSON(const CBlock& block, const CBlockIndex* blockindex) result.push_back(Pair("nonce", block.nNonce.GetHex())); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); - result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); + result.push_back(Pair("chainwork", blockindex->chainPower.chainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); @@ -266,10 +266,10 @@ UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool tx int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) - confirmations = chainActive.Height() - blockindex->nHeight + 1; + confirmations = chainActive.Height() - blockindex->GetHeight() + 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)); + result.push_back(Pair("height", blockindex->GetHeight())); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("segid", (int64_t)blockindex->segid)); @@ -292,7 +292,7 @@ UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool tx result.push_back(Pair("solution", HexStr(block.nSolution))); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); - result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); + result.push_back(Pair("chainwork", blockindex->chainPower.chainWork.GetHex())); result.push_back(Pair("anchor", blockindex->hashFinalSproutRoot.GetHex())); result.push_back(Pair("blocktype", block.IsVerusPOSBlock() ? "minted" : "mined")); @@ -819,6 +819,7 @@ UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) #define KOMODO_KVDURATION 1440 #define KOMODO_KVBINARY 2 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; +extern int32_t ASSETCHAINS_LWMAPOS; uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uint64_t basevolume); int32_t komodo_paxprices(int32_t *heights,uint64_t *prices,int32_t max,char *base,char *rel); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); @@ -856,13 +857,13 @@ UniValue kvsearch(const UniValue& params, bool fHelp) if ( (keylen= (int32_t)strlen(params[0].get_str().c_str())) > 0 ) { ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL))); - ret.push_back(Pair("currentheight", (int64_t)chainActive.LastTip()->nHeight)); + ret.push_back(Pair("currentheight", (int64_t)chainActive.LastTip()->GetHeight())); ret.push_back(Pair("key",params[0].get_str())); ret.push_back(Pair("keylen",keylen)); if ( keylen < sizeof(key) ) { memcpy(key,params[0].get_str().c_str(),keylen); - if ( (valuesize= komodo_kvsearch(&refpubkey,chainActive.LastTip()->nHeight,&flags,&height,value,key,keylen)) >= 0 ) + if ( (valuesize= komodo_kvsearch(&refpubkey,chainActive.LastTip()->GetHeight(),&flags,&height,value,key,keylen)) >= 0 ) { std::string val; char *valuestr; val.resize(valuesize); @@ -890,7 +891,7 @@ UniValue minerids(const UniValue& params, bool fHelp) LOCK(cs_main); int32_t height = atoi(params[0].get_str().c_str()); if ( height <= 0 ) - height = chainActive.LastTip()->nHeight; + height = chainActive.LastTip()->GetHeight(); else { CBlockIndex *pblockindex = chainActive[height]; @@ -952,7 +953,7 @@ UniValue notaries(const UniValue& params, bool fHelp) else timestamp = (uint32_t)time(NULL); if ( height < 0 ) { - height = chainActive.LastTip()->nHeight; + height = chainActive.LastTip()->GetHeight(); timestamp = chainActive.LastTip()->GetBlockTime(); } else if ( params.size() < 2 ) @@ -1041,7 +1042,7 @@ UniValue paxprice(const UniValue& params, bool fHelp) std::string rel = params[1].get_str(); int32_t height; if ( params.size() == 2 ) - height = chainActive.LastTip()->nHeight; + height = chainActive.LastTip()->GetHeight(); else height = atoi(params[2].get_str().c_str()); //if ( params.size() == 3 || (basevolume= COIN * atof(params[3].get_str().c_str())) == 0 ) basevolume = 100000; @@ -1175,10 +1176,10 @@ UniValue gettxout(const UniValue& params, bool fHelp) ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); - else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); + else ret.push_back(Pair("confirmations", pindex->GetHeight() - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); uint64_t interest; int32_t txheight; uint32_t locktime; - if ( (interest= komodo_accrued_interest(&txheight,&locktime,hash,n,coins.nHeight,coins.vout[n].nValue,(int32_t)pindex->nHeight)) != 0 ) + if ( (interest= komodo_accrued_interest(&txheight,&locktime,hash,n,coins.nHeight,coins.vout[n].nValue,(int32_t)pindex->GetHeight())) != 0 ) ret.push_back(Pair("interest", ValueFromAmount(interest))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); @@ -1338,11 +1339,15 @@ UniValue getblockchaininfo(const UniValue& params, bool fHelp) UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); - obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); + obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->GetHeight() : -1)); obj.push_back(Pair("bestblockhash", chainActive.LastTip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetNetworkDifficulty())); obj.push_back(Pair("verificationprogress", progress)); - obj.push_back(Pair("chainwork", chainActive.LastTip()->nChainWork.GetHex())); + obj.push_back(Pair("chainwork", chainActive.LastTip()->chainPower.chainWork.GetHex())); + if (ASSETCHAINS_LWMAPOS) + { + obj.push_back(Pair("chainstake", chainActive.LastTip()->chainPower.chainStake.GetHex())); + } obj.push_back(Pair("pruned", fPruneMode)); SproutMerkleTree tree; @@ -1364,13 +1369,13 @@ UniValue getblockchaininfo(const UniValue& params, bool fHelp) UniValue upgrades(UniValue::VOBJ); for (int i = Consensus::UPGRADE_OVERWINTER; i < Consensus::MAX_NETWORK_UPGRADES; i++) { - NetworkUpgradeDescPushBack(upgrades, consensusParams, Consensus::UpgradeIndex(i), tip->nHeight); + NetworkUpgradeDescPushBack(upgrades, consensusParams, Consensus::UpgradeIndex(i), tip->GetHeight()); } obj.push_back(Pair("upgrades", upgrades)); UniValue consensus(UniValue::VOBJ); - consensus.push_back(Pair("chaintip", HexInt(CurrentEpochBranchId(tip->nHeight, consensusParams)))); - consensus.push_back(Pair("nextblock", HexInt(CurrentEpochBranchId(tip->nHeight + 1, consensusParams)))); + consensus.push_back(Pair("chaintip", HexInt(CurrentEpochBranchId(tip->GetHeight(), consensusParams)))); + consensus.push_back(Pair("nextblock", HexInt(CurrentEpochBranchId(tip->GetHeight() + 1, consensusParams)))); obj.push_back(Pair("consensus", consensus)); if (fPruneMode) @@ -1379,7 +1384,7 @@ UniValue getblockchaininfo(const UniValue& params, bool fHelp) while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; - obj.push_back(Pair("pruneheight", block->nHeight)); + obj.push_back(Pair("pruneheight", block->GetHeight())); } return obj; } @@ -1392,8 +1397,8 @@ struct CompareBlocksByHeight /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ - if (a->nHeight != b->nHeight) - return (a->nHeight > b->nHeight); + if (a->GetHeight() != b->GetHeight()) + return (a->GetHeight() > b->GetHeight()); return a < b; } @@ -1458,12 +1463,12 @@ UniValue getchaintips(const UniValue& params, bool fHelp) BOOST_FOREACH(const CBlockIndex* block, setTips) { UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("height", block->nHeight)); + obj.push_back(Pair("height", block->GetHeight())); obj.push_back(Pair("hash", block->phashBlock->GetHex())); forked = chainActive.FindFork(block); if ( forked != 0 ) { - const int branchLen = block->nHeight - forked->nHeight; + const int branchLen = block->GetHeight() - forked->GetHeight(); obj.push_back(Pair("branchlen", branchLen)); string status; diff --git a/src/rpc/crosschain.cpp b/src/rpc/crosschain.cpp index b0d9c674b..7e113f330 100644 --- a/src/rpc/crosschain.cpp +++ b/src/rpc/crosschain.cpp @@ -68,7 +68,7 @@ UniValue height_MoM(const UniValue& params, bool fHelp) ret.push_back(Pair("error",(char *)"no active chain yet")); return(ret); } - height = chainActive.Tip()->nHeight; + height = chainActive.Tip()->GetHeight(); } //fprintf(stderr,"height_MoM height.%d\n",height); depth = komodo_MoM(¬arized_height,&MoM,&kmdtxid,height,&MoMoM,&MoMoMoffset,&MoMoMdepth,&kmdstarti,&kmdendi); diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index feb747a60..51d29b5ea 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -49,7 +49,7 @@ int64_t GetNetworkHashPS(int lookup, int height) { if (height >= 0 && height < chainActive.Height()) pb = chainActive[height]; - if (pb == NULL || !pb->nHeight) + if (pb == NULL || !pb->GetHeight()) return 0; // If lookup is nonpositive, then use difficulty averaging window. @@ -57,8 +57,8 @@ int64_t GetNetworkHashPS(int lookup, int height) { lookup = Params().GetConsensus().nPowAveragingWindow; // If lookup is larger than chain, then set it to chain length. - if (lookup > pb->nHeight) - lookup = pb->nHeight; + if (lookup > pb->GetHeight()) + lookup = pb->GetHeight(); CBlockIndex *pb0 = pb; int64_t minTime = pb0->GetBlockTime(); @@ -74,7 +74,7 @@ int64_t GetNetworkHashPS(int lookup, int height) { if (minTime == maxTime) return 0; - arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork; + arith_uint256 workDiff = pb->chainPower.chainWork - pb0->chainPower.chainWork; int64_t timeDiff = maxTime - minTime; return (int64_t)(workDiff.getdouble() / timeDiff); @@ -273,7 +273,7 @@ UniValue generate(const UniValue& params, bool fHelp) } endloop: CValidationState state; - if (!ProcessNewBlock(1,chainActive.LastTip()->nHeight+1,state, NULL, pblock, true, NULL)) + if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL)) throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted"); ++nHeight; blockHashes.push_back(pblock->GetHash().GetHex()); @@ -657,7 +657,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp) } #ifdef ENABLE_WALLET CReserveKey reservekey(pwalletMain); - pblocktemplate = CreateNewBlockWithKey(reservekey,chainActive.LastTip()->nHeight+1,KOMODO_MAXGPUCOUNT); + pblocktemplate = CreateNewBlockWithKey(reservekey,chainActive.LastTip()->GetHeight()+1,KOMODO_MAXGPUCOUNT); #else pblocktemplate = CreateNewBlockWithKey(); #endif @@ -710,7 +710,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp) // Correct this if GetBlockTemplate changes the order // entry.push_back(Pair("foundersreward", (int64_t)tx.vout[1].nValue)); //} - CAmount nReward = GetBlockSubsidy(chainActive.LastTip()->nHeight+1, Params().GetConsensus()); + CAmount nReward = GetBlockSubsidy(chainActive.LastTip()->GetHeight()+1, Params().GetConsensus()); entry.push_back(Pair("coinbasevalue", nReward)); entry.push_back(Pair("required", true)); txCoinbase = entry; @@ -748,7 +748,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp) if ( ASSETCHAINS_STAKED != 0 ) { arith_uint256 POWtarget; int32_t PoSperc; - POWtarget = komodo_PoWtarget(&PoSperc,hashTarget,(int32_t)(pindexPrev->nHeight+1),ASSETCHAINS_STAKED); + POWtarget = komodo_PoWtarget(&PoSperc,hashTarget,(int32_t)(pindexPrev->GetHeight()+1),ASSETCHAINS_STAKED); result.push_back(Pair("target", POWtarget.GetHex())); result.push_back(Pair("PoSperc", (int64_t)PoSperc)); result.push_back(Pair("ac_staked", (int64_t)ASSETCHAINS_STAKED)); @@ -761,7 +761,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp) result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", pblock->GetBlockTime())); result.push_back(Pair("bits", strprintf("%08x", pblock->nBits))); - result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); + result.push_back(Pair("height", (int64_t)(pindexPrev->GetHeight()+1))); //fprintf(stderr,"return complete template\n"); return result; @@ -835,7 +835,7 @@ UniValue submitblock(const UniValue& params, bool fHelp) CValidationState state; submitblock_StateCatcher sc(block.GetHash()); RegisterValidationInterface(&sc); - bool fAccepted = ProcessNewBlock(1,chainActive.LastTip()->nHeight+1,state, NULL, &block, true, NULL); + bool fAccepted = ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, &block, true, NULL); UnregisterValidationInterface(&sc); if (fBlockPresent) { diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index 2613fa3aa..2a871460f 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -56,7 +56,7 @@ uint32_t komodo_segid32(char *coinaddr); int64_t komodo_coinsupply(int64_t *zfundsp,int32_t height); int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heightp); #define KOMODO_VERSION "0.2.1" -#define VERUS_VERSION "0.3.13" +#define VERUS_VERSION "0.3.2" extern uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT; extern uint32_t ASSETCHAINS_CC; extern uint32_t ASSETCHAINS_MAGIC; @@ -156,7 +156,7 @@ UniValue getinfo(const UniValue& params, bool fHelp) obj.push_back(Pair("errors", GetWarnings("statusbar"))); { char pubkeystr[65]; int32_t notaryid; - if ( (notaryid= komodo_whoami(pubkeystr,(int32_t)chainActive.LastTip()->nHeight,komodo_chainactive_timestamp())) >= 0 ) + if ( (notaryid= komodo_whoami(pubkeystr,(int32_t)chainActive.LastTip()->GetHeight(),komodo_chainactive_timestamp())) >= 0 ) { obj.push_back(Pair("notaryid", notaryid)); obj.push_back(Pair("pubkey", pubkeystr)); diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index f4fbbc058..8297e2cb6 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -233,7 +233,7 @@ void TxToJSONExpanded(const CTransaction& tx, const uint256 hashBlock, UniValue& if ( ASSETCHAINS_SYMBOL[0] == 0 && pindex != 0 && tx.nLockTime >= 500000000 && (tipindex= chainActive.LastTip()) != 0 ) { int64_t interest; int32_t txheight; uint32_t locktime; - interest = komodo_accrued_interest(&txheight,&locktime,tx.GetHash(),i,0,txout.nValue,(int32_t)tipindex->nHeight); + interest = komodo_accrued_interest(&txheight,&locktime,tx.GetHash(),i,0,txout.nValue,(int32_t)tipindex->GetHeight()); out.push_back(Pair("interest", ValueFromAmount(interest))); } out.push_back(Pair("valueSat", txout.nValue)); // [+] Decker @@ -325,7 +325,7 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) if ( ASSETCHAINS_SYMBOL[0] == 0 && pindex != 0 && tx.nLockTime >= 500000000 && (tipindex= chainActive.LastTip()) != 0 ) { int64_t interest; int32_t txheight; uint32_t locktime; - interest = komodo_accrued_interest(&txheight,&locktime,tx.GetHash(),i,0,txout.nValue,(int32_t)tipindex->nHeight); + interest = komodo_accrued_interest(&txheight,&locktime,tx.GetHash(),i,0,txout.nValue,(int32_t)tipindex->GetHeight()); out.push_back(Pair("interest", ValueFromAmount(interest))); } out.push_back(Pair("valueZat", txout.nValue)); @@ -357,7 +357,7 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { - entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight)); + entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->GetHeight())); entry.push_back(Pair("time", pindex->GetBlockTime())); entry.push_back(Pair("blocktime", pindex->GetBlockTime())); } @@ -483,8 +483,8 @@ UniValue getrawtransaction(const UniValue& params, bool fHelp) if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { - nHeight = pindex->nHeight; - nConfirmations = 1 + chainActive.Height() - pindex->nHeight; + nHeight = pindex->GetHeight(); + nConfirmations = 1 + chainActive.Height() - pindex->GetHeight(); nBlockTime = pindex->GetBlockTime(); } else { nHeight = -1; diff --git a/src/test-komodo/test_eval_bet.cpp b/src/test-komodo/test_eval_bet.cpp index 4dfcf1cab..d7248058c 100644 --- a/src/test-komodo/test_eval_bet.cpp +++ b/src/test-komodo/test_eval_bet.cpp @@ -225,7 +225,7 @@ public: eval.txs[sessionTx.GetHash()] = sessionTx; CBlockIndex sessionBlock; - sessionBlock.nHeight = 10; + sessionBlock.SetHeight(10); eval.blocks[sessionTx.GetHash()] = sessionBlock; std::vector sessionSpends; diff --git a/src/test-komodo/test_eval_notarisation.cpp b/src/test-komodo/test_eval_notarisation.cpp index 68da7d990..0abac499d 100644 --- a/src/test-komodo/test_eval_notarisation.cpp +++ b/src/test-komodo/test_eval_notarisation.cpp @@ -77,7 +77,7 @@ namespace TestEvalNotarisation { modify(notary); eval.txs[notary.GetHash()] = CTransaction(notary); - eval.blocks[notary.GetHash()].nHeight = 780060; + eval.blocks[notary.GetHash()].SetHeight(780060); eval.blocks[notary.GetHash()].nTime = 1522946781; } diff --git a/src/test/alert_tests.cpp b/src/test/alert_tests.cpp index a0b49b4dd..533b8f1ef 100644 --- a/src/test/alert_tests.cpp +++ b/src/test/alert_tests.cpp @@ -402,7 +402,7 @@ BOOST_AUTO_TEST_CASE(PartitionAlert) indexDummy[i].phashBlock = NULL; if (i == 0) indexDummy[i].pprev = NULL; else indexDummy[i].pprev = &indexDummy[i-1]; - indexDummy[i].nHeight = i; + indexDummy[i].SetHeight(i); indexDummy[i].nTime = now - (400-i)*nPowTargetSpacing; // Other members don't matter, the partition check code doesn't // use them diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index 3407fb62c..6d80fc4b7 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -387,13 +387,13 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) // subsidy changing int nHeight = chainActive.Height(); - chainActive.Tip()->nHeight = 209999; + chainActive.Tip()->SetHeight(209999); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1)); delete pblocktemplate; - chainActive.Tip()->nHeight = 210000; + chainActive.Tip()->SetHeight(210000); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1)); delete pblocktemplate; - chainActive.Tip()->nHeight = nHeight; + chainActive.Tip()->SetHeight(nHeight); // non-final txs in mempool SetMockTime(chainActive.Tip()->GetMedianTimePast()+1); @@ -404,7 +404,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) tx.vin[0].nSequence = 0; tx.vout[0].nValue = 49000LL; tx.vout[0].scriptPubKey = CScript() << OP_1; - tx.nLockTime = chainActive.Tip()->nHeight+1; + tx.nLockTime = chainActive.Tip()->GetHeight()+1; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK(!CheckFinalTx(tx, LOCKTIME_MEDIAN_TIME_PAST)); @@ -430,7 +430,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) delete pblocktemplate; // However if we advance height and time by one, both will. - chainActive.Tip()->nHeight++; + chainActive.Tip()->SetHeight(chainActive.Tip()->GetHeight() + 1); SetMockTime(chainActive.Tip()->GetMedianTimePast()+2); // FIXME: we should *actually* create a new block so the following test @@ -442,7 +442,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 2); delete pblocktemplate; - chainActive.Tip()->nHeight--; + chainActive.Tip()->SetHeight(chainActive.Tip()->GetHeight() - 1); SetMockTime(0); mempool.clear(); diff --git a/src/test/pow_tests.cpp b/src/test/pow_tests.cpp index 46abcb431..8837a43c8 100644 --- a/src/test/pow_tests.cpp +++ b/src/test/pow_tests.cpp @@ -78,10 +78,12 @@ BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test) std::vector blocks(10000); for (int i = 0; i < 10000; i++) { blocks[i].pprev = i ? &blocks[i - 1] : NULL; - blocks[i].nHeight = i; + blocks[i].SetHeight(i); blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing; blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */ - blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0); + blocks[i].chainPower = CChainPower(&blocks[i]); + if (i != 0) + blocks[i].chainPower += GetBlockProof(blocks[i - 1]); } for (int j = 0; j < 1000; j++) { diff --git a/src/test/rpc_wallet_tests.cpp b/src/test/rpc_wallet_tests.cpp index 25b5e68a2..678f54313 100644 --- a/src/test/rpc_wallet_tests.cpp +++ b/src/test/rpc_wallet_tests.cpp @@ -1291,7 +1291,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_taddr_to_sapling) block.hashMerkleRoot = block.BuildMerkleTree(); auto blockHash = block.GetHash(); CBlockIndex fakeIndex {block}; - fakeIndex.nHeight = 1; + fakeIndex.SetHeight(1); mapBlockIndex.insert(std::make_pair(blockHash, &fakeIndex)); chainActive.SetTip(&fakeIndex); BOOST_CHECK(chainActive.Contains(&fakeIndex)); diff --git a/src/test/skiplist_tests.cpp b/src/test/skiplist_tests.cpp index 86a4bc672..3c33db168 100644 --- a/src/test/skiplist_tests.cpp +++ b/src/test/skiplist_tests.cpp @@ -20,15 +20,15 @@ BOOST_AUTO_TEST_CASE(skiplist_test) std::vector vIndex(SKIPLIST_LENGTH); for (int i=0; i 0) { - BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]); - BOOST_CHECK(vIndex[i].pskip->nHeight < i); + BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->GetHeight()]); + BOOST_CHECK(vIndex[i].pskip->GetHeight() < i); } else { BOOST_CHECK(vIndex[i].pskip == NULL); } @@ -51,12 +51,12 @@ BOOST_AUTO_TEST_CASE(getlocator_test) std::vector vBlocksMain(100000); for (unsigned int i=0; inHeight + 1); + BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksMain[i].GetBlockHash()).GetLow64(), vBlocksMain[i].GetHeight()); + BOOST_CHECK(vBlocksMain[i].pprev == NULL || vBlocksMain[i].GetHeight() == vBlocksMain[i].pprev->GetHeight() + 1); } // Build a branch that splits off at block 49999, 50000 blocks long. @@ -64,12 +64,12 @@ BOOST_AUTO_TEST_CASE(getlocator_test) std::vector vBlocksSide(50000); for (unsigned int i=0; inHeight + 1); + BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksSide[i].GetBlockHash()).GetLow64(), vBlocksSide[i].GetHeight()); + BOOST_CHECK(vBlocksSide[i].pprev == NULL || vBlocksSide[i].GetHeight() == vBlocksSide[i].pprev->GetHeight() + 1); } // Build a CChain for the main branch. @@ -88,7 +88,7 @@ BOOST_AUTO_TEST_CASE(getlocator_test) // Entries 1 through 11 (inclusive) go back one step each. for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) { - BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i]).GetLow64(), tip->nHeight - i); + BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i]).GetLow64(), tip->GetHeight() - i); } // The further ones (excluding the last one) go back with exponential steps. diff --git a/src/txdb.cpp b/src/txdb.cpp index 9ce14b308..ba437b5ff 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -261,7 +261,7 @@ bool CCoinsViewDB::GetStats(CCoinsStats &stats) const { } { LOCK(cs_main); - stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; + stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->GetHeight(); } stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; @@ -675,7 +675,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); - pindexNew->nHeight = diskindex.nHeight; + pindexNew->SetHeight(diskindex.GetHeight()); pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; @@ -700,8 +700,8 @@ bool CBlockTreeDB::LoadBlockIndexGuts() if ( 0 ) // POW will be checked before any block is connected { uint8_t pubkey33[33]; - komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->nHeight); - if (!CheckProofOfWork(header,pubkey33,pindexNew->nHeight,Params().GetConsensus())) + komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->GetHeight()); + if (!CheckProofOfWork(header,pubkey33,pindexNew->GetHeight(),Params().GetConsensus())) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); } pcursor->Next(); diff --git a/src/txmempool.cpp b/src/txmempool.cpp index e3c18552e..518fdf278 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -488,7 +488,7 @@ void CTxMemPool::removeExpired(unsigned int nBlockHeight) { const CTransaction& tx = it->GetTx(); tipindex = chainActive.LastTip(); - if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->nHeight+1,tipindex->GetMedianTimePast() + 777,0)) < 0) + if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0) { transactionsToRemove.push_back(tx); } diff --git a/src/wallet-utility.cpp b/src/wallet-utility.cpp index 6889d4cc1..9eea714ac 100644 --- a/src/wallet-utility.cpp +++ b/src/wallet-utility.cpp @@ -21,6 +21,8 @@ uint32_t ASSETCHAINS_VERUSHASH = 1; uint32_t ASSETCHAINS_ALGO = 0; int32_t ASSETCHAINS_LWMAPOS = 0; int32_t VERUS_BLOCK_POSUNITS = 1000; +int32_t ASSETCHAINS_OVERWINTER = 227520 - 120; +int32_t ASSETCHAINS_SAPLING = 227520; unsigned int MAX_BLOCK_SIGOPS = 20000; diff --git a/src/wallet/asyncrpcoperation_mergetoaddress.cpp b/src/wallet/asyncrpcoperation_mergetoaddress.cpp index 8c8276340..01a5cd261 100644 --- a/src/wallet/asyncrpcoperation_mergetoaddress.cpp +++ b/src/wallet/asyncrpcoperation_mergetoaddress.cpp @@ -521,7 +521,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() if (mapBlockIndex.find(wtx.hashBlock) == mapBlockIndex.end()) { throw JSONRPCError(RPC_WALLET_ERROR, strprintf("mapBlockIndex does not contain block hash %s", wtx.hashBlock.ToString())); } - wtxHeight = mapBlockIndex[wtx.hashBlock]->nHeight; + wtxHeight = mapBlockIndex[wtx.hashBlock]->GetHeight(); wtxDepth = wtx.GetDepthInMainChain(); } LogPrint("zrpcunsafe", "%s: spending note (txid=%s, vjoinsplit=%d, ciphertext=%d, amount=%s, height=%d, confirmations=%d)\n", diff --git a/src/wallet/asyncrpcoperation_sendmany.cpp b/src/wallet/asyncrpcoperation_sendmany.cpp index 677476d02..d328fe25e 100644 --- a/src/wallet/asyncrpcoperation_sendmany.cpp +++ b/src/wallet/asyncrpcoperation_sendmany.cpp @@ -808,7 +808,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { if (mapBlockIndex.find(wtx.hashBlock) == mapBlockIndex.end()) { throw JSONRPCError(RPC_WALLET_ERROR, strprintf("mapBlockIndex does not contain block hash %s", wtx.hashBlock.ToString())); } - wtxHeight = mapBlockIndex[wtx.hashBlock]->nHeight; + wtxHeight = mapBlockIndex[wtx.hashBlock]->GetHeight(); wtxDepth = wtx.GetDepthInMainChain(); } LogPrint("zrpcunsafe", "%s: spending note (txid=%s, vjoinsplit=%d, ciphertext=%d, amount=%s, height=%d, confirmations=%d)\n", diff --git a/src/wallet/gtest/test_wallet.cpp b/src/wallet/gtest/test_wallet.cpp index a67c3b491..e1aa641d2 100644 --- a/src/wallet/gtest/test_wallet.cpp +++ b/src/wallet/gtest/test_wallet.cpp @@ -243,7 +243,7 @@ TEST(WalletTests, FindUnspentSproutNotes) { auto blockHash2 = block2.GetHash(); CBlockIndex fakeIndex2 {block2}; mapBlockIndex.insert(std::make_pair(blockHash2, &fakeIndex2)); - fakeIndex2.nHeight = 1; + fakeIndex2.SetHeight(1); chainActive.SetTip(&fakeIndex2); EXPECT_TRUE(chainActive.Contains(&fakeIndex2)); EXPECT_EQ(1, chainActive.Height()); @@ -302,7 +302,7 @@ TEST(WalletTests, FindUnspentSproutNotes) { auto blockHash3 = block3.GetHash(); CBlockIndex fakeIndex3 {block3}; mapBlockIndex.insert(std::make_pair(blockHash3, &fakeIndex3)); - fakeIndex3.nHeight = 2; + fakeIndex3.SetHeight(2); chainActive.SetTip(&fakeIndex3); EXPECT_TRUE(chainActive.Contains(&fakeIndex3)); EXPECT_EQ(2, chainActive.Height()); @@ -1136,7 +1136,7 @@ TEST(WalletTests, SpentSaplingNoteIsFromMe) { auto blockHash2 = block2.GetHash(); CBlockIndex fakeIndex2 {block2}; mapBlockIndex.insert(std::make_pair(blockHash2, &fakeIndex2)); - fakeIndex2.nHeight = 1; + fakeIndex2.SetHeight(1); chainActive.SetTip(&fakeIndex2); EXPECT_TRUE(chainActive.Contains(&fakeIndex2)); EXPECT_EQ(1, chainActive.Height()); @@ -1236,7 +1236,7 @@ TEST(WalletTests, CachedWitnessesChainTip) { { // First block (case tested in _empty_chain) CBlockIndex index1(block1); - index1.nHeight = 1; + index1.SetHeight(1); auto outpts = CreateValidBlock(wallet, sk, index1, block1, sproutTree, saplingTree); // Called to fetch anchor @@ -1277,7 +1277,7 @@ TEST(WalletTests, CachedWitnessesChainTip) { block2.hashPrevBlock = block1.GetHash(); block2.vtx.push_back(wtx); CBlockIndex index2(block2); - index2.nHeight = 2; + index2.SetHeight(2); SproutMerkleTree sproutTree2 {sproutTree}; SaplingMerkleTree saplingTree2 {saplingTree}; wallet.IncrementNoteWitnesses(&index2, &block2, sproutTree2, saplingTree2); @@ -1337,7 +1337,7 @@ TEST(WalletTests, CachedWitnessesDecrementFirst) { // First block (case tested in _empty_chain) CBlock block1; CBlockIndex index1(block1); - index1.nHeight = 1; + index1.SetHeight(1); CreateValidBlock(wallet, sk, index1, block1, sproutTree, saplingTree); } @@ -1347,7 +1347,7 @@ TEST(WalletTests, CachedWitnessesDecrementFirst) { { // Second block (case tested in _chain_tip) - index2.nHeight = 2; + index2.SetHeight(2); auto outpts = CreateValidBlock(wallet, sk, index2, block2, sproutTree, saplingTree); // Called to fetch anchor @@ -1428,7 +1428,7 @@ TEST(WalletTests, CachedWitnessesCleanIndex) { blocks.resize(numBlocks); indices.resize(numBlocks); for (size_t i = 0; i < numBlocks; i++) { - indices[i].nHeight = i; + indices[i].SetHeight(i); auto oldSproutRoot = sproutTree.root(); auto oldSaplingRoot = saplingTree.root(); auto outpts = CreateValidBlock(wallet, sk, indices[i], blocks[i], sproutTree, saplingTree); diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index e5bb0c427..bd7595ebf 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -362,7 +362,7 @@ UniValue importwallet_impl(const UniValue& params, bool fHelp, bool fImportZKeys if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; - LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); + LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->GetHeight() + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index ddeb1ff7b..273590e9b 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -587,7 +587,7 @@ UniValue kvupdate(const UniValue& params, bool fHelp) valuesize = (int32_t)strlen(params[1].get_str().c_str()); } memcpy(keyvalue,key,keylen); - if ( (refvaluesize= komodo_kvsearch(&refpubkey,chainActive.LastTip()->nHeight,&tmpflags,&height,&keyvalue[keylen],key,keylen)) >= 0 ) + if ( (refvaluesize= komodo_kvsearch(&refpubkey,chainActive.LastTip()->GetHeight(),&tmpflags,&height,&keyvalue[keylen],key,keylen)) >= 0 ) { if ( (tmpflags & KOMODO_KVPROTECTED) != 0 ) { @@ -612,7 +612,7 @@ UniValue kvupdate(const UniValue& params, bool fHelp) // printf("%02x",((uint8_t *)&sig)[i]); //printf(" sig for keylen.%d + valuesize.%d\n",keylen,refvaluesize); ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL))); - height = chainActive.LastTip()->nHeight; + height = chainActive.LastTip()->GetHeight(); if ( memcmp(&zeroes,&refpubkey,sizeof(refpubkey)) != 0 ) ret.push_back(Pair("owner",refpubkey.GetHex())); ret.push_back(Pair("height", (int64_t)height)); @@ -684,7 +684,7 @@ UniValue paxdeposit(const UniValue& params, bool fHelp) int64_t fiatoshis = atof(params[1].get_str().c_str()) * COIN; std::string base = params[2].get_str(); std::string dest; - height = chainActive.LastTip()->nHeight; + height = chainActive.LastTip()->GetHeight(); if ( pax_fiatstatus(&available,&deposited,&issued,&withdrawn,&approved,&redeemed,(char *)base.c_str()) != 0 || available < fiatoshis ) { fprintf(stderr,"available %llu vs fiatoshis %llu\n",(long long)available,(long long)fiatoshis); @@ -1981,7 +1981,7 @@ UniValue listsinceblock(const UniValue& params, bool fHelp) if(params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; - int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1; + int depth = pindex ? (1 + chainActive.Height() - pindex->GetHeight()) : -1; UniValue transactions(UniValue::VARR); @@ -2738,11 +2738,11 @@ UniValue listunspent(const UniValue& params, bool fHelp) uint64_t interest; uint32_t locktime; int32_t txheight; if ( pindex != 0 && (tipindex= chainActive.LastTip()) != 0 ) { - interest = komodo_accrued_interest(&txheight,&locktime,out.tx->GetHash(),out.i,0,nValue,(int32_t)tipindex->nHeight); + interest = komodo_accrued_interest(&txheight,&locktime,out.tx->GetHash(),out.i,0,nValue,(int32_t)tipindex->GetHeight()); //interest = komodo_interest(txheight,nValue,out.tx->nLockTime,tipindex->nTime); entry.push_back(Pair("interest",ValueFromAmount(interest))); } - //fprintf(stderr,"nValue %.8f pindex.%p tipindex.%p locktime.%u txheight.%d pindexht.%d\n",(double)nValue/COIN,pindex,chainActive.LastTip(),locktime,txheight,pindex->nHeight); + //fprintf(stderr,"nValue %.8f pindex.%p tipindex.%p locktime.%u txheight.%d pindexht.%d\n",(double)nValue/COIN,pindex,chainActive.LastTip(),locktime,txheight,pindex->GetHeight()); } entry.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); entry.push_back(Pair("confirmations", out.nDepth)); @@ -2772,8 +2772,8 @@ uint64_t komodo_interestsum() CBlockIndex *tipindex,*pindex = it->second; if ( pindex != 0 && (tipindex= chainActive.LastTip()) != 0 ) { - interest = komodo_accrued_interest(&txheight,&locktime,out.tx->GetHash(),out.i,0,nValue,(int32_t)tipindex->nHeight); - //interest = komodo_interest(pindex->nHeight,nValue,out.tx->nLockTime,tipindex->nTime); + interest = komodo_accrued_interest(&txheight,&locktime,out.tx->GetHash(),out.i,0,nValue,(int32_t)tipindex->GetHeight()); + //interest = komodo_interest(pindex->GetHeight(),nValue,out.tx->nLockTime,tipindex->nTime); sum += interest; } } @@ -3455,7 +3455,7 @@ UniValue z_getnewaddress(const UniValue& params, bool fHelp) if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; - bool allowSapling = (Params().GetConsensus().vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight <= chainActive.LastTip()->nHeight); + bool allowSapling = (Params().GetConsensus().vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight <= chainActive.LastTip()->GetHeight()); std::string defaultType = allowSapling ? ADDR_TYPE_SAPLING : ADDR_TYPE_SPROUT; @@ -4371,7 +4371,7 @@ UniValue z_shieldcoinbase(const UniValue& params, bool fHelp) contextInfo.push_back(Pair("fee", ValueFromAmount(nFee))); // Contextual transaction we will build on - int blockHeight = chainActive.LastTip()->nHeight; + int blockHeight = chainActive.LastTip()->GetHeight(); nextBlockHeight = blockHeight + 1; CMutableTransaction contextualTx = CreateNewContextualCMutableTransaction( Params().GetConsensus(), nextBlockHeight); @@ -4988,7 +4988,7 @@ int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blockt pwalletMain->AvailableCoins(vecOutputs, false, NULL, true); if ( (tipindex= chainActive.Tip()) == 0 ) return(0); - nHeight = tipindex->nHeight + 1; + nHeight = tipindex->GetHeight() + 1; if ( (minage= nHeight*3) > 6000 ) // about 100 blocks minage = 6000; komodo_segids(hashbuf,nHeight-101,100); @@ -5006,7 +5006,7 @@ int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blockt } BOOST_FOREACH(const COutput& out, vecOutputs) { - if ( (tipindex= chainActive.Tip()) == 0 || tipindex->nHeight+1 > nHeight ) + if ( (tipindex= chainActive.Tip()) == 0 || tipindex->GetHeight()+1 > nHeight ) { fprintf(stderr,"chain tip changed during staking loop t.%u counter.%d\n",(uint32_t)time(NULL),counter); return(0); @@ -5037,7 +5037,7 @@ int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blockt block_from_future_rejecttime = (uint32_t)GetAdjustedTime() + 57; for (i=winners=0; inHeight+1 > nHeight ) + if ( (tipindex= chainActive.Tip()) == 0 || tipindex->GetHeight()+1 > nHeight ) { fprintf(stderr,"chain tip changed during staking loop t.%u counter.%d\n",(uint32_t)time(NULL),counter); return(0); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 6aebbef33..8f0c5f044 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -943,8 +943,8 @@ void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex, { LOCK(cs_wallet); for (std::pair& wtxItem : mapWallet) { - ::CopyPreviousWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize); - ::CopyPreviousWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize); + ::CopyPreviousWitnesses(wtxItem.second.mapSproutNoteData, pindex->GetHeight(), nWitnessCacheSize); + ::CopyPreviousWitnesses(wtxItem.second.mapSaplingNoteData, pindex->GetHeight(), nWitnessCacheSize); } if (nWitnessCacheSize < WITNESS_CACHE_SIZE) { @@ -970,13 +970,13 @@ void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex, // Increment existing witnesses for (std::pair& wtxItem : mapWallet) { - ::AppendNoteCommitment(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment); + ::AppendNoteCommitment(wtxItem.second.mapSproutNoteData, pindex->GetHeight(), nWitnessCacheSize, note_commitment); } // If this is our note, witness it if (txIsOurs) { JSOutPoint jsoutpt {hash, i, j}; - ::WitnessNoteIfMine(mapWallet[hash].mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, jsoutpt, sproutTree.witness()); + ::WitnessNoteIfMine(mapWallet[hash].mapSproutNoteData, pindex->GetHeight(), nWitnessCacheSize, jsoutpt, sproutTree.witness()); } } } @@ -987,21 +987,21 @@ void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex, // Increment existing witnesses for (std::pair& wtxItem : mapWallet) { - ::AppendNoteCommitment(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment); + ::AppendNoteCommitment(wtxItem.second.mapSaplingNoteData, pindex->GetHeight(), nWitnessCacheSize, note_commitment); } // If this is our note, witness it if (txIsOurs) { SaplingOutPoint outPoint {hash, i}; - ::WitnessNoteIfMine(mapWallet[hash].mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, outPoint, saplingTree.witness()); + ::WitnessNoteIfMine(mapWallet[hash].mapSaplingNoteData, pindex->GetHeight(), nWitnessCacheSize, outPoint, saplingTree.witness()); } } } // Update witness heights for (std::pair& wtxItem : mapWallet) { - ::UpdateWitnessHeights(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize); - ::UpdateWitnessHeights(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize); + ::UpdateWitnessHeights(wtxItem.second.mapSproutNoteData, pindex->GetHeight(), nWitnessCacheSize); + ::UpdateWitnessHeights(wtxItem.second.mapSaplingNoteData, pindex->GetHeight(), nWitnessCacheSize); } // For performance reasons, we write out the witness cache in @@ -1056,8 +1056,8 @@ void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex) { LOCK(cs_wallet); for (std::pair& wtxItem : mapWallet) { - ::DecrementNoteWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize); - ::DecrementNoteWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize); + ::DecrementNoteWitnesses(wtxItem.second.mapSproutNoteData, pindex->GetHeight(), nWitnessCacheSize); + ::DecrementNoteWitnesses(wtxItem.second.mapSaplingNoteData, pindex->GetHeight(), nWitnessCacheSize); } nWitnessCacheSize -= 1; // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302) @@ -1225,7 +1225,9 @@ bool CWallet::VerusSelectStakeOutput(CBlock *pBlock, arith_uint256 &hashResult, { if (txout.fSpendable && (UintToArith256(txout.tx->GetVerusPOSHash(&(pBlock->nNonce), txout.i, nHeight, pastHash)) <= target) && (txout.nDepth >= VERUS_MIN_STAKEAGE)) { - printf("Found PoS block\nnNonce: %s\n", pBlock->nNonce.GetHex().c_str()); + printf("Found PoS block\nnNonce: %s\n", pBlock->nNonce.GetHex().c_str()); + pBlock->nNonce.SetPOSEntropy(pastHash, txout.tx->GetHash(), txout.i); + printf("new nonce: %s\n", pBlock->nNonce.GetHex().c_str()); // get the smallest winner if (Solver(txout.tx->vout[txout.i].scriptPubKey, whichType, vSolutions) && (whichType == TX_PUBKEY || whichType == TX_PUBKEYHASH) && (!pwinner || pwinner->tx->vout[pwinner->i].nValue > txout.tx->vout[txout.i].nValue)) @@ -1259,7 +1261,7 @@ int32_t CWallet::VerusStakeTransaction(CBlock *pBlock, CMutableTransaction &txNe } bnTarget = lwmaGetNextPOSRequired(tipindex, Params().GetConsensus()); - if (!VerusSelectStakeOutput(pBlock, hashResult, stakeSource, voutNum, tipindex->nHeight + 1, bnTarget) || + if (!VerusSelectStakeOutput(pBlock, hashResult, stakeSource, voutNum, tipindex->GetHeight() + 1, bnTarget) || !Solver(stakeSource.vout[voutNum].scriptPubKey, whichType, vSolutions)) { LogPrintf("Searched for eligible staking transactions, no winners found\n"); @@ -2530,7 +2532,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.LastTip(), false); while (pindex) { - if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) + if (pindex->GetHeight() % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; @@ -2547,7 +2549,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) // state on the path to the tip of our chain assert(pcoinsTip->GetSproutAnchorAt(pindex->hashSproutAnchor, sproutTree)); if (pindex->pprev) { - if (NetworkUpgradeActive(pindex->pprev->nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) { + if (NetworkUpgradeActive(pindex->pprev->GetHeight(), Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) { assert(pcoinsTip->GetSaplingAnchorAt(pindex->pprev->hashFinalSaplingRoot, saplingTree)); } } @@ -2557,7 +2559,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) pindex = chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); - LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex)); + LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->GetHeight(), Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex)); } } ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI @@ -3021,20 +3023,20 @@ void CWallet::AvailableCoins(vector& vCoins, bool fOnlyConfirmed, const if ( KOMODO_EXCHANGEWALLET == 0 ) { uint32_t locktime; int32_t txheight; CBlockIndex *tipindex; - if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.LastTip() != 0 && chainActive.LastTip()->nHeight >= 60000 ) + if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.LastTip() != 0 && chainActive.LastTip()->GetHeight() >= 60000 ) { if ( pcoin->vout[i].nValue >= 10*COIN ) { if ( (tipindex= chainActive.LastTip()) != 0 ) { - komodo_accrued_interest(&txheight,&locktime,wtxid,i,0,pcoin->vout[i].nValue,(int32_t)tipindex->nHeight); + komodo_accrued_interest(&txheight,&locktime,wtxid,i,0,pcoin->vout[i].nValue,(int32_t)tipindex->GetHeight()); interest = komodo_interestnew(txheight,pcoin->vout[i].nValue,locktime,tipindex->nTime); } else interest = 0; - //interest = komodo_interestnew(chainActive.LastTip()->nHeight+1,pcoin->vout[i].nValue,pcoin->nLockTime,chainActive.LastTip()->nTime); + //interest = komodo_interestnew(chainActive.LastTip()->GetHeight()+1,pcoin->vout[i].nValue,pcoin->nLockTime,chainActive.LastTip()->nTime); if ( interest != 0 ) { //printf("wallet nValueRet %.8f += interest %.8f ht.%d lock.%u/%u tip.%u\n",(double)pcoin->vout[i].nValue/COIN,(double)interest/COIN,txheight,locktime,pcoin->nLockTime,tipindex->nTime); - //fprintf(stderr,"wallet nValueRet %.8f += interest %.8f ht.%d lock.%u tip.%u\n",(double)pcoin->vout[i].nValue/COIN,(double)interest/COIN,chainActive.LastTip()->nHeight+1,pcoin->nLockTime,chainActive.LastTip()->nTime); + //fprintf(stderr,"wallet nValueRet %.8f += interest %.8f ht.%d lock.%u tip.%u\n",(double)pcoin->vout[i].nValue/COIN,(double)interest/COIN,chainActive.LastTip()->GetHeight()+1,pcoin->nLockTime,chainActive.LastTip()->nTime); //ptr = (uint64_t *)&pcoin->vout[i].nValue; //(*ptr) += interest; ptr = (uint64_t *)&pcoin->vout[i].interest; @@ -4457,14 +4459,14 @@ void CWallet::GetKeyBirthTimes(std::map &mapKeyBirth) const { BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block - int nHeight = blit->second->nHeight; + int nHeight = blit->second->GetHeight(); BOOST_FOREACH(const CTxOut &txout, wtx.vout) { // iterate over all their outputs CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); BOOST_FOREACH(const CKeyID &keyid, vAffected) { // ... and all their affected keys std::map::iterator rit = mapKeyFirstBlock.find(keyid); - if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) + if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->GetHeight()) rit->second = blit->second; } vAffected.clear(); @@ -4567,7 +4569,7 @@ int CMerkleTx::SetMerkleBranch(const CBlock& block) if (!pindex || !chainActive.Contains(pindex)) return 0; - return chainActive.Height() - pindex->nHeight + 1; + return chainActive.Height() - pindex->GetHeight() + 1; } int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const @@ -4593,7 +4595,7 @@ int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const } pindexRet = pindex; - return chainActive.Height() - pindex->nHeight + 1; + return chainActive.Height() - pindex->GetHeight() + 1; } int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const diff --git a/src/zcbenchmarks.cpp b/src/zcbenchmarks.cpp index be3d2862f..c5bdd7c2e 100644 --- a/src/zcbenchmarks.cpp +++ b/src/zcbenchmarks.cpp @@ -321,7 +321,7 @@ double benchmark_increment_note_witnesses(size_t nTxs) block1.vtx.push_back(wtx); } CBlockIndex index1(block1); - index1.nHeight = 1; + index1.SetHeight(1); // Increment to get transactions witnessed wallet.ChainTip(&index1, &block1, sproutTree, saplingTree, true); @@ -344,7 +344,7 @@ double benchmark_increment_note_witnesses(size_t nTxs) block2.vtx.push_back(wtx); } CBlockIndex index2(block2); - index2.nHeight = 2; + index2.SetHeight(2); struct timeval tv_start; timer_start(tv_start); @@ -412,10 +412,10 @@ double benchmark_connectblock_slow() // Fake the chain CBlockIndex index(block); - index.nHeight = 107134; + index.SetHeight(107134); CBlockIndex indexPrev; indexPrev.phashBlock = &hashPrev; - indexPrev.nHeight = index.nHeight - 1; + indexPrev.SetHeight(index.GetHeight() - 1); index.pprev = &indexPrev; mapBlockIndex.insert(std::make_pair(hashPrev, &indexPrev));