LCOV - code coverage report
Current view: top level - src - blockassembler.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 259 271 95.6 %
Date: 2025-02-23 09:33:43 Functions: 22 22 100.0 %

          Line data    Source code
       1             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2021 The Bitcoin Core developers
       3             : // Copyright (c) 2021 The PIVX Core developers
       4             : // Distributed under the MIT software license, see the accompanying
       5             : // file COPYING or https://www.opensource.org/licenses/mit-license.php.
       6             : 
       7             : #include "blockassembler.h"
       8             : 
       9             : #include "amount.h"
      10             : #include "blocksignature.h"
      11             : #include "chain.h"
      12             : #include "chainparams.h"
      13             : #include "consensus/consensus.h"
      14             : #include "consensus/merkle.h"
      15             : #include "consensus/upgrades.h"
      16             : #include "consensus/validation.h"
      17             : #include "llmq/quorums_blockprocessor.h"
      18             : #include "masternode-payments.h"
      19             : #include "policy/policy.h"
      20             : #include "pow.h"
      21             : #include "primitives/transaction.h"
      22             : #include "spork.h"
      23             : #include "timedata.h"
      24             : #include "util/system.h"
      25             : #include "util/validation.h"
      26             : #include "validationinterface.h"
      27             : 
      28             : #ifdef ENABLE_WALLET
      29             : #include "wallet/wallet.h"
      30             : #endif
      31             : 
      32             : #include <algorithm>
      33             : #include <boost/thread.hpp>
      34             : 
      35             : // Unconfirmed transactions in the memory pool often depend on other
      36             : // transactions in the memory pool. When we select transactions from the
      37             : // pool, we select by highest priority or fee rate, so we might consider
      38             : // transactions that depend on transactions that aren't yet in the block.
      39             : 
      40             : uint64_t nLastBlockTx = 0;
      41             : uint64_t nLastBlockSize = 0;
      42             : 
      43       13293 : int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
      44             : {
      45       13293 :     int64_t nOldTime = pblock->nTime;
      46       13293 :     int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
      47             : 
      48       13293 :     if (nOldTime < nNewTime)
      49       13293 :         pblock->nTime = nNewTime;
      50             : 
      51             :     // Updating time can change work required on testnet:
      52       13293 :     if (consensusParams.fPowAllowMinDifficultyBlocks)
      53       13293 :         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
      54             : 
      55       13293 :     return nNewTime - nOldTime;
      56             : }
      57             : 
      58       15323 : static CMutableTransaction NewCoinbase(const int nHeight, const CScript* pScriptPubKey = nullptr)
      59             : {
      60       15323 :     CMutableTransaction txCoinbase;
      61       15323 :     txCoinbase.vout.emplace_back();
      62       15323 :     txCoinbase.vout[0].SetEmpty();
      63       15323 :     if (pScriptPubKey) txCoinbase.vout[0].scriptPubKey = *pScriptPubKey;
      64       15323 :     txCoinbase.vin.emplace_back();
      65       15323 :     txCoinbase.vin[0].scriptSig = CScript() << nHeight << OP_0;
      66       15323 :     return txCoinbase;
      67             : }
      68             : 
      69        1925 : bool SolveProofOfStake(CBlock* pblock, CBlockIndex* pindexPrev, CWallet* pwallet,
      70             :                        std::vector<CStakeableOutput>* availableCoins, bool stopPoSOnNewBlock)
      71             : {
      72        1925 :     boost::this_thread::interruption_point();
      73             : 
      74        1925 :     assert(pindexPrev);
      75        1925 :     pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
      76             : 
      77             :     // Sync wallet before create coinstake
      78        1925 :     pwallet->BlockUntilSyncedToCurrentChain();
      79             : 
      80        3850 :     CMutableTransaction txCoinStake;
      81        1925 :     int64_t nTxNewTime = 0;
      82        1925 :     if (!pwallet->CreateCoinStake(pindexPrev,
      83             :                                   pblock->nBits,
      84             :                                   txCoinStake,
      85             :                                   nTxNewTime,
      86             :                                   availableCoins,
      87             :                                   stopPoSOnNewBlock
      88             :                                   )) {
      89           6 :         LogPrint(BCLog::STAKING, "%s : stake not found\n", __func__);
      90           6 :         return false;
      91             :     }
      92             :     // Stake found
      93             : 
      94             :     // Create coinbase tx and add masternode/budget payments
      95        3838 :     CMutableTransaction txCoinbase = NewCoinbase(pindexPrev->nHeight + 1);
      96        1919 :     FillBlockPayee(txCoinbase, txCoinStake, pindexPrev, true);
      97             : 
      98             :     // Sign coinstake
      99        1919 :     if (!pwallet->SignCoinStake(txCoinStake)) {
     100           0 :         const COutPoint& stakeIn = txCoinStake.vin[0].prevout;
     101           0 :         return error("Unable to sign coinstake with input %s-%d", stakeIn.hash.ToString(), stakeIn.n);
     102             :     }
     103             : 
     104        1919 :     pblock->vtx.emplace_back(MakeTransactionRef(txCoinbase));
     105        1919 :     pblock->vtx.emplace_back(MakeTransactionRef(txCoinStake));
     106        1919 :     pblock->nTime = nTxNewTime;
     107        1919 :     return true;
     108             : }
     109             : 
     110       13404 : CMutableTransaction CreateCoinbaseTx(const CScript& scriptPubKeyIn, CBlockIndex* pindexPrev)
     111             : {
     112       13404 :     assert(pindexPrev);
     113       13404 :     const int nHeight = pindexPrev->nHeight + 1;
     114             : 
     115             :     // Create coinbase tx
     116       13404 :     CMutableTransaction txCoinbase = NewCoinbase(nHeight, &scriptPubKeyIn);
     117             : 
     118             :     //Masternode and general budget payments
     119       13404 :     CMutableTransaction txDummy;    // POW blocks have no coinstake
     120       13404 :     FillBlockPayee(txCoinbase, txDummy, pindexPrev, false);
     121             : 
     122             :     // If no payee was detected, then the whole block value goes to the first output.
     123       13404 :     if (txCoinbase.vout.size() == 1) {
     124       12549 :         txCoinbase.vout[0].nValue = GetBlockValue(nHeight);
     125             :     }
     126             : 
     127       13404 :     return txCoinbase;
     128             : }
     129             : 
     130       13403 : bool CreateCoinbaseTx(CBlock* pblock, const CScript& scriptPubKeyIn, CBlockIndex* pindexPrev)
     131             : {
     132       26806 :     pblock->vtx.emplace_back(MakeTransactionRef(CreateCoinbaseTx(scriptPubKeyIn, pindexPrev)));
     133       13403 :     return true;
     134             : }
     135             : 
     136       15218 : BlockAssembler::BlockAssembler(const CChainParams& _chainparams, const bool _defaultPrintPriority)
     137       15218 :         : chainparams(_chainparams), defaultPrintPriority(_defaultPrintPriority)
     138             : {
     139             :     // Largest block you're willing to create:
     140       15218 :     nBlockMaxSize = gArgs.GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
     141             :     // Limit to between 1K and MAX_BLOCK_SIZE-1K for sanity:
     142       27452 :     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE_CURRENT - 1000), nBlockMaxSize));
     143       15218 : }
     144             : 
     145       15218 : void BlockAssembler::resetBlock()
     146             : {
     147       15218 :     inBlock.clear();
     148             : 
     149             :     // Reserve space for coinbase tx
     150       15218 :     nBlockSize = 1000;
     151       15218 :     nBlockSigOps = 100;
     152             : 
     153             :     // These counters do not include coinbase tx
     154       15218 :     nBlockTx = 0;
     155       15218 :     nFees = 0;
     156       15218 : }
     157             : 
     158       15218 : std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn,
     159             :                                                CWallet* pwallet,
     160             :                                                bool fProofOfStake,
     161             :                                                std::vector<CStakeableOutput>* availableCoins,
     162             :                                                bool fNoMempoolTx,
     163             :                                                bool fTestValidity,
     164             :                                                CBlockIndex* prevBlock,
     165             :                                                bool stopPoSOnNewBlock,
     166             :                                                bool fIncludeQfc)
     167             : {
     168       15218 :     resetBlock();
     169             : 
     170       30436 :     pblocktemplate.reset(new CBlockTemplate());
     171             : 
     172       15218 :     if(!pblocktemplate) return nullptr;
     173       15218 :     pblock = &pblocktemplate->block; // pointer for convenience
     174             : 
     175       15218 :     pblocktemplate->vTxFees.push_back(-1); // updated at end
     176       15218 :     pblocktemplate->vTxSigOps.push_back(-1); // updated at end
     177             : 
     178       45628 :     CBlockIndex* pindexPrev = prevBlock ? prevBlock : WITH_LOCK(cs_main, return chainActive.Tip());
     179       15218 :     assert(pindexPrev);
     180       15218 :     nHeight = pindexPrev->nHeight + 1;
     181             : 
     182       15218 :     pblock->nVersion = ComputeBlockVersion(chainparams.GetConsensus(), nHeight);
     183             :     // -regtest only: allow overriding block.nVersion with
     184             :     // -blockversion=N to test forking scenarios
     185       15218 :     if (Params().IsRegTestNet()) {
     186       15218 :         pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
     187             :     }
     188             : 
     189             :     // Depending on the tip height, try to find a coinstake who solves the block or create a coinbase tx.
     190       28511 :     if (!(fProofOfStake ? SolveProofOfStake(pblock, pindexPrev, pwallet, availableCoins, stopPoSOnNewBlock)
     191       13293 :                         : CreateCoinbaseTx(pblock, scriptPubKeyIn, pindexPrev))) {
     192           6 :         return nullptr;
     193             :     }
     194             : 
     195             :     // After v6 enforcement, add LLMQ commitments if needed
     196       15212 :     const Consensus::Params& consensus = Params().GetConsensus();
     197       15212 :     if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V6_0) && fIncludeQfc) {
     198        2734 :         LOCK(cs_main);
     199        2734 :         for (const auto& p : Params().GetConsensus().llmqs) {
     200        1367 :             CTransactionRef qcTx;
     201        1367 :             if (llmq::quorumBlockProcessor->GetMinableCommitmentTx(p.first, nHeight, qcTx)) {
     202         353 :                 pblock->vtx.emplace_back(qcTx);
     203         353 :                 pblocktemplate->vTxFees.emplace_back(0);
     204         353 :                 pblocktemplate->vTxSigOps.emplace_back(0);
     205         353 :                 nBlockSize += qcTx->GetTotalSize();
     206         353 :                 ++nBlockTx;
     207             :             }
     208             :         }
     209             :     }
     210             : 
     211       15212 :     if (!fNoMempoolTx) {
     212             :         // Add transactions from mempool
     213       38214 :         LOCK2(cs_main,mempool.cs);
     214       12738 :         addPackageTxs();
     215             :     }
     216             : 
     217       15212 :     if (!fProofOfStake) {
     218             :         // Coinbase can get the fees.
     219       26586 :         CMutableTransaction txCoinbase(*pblock->vtx[0]);
     220       13293 :         txCoinbase.vout[0].nValue += nFees;
     221       26586 :         pblock->vtx[0] = MakeTransactionRef(txCoinbase);
     222       13293 :         pblocktemplate->vTxFees[0] = -nFees;
     223             :     }
     224             : 
     225       15212 :     nLastBlockTx = nBlockTx;
     226       15212 :     nLastBlockSize = nBlockSize;
     227       15212 :     LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps);
     228             : 
     229             : 
     230             :     // Fill in header
     231       15212 :     pblock->hashPrevBlock = pindexPrev->GetBlockHash();
     232       15212 :     if (!fProofOfStake) UpdateTime(pblock, consensus, pindexPrev);
     233       15212 :     pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
     234       15212 :     pblock->nNonce = 0;
     235       15212 :     pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(*(pblock->vtx[0]));
     236       15212 :     appendSaplingTreeRoot();
     237             : 
     238       15212 :     if (fProofOfStake) { // this is only for PoS because the IncrementExtraNonce does it for PoW
     239        1919 :         pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
     240        1919 :         LogPrintf("CPUMiner : proof-of-stake block found %s \n", pblock->GetHash().GetHex());
     241        1919 :         if (!SignBlock(*pblock, *pwallet)) {
     242           0 :             LogPrintf("%s: Signing new block with UTXO key failed \n", __func__);
     243           0 :             return nullptr;
     244             :         }
     245             :     }
     246             : 
     247       15212 :     {
     248       15212 :         LOCK(cs_main);
     249       30411 :         if (prevBlock == nullptr && chainActive.Tip() != pindexPrev) return nullptr; // new block came in, move on
     250             : 
     251       30361 :         CValidationState state;
     252       30361 :         if (fTestValidity &&
     253       15149 :             !TestBlockValidity(state, *pblock, pindexPrev, false, false, false)) {
     254           5 :             throw std::runtime_error(
     255          14 :                     strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
     256             :         }
     257             :     }
     258             : 
     259       15213 :     return std::move(pblocktemplate);
     260             : }
     261             : 
     262      142931 : void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
     263             : {
     264      142931 :     for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
     265             :         // Only test txs not already in the block
     266       46479 :         if (inBlock.count(*iit)) {
     267       26059 :             testSet.erase(iit++);
     268             :         }
     269             :         else {
     270      209830 :             iit++;
     271             :         }
     272             :     }
     273      142931 : }
     274             : 
     275      223715 : bool BlockAssembler::TestPackage(uint64_t packageSize, unsigned int packageSigOps)
     276             : {
     277      223715 :     if (nBlockSize + packageSize >= nBlockMaxSize)
     278             :         return false;
     279      142931 :     if (nBlockSigOps + packageSigOps >= MAX_BLOCK_SIGOPS_CURRENT)
     280           0 :         return false;
     281             :     return true;
     282             : }
     283             : 
     284             : // Block size and sigops have already been tested.  Check that all transactions
     285             : // are final.
     286      142931 : bool BlockAssembler::TestPackageFinality(const CTxMemPool::setEntries& package)
     287             : {
     288      306280 :     for (const CTxMemPool::txiter& it : package) {
     289      326702 :         if (!IsFinalTx(it->GetSharedTx(), nHeight))
     290           2 :             return false;
     291             :     }
     292      142929 :     return true;
     293             : }
     294             : 
     295      162966 : void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
     296             : {
     297      162966 :     pblock->vtx.emplace_back(iter->GetSharedTx());
     298      162966 :     pblocktemplate->vTxFees.push_back(iter->GetFee());
     299      162966 :     pblocktemplate->vTxSigOps.push_back(iter->GetSigOpCount());
     300      162966 :     nBlockSize += iter->GetTxSize();
     301      162966 :     ++nBlockTx;
     302      162966 :     nBlockSigOps += iter->GetSigOpCount();
     303      162966 :     nFees += iter->GetFee();
     304      162966 :     inBlock.insert(iter);
     305             : 
     306      162966 :     bool fPrintPriority = gArgs.GetBoolArg("-printpriority", defaultPrintPriority);
     307      162966 :     if (fPrintPriority) {
     308           0 :         LogPrintf("feerate %s txid %s\n",
     309           0 :                   CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
     310           0 :                   iter->GetTx().GetHash().ToString());
     311             :     }
     312      162966 : }
     313             : 
     314      155667 : void BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
     315             :                                             indexed_modified_transaction_set& mapModifiedTx)
     316             : {
     317      319016 :     for (const CTxMemPool::txiter& it : alreadyAdded) {
     318      326698 :         CTxMemPool::setEntries descendants;
     319      163349 :         mempool.CalculateDescendants(it, descendants);
     320             :         // Insert all descendants (not yet in block) into the modified set
     321     2905518 :         for (CTxMemPool::txiter desc : descendants) {
     322     2742165 :             if (alreadyAdded.count(desc))
     323     1767240 :                 continue;
     324      974932 :             modtxiter mit = mapModifiedTx.find(desc);
     325      974932 :             if (mit == mapModifiedTx.end()) {
     326       28576 :                 CTxMemPoolModifiedEntry modEntry(desc);
     327       28576 :                 modEntry.nSizeWithAncestors -= it->GetTxSize();
     328       28576 :                 modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
     329       28576 :                 modEntry.nSigOpCountWithAncestors -= it->GetSigOpCount();
     330       28576 :                 mapModifiedTx.insert(modEntry);
     331             :             } else {
     332      946356 :                 mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
     333             :             }
     334             :         }
     335             :     }
     336      155667 : }
     337             : 
     338             : // Skip entries in mapTx that are already in a block or are present
     339             : // in mapModifiedTx (which implies that the mapTx ancestor state is
     340             : // stale due to ancestor inclusion in the block)
     341             : // Also skip transactions that we've already failed to add. This can happen if
     342             : // we consider a transaction in mapModifiedTx and it fails: we can then
     343             : // potentially consider it again while walking mapTx.  It's currently
     344             : // guaranteed to fail again, but as a belt-and-suspenders check we put it in
     345             : // failedTx and avoid re-evaluation, since the re-evaluation would be using
     346             : // cached size/sigops/fee values that are not actually correct.
     347      269323 : bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
     348             : {
     349      269323 :     assert (it != mempool.mapTx.end());
     350      740487 :     if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
     351       46014 :         return true;
     352             :     return false;
     353             : }
     354             : 
     355      142929 : void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
     356             : {
     357             :     // Sort package by ancestor count
     358             :     // If a transaction A depends on transaction B, then A's ancestor count
     359             :     // must be greater than B's.  So this is sufficient to validly order the
     360             :     // transactions for block inclusion.
     361      142929 :     sortedEntries.clear();
     362      142929 :     sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
     363      142929 :     std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
     364      142929 : }
     365             : 
     366             : // This transaction selection algorithm orders the mempool based
     367             : // on feerate of a transaction including all unconfirmed ancestors.
     368             : // Since we don't remove transactions from the mempool as we select them
     369             : // for block inclusion, we need an alternate method of updating the feerate
     370             : // of a transaction with its not-yet-selected ancestors as we go.
     371             : // This is accomplished by walking the in-mempool descendants of selected
     372             : // transactions and storing a temporary modified state in mapModifiedTxs.
     373             : // Each time through the loop, we compare the best transaction in
     374             : // mapModifiedTxs with the next transaction in the mempool to decide what
     375             : // transaction package to work on next.
     376       12738 : void BlockAssembler::addPackageTxs()
     377             : {
     378             :     // mapModifiedTx will store sorted packages after they are modified
     379             :     // because some of their txs are already in the block
     380       12738 :     indexed_modified_transaction_set mapModifiedTx;
     381             :     // Keep track of entries that failed inclusion, to avoid duplicate work
     382       25474 :     CTxMemPool::setEntries failedTx;
     383             : 
     384             :     // Start by adding all descendants of previously added txs to mapModifiedTx
     385             :     // and modifying them for their already included ancestors
     386       12738 :     UpdatePackagesForAdded(inBlock, mapModifiedTx);
     387             : 
     388       12738 :     CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
     389       12738 :     CTxMemPool::txiter iter;
     390      282467 :     while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
     391             :     {
     392             :         // First try to find a new transaction in mapTx to evaluate.
     393      539054 :         if (mi != mempool.mapTx.get<ancestor_score>().end() &&
     394      269323 :                 SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
     395       46014 :             ++mi;
     396      126800 :             continue;
     397             :         }
     398             : 
     399             :         // Now that mi is not stale, determine which transaction to evaluate:
     400             :         // the next entry from mapTx, or the best from mapModifiedTx?
     401      223717 :         bool fUsingModified = false;
     402             : 
     403      223717 :         modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
     404      223717 :         if (mi == mempool.mapTx.get<ancestor_score>().end()) {
     405             :             // We're out of entries in mapTx; use the entry from mapModifiedTx
     406         408 :             iter = modit->iter;
     407         408 :             fUsingModified = true;
     408             :         } else {
     409             :             // Try to compare the mapTx entry to the mapModifiedTx entry
     410      223309 :             iter = mempool.mapTx.project<0>(mi);
     411      223309 :             if (modit != mapModifiedTx.get<ancestor_score>().end() &&
     412      112235 :                     CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
     413             :                 // The best entry in mapModifiedTx has higher score
     414             :                 // than the one from mapTx.
     415             :                 // Switch which transaction (package) to consider
     416       25403 :                 iter = modit->iter;
     417       25403 :                 fUsingModified = true;
     418             :             } else {
     419             :                 // Either no entry in mapModifiedTx, or it's worse than mapTx.
     420             :                 // Increment mi for the next loop iteration.
     421      197906 :                 ++mi;
     422             :             }
     423             :         }
     424             : 
     425             :         // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
     426             :         // contain anything that is inBlock.
     427      223717 :         assert(!inBlock.count(iter));
     428             : 
     429      223717 :         uint64_t packageSize = iter->GetSizeWithAncestors();
     430      223717 :         CAmount packageFees = iter->GetModFeesWithAncestors();
     431      223717 :         unsigned int packageSigOps = iter->GetSigOpCountWithAncestors();
     432      223717 :         if (fUsingModified) {
     433       25811 :             packageSize = modit->nSizeWithAncestors;
     434       25811 :             packageFees = modit->nModFeesWithAncestors;
     435       25811 :             packageSigOps = modit->nSigOpCountWithAncestors;
     436             :         }
     437             : 
     438      223717 :         if (packageFees < ::minRelayTxFee.GetFee(packageSize)) {
     439             :             // Everything else we might consider has a lower fee rate
     440           2 :             return;
     441             :         }
     442             : 
     443      223715 :         if (!TestPackage(packageSize, packageSigOps)) {
     444       80784 :             if (fUsingModified) {
     445             :                 // Since we always look at the best entry in mapModifiedTx,
     446             :                 // we must erase failed entries so that we can consider the
     447             :                 // next best entry on the next loop iteration
     448       18412 :                 mapModifiedTx.get<ancestor_score>().erase(modit);
     449       18412 :                 failedTx.insert(iter);
     450             :             }
     451       80784 :             continue;
     452             :         }
     453             : 
     454      285860 :         CTxMemPool::setEntries ancestors;
     455      142931 :         uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
     456      285860 :         std::string dummy;
     457      142931 :         mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
     458             : 
     459      142931 :         onlyUnconfirmed(ancestors);
     460      142931 :         ancestors.insert(iter);
     461             : 
     462             :         // Test if all tx's are Final
     463      142931 :         if (!TestPackageFinality(ancestors)) {
     464           2 :             if (fUsingModified) {
     465           0 :                 mapModifiedTx.get<ancestor_score>().erase(modit);
     466           0 :                 failedTx.insert(iter);
     467             :             }
     468           2 :             continue;
     469             :         }
     470             : 
     471             :         // Package can be added. Sort the entries in a valid order.
     472      285858 :         std::vector<CTxMemPool::txiter> sortedEntries;
     473      142929 :         SortForBlock(ancestors, iter, sortedEntries);
     474             : 
     475      305895 :         for (size_t i = 0; i < sortedEntries.size(); ++i) {
     476      163349 :             CTxMemPool::txiter& iterSortedEntries = sortedEntries[i];
     477      163349 :             if (iterSortedEntries->IsShielded()) {
     478             :                 // Don't add SHIELD transactions if in maintenance (SPORK_20)
     479        1075 :                 if (sporkManager.IsSporkActive(SPORK_20_SAPLING_MAINTENANCE)) {
     480             :                     break;
     481             :                 }
     482             :                 // Don't add SHIELD transactions if there's no reserved space left in the block
     483        1075 :                 if (nSizeShielded + iterSortedEntries->GetTxSize() > MAX_BLOCK_SHIELDED_TXES_SIZE) {
     484             :                     break;
     485             :                 }
     486             :                 // Update cumulative size of SHIELD transactions in this block
     487         692 :                 nSizeShielded += iterSortedEntries->GetTxSize();
     488             :             }
     489      162966 :             AddToBlock(iterSortedEntries);
     490             :             // Erase from the modified set, if present
     491      162966 :             mapModifiedTx.erase(iterSortedEntries);
     492             :         }
     493             : 
     494             :         // Update transactions that depend on each of these
     495      142929 :         UpdatePackagesForAdded(ancestors, mapModifiedTx);
     496             :     }
     497             : }
     498             : 
     499       15212 : void BlockAssembler::appendSaplingTreeRoot()
     500             : {
     501             :     // Update header
     502       15212 :     pblock->hashFinalSaplingRoot = CalculateSaplingTreeRoot(pblock, nHeight, chainparams);
     503       15212 : }
     504             : 
     505       17647 : uint256 CalculateSaplingTreeRoot(CBlock* pblock, int nHeight, const CChainParams& chainparams)
     506             : {
     507       17647 :     if (NetworkUpgradeActive(nHeight, chainparams.GetConsensus(), Consensus::UPGRADE_V5_0)) {
     508       10112 :         SaplingMerkleTree sapling_tree;
     509        5056 :         assert(pcoinsTip->GetSaplingAnchorAt(pcoinsTip->GetBestAnchor(), sapling_tree));
     510             : 
     511             :         // Update the Sapling commitment tree.
     512       13063 :         for (const auto &tx : pblock->vtx) {
     513        9235 :             if (tx->IsShieldedTx()) {
     514        1466 :                 for (const OutputDescription &odesc : tx->sapData->vShieldedOutput) {
     515         771 :                     sapling_tree.append(odesc.cmu);
     516             :                 }
     517             :             }
     518             :         }
     519        5056 :         return sapling_tree.root();
     520             :     }
     521       12591 :     return UINT256_ZERO;
     522             : }
     523             : 
     524       13046 : bool SolveBlock(std::shared_ptr<CBlock>& pblock, int nHeight)
     525             : {
     526       13046 :     unsigned int extraNonce = 0;
     527       13046 :     IncrementExtraNonce(pblock, nHeight, extraNonce);
     528       52118 :     while (pblock->nNonce < std::numeric_limits<uint32_t>::max() &&
     529       26059 :            !CheckProofOfWork(pblock->GetHash(), pblock->nBits)) {
     530       13013 :         ++pblock->nNonce;
     531             :     }
     532       13046 :     return pblock->nNonce != std::numeric_limits<uint32_t>::max();
     533             : }
     534             : 
     535       13046 : void IncrementExtraNonce(std::shared_ptr<CBlock>& pblock, int nHeight, unsigned int& nExtraNonce)
     536             : {
     537             :     // Update nExtraNonce
     538       13175 :     static uint256 hashPrevBlock;
     539       13046 :     if (hashPrevBlock != pblock->hashPrevBlock) {
     540       13019 :         nExtraNonce = 0;
     541       13019 :         hashPrevBlock = pblock->hashPrevBlock;
     542             :     }
     543       13046 :     ++nExtraNonce;
     544       26092 :     CMutableTransaction txCoinbase(*pblock->vtx[0]);
     545       26092 :     txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
     546       13046 :     assert(txCoinbase.vin[0].scriptSig.size() <= 100);
     547             : 
     548       26092 :     pblock->vtx[0] = MakeTransactionRef(txCoinbase);
     549       13046 :     pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
     550       13046 : }
     551             : 
     552       15218 : int32_t ComputeBlockVersion(const Consensus::Params& consensus, int nHeight)
     553             : {
     554       15218 :     if (NetworkUpgradeActive(nHeight, consensus, Consensus::UPGRADE_V5_0)) {
     555             :         return CBlockHeader::CURRENT_VERSION;       // v11 (since 5.2.99)
     556       10564 :     } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V4_0)) {
     557             :         return 7;
     558        2681 :     } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4)) {
     559             :         return 6;
     560        2681 :     } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_BIP65)) {
     561             :         return 5;
     562           0 :     } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_ZC)) {
     563             :         return 4;
     564             :     } else {
     565           0 :         return 3;
     566             :     }
     567             : }
     568             : 

Generated by: LCOV version 1.14