Move CTxInWitness inside CTxIn
[bitcoinplatinum.git] / src / miner.cpp
blobb48b9cee49be5718529e995392c592edc989246d
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "miner.h"
8 #include "amount.h"
9 #include "chain.h"
10 #include "chainparams.h"
11 #include "coins.h"
12 #include "consensus/consensus.h"
13 #include "consensus/merkle.h"
14 #include "consensus/validation.h"
15 #include "hash.h"
16 #include "validation.h"
17 #include "net.h"
18 #include "policy/policy.h"
19 #include "pow.h"
20 #include "primitives/transaction.h"
21 #include "script/standard.h"
22 #include "timedata.h"
23 #include "txmempool.h"
24 #include "util.h"
25 #include "utilmoneystr.h"
26 #include "validationinterface.h"
28 #include <algorithm>
29 #include <boost/thread.hpp>
30 #include <boost/tuple/tuple.hpp>
31 #include <queue>
32 #include <utility>
34 using namespace std;
36 //////////////////////////////////////////////////////////////////////////////
38 // BitcoinMiner
42 // Unconfirmed transactions in the memory pool often depend on other
43 // transactions in the memory pool. When we select transactions from the
44 // pool, we select by highest priority or fee rate, so we might consider
45 // transactions that depend on transactions that aren't yet in the block.
47 uint64_t nLastBlockTx = 0;
48 uint64_t nLastBlockSize = 0;
49 uint64_t nLastBlockWeight = 0;
51 class ScoreCompare
53 public:
54 ScoreCompare() {}
56 bool operator()(const CTxMemPool::txiter a, const CTxMemPool::txiter b)
58 return CompareTxMemPoolEntryByScore()(*b,*a); // Convert to less than
62 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
64 int64_t nOldTime = pblock->nTime;
65 int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
67 if (nOldTime < nNewTime)
68 pblock->nTime = nNewTime;
70 // Updating time can change work required on testnet:
71 if (consensusParams.fPowAllowMinDifficultyBlocks)
72 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
74 return nNewTime - nOldTime;
77 BlockAssembler::BlockAssembler(const CChainParams& _chainparams)
78 : chainparams(_chainparams)
80 // Block resource limits
81 // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
82 // If only one is given, only restrict the specified resource.
83 // If both are given, restrict both.
84 nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
85 nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
86 bool fWeightSet = false;
87 if (mapArgs.count("-blockmaxweight")) {
88 nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
89 nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
90 fWeightSet = true;
92 if (mapArgs.count("-blockmaxsize")) {
93 nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
94 if (!fWeightSet) {
95 nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR;
99 // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
100 nBlockMaxWeight = std::max((unsigned int)4000, std::min((unsigned int)(MAX_BLOCK_WEIGHT-4000), nBlockMaxWeight));
101 // Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
102 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SERIALIZED_SIZE-1000), nBlockMaxSize));
104 // Whether we need to account for byte usage (in addition to weight usage)
105 fNeedSizeAccounting = (nBlockMaxSize < MAX_BLOCK_SERIALIZED_SIZE-1000);
108 void BlockAssembler::resetBlock()
110 inBlock.clear();
112 // Reserve space for coinbase tx
113 nBlockSize = 1000;
114 nBlockWeight = 4000;
115 nBlockSigOpsCost = 400;
116 fIncludeWitness = false;
118 // These counters do not include coinbase tx
119 nBlockTx = 0;
120 nFees = 0;
122 lastFewTxs = 0;
123 blockFinished = false;
126 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn)
128 resetBlock();
130 pblocktemplate.reset(new CBlockTemplate());
132 if(!pblocktemplate.get())
133 return nullptr;
134 pblock = &pblocktemplate->block; // pointer for convenience
136 // Add dummy coinbase tx as first transaction
137 pblock->vtx.emplace_back();
138 pblocktemplate->vTxFees.push_back(-1); // updated at end
139 pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
141 LOCK2(cs_main, mempool.cs);
142 CBlockIndex* pindexPrev = chainActive.Tip();
143 nHeight = pindexPrev->nHeight + 1;
145 pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
146 // -regtest only: allow overriding block.nVersion with
147 // -blockversion=N to test forking scenarios
148 if (chainparams.MineBlocksOnDemand())
149 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
151 pblock->nTime = GetAdjustedTime();
152 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
154 nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
155 ? nMedianTimePast
156 : pblock->GetBlockTime();
158 // Decide whether to include witness transactions
159 // This is only needed in case the witness softfork activation is reverted
160 // (which would require a very deep reorganization) or when
161 // -promiscuousmempoolflags is used.
162 // TODO: replace this with a call to main to assess validity of a mempool
163 // transaction (which in most cases can be a no-op).
164 fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus());
166 addPriorityTxs();
167 addPackageTxs();
169 nLastBlockTx = nBlockTx;
170 nLastBlockSize = nBlockSize;
171 nLastBlockWeight = nBlockWeight;
173 // Create coinbase transaction.
174 CMutableTransaction coinbaseTx;
175 coinbaseTx.vin.resize(1);
176 coinbaseTx.vin[0].prevout.SetNull();
177 coinbaseTx.vout.resize(1);
178 coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
179 coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
180 coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
181 pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
182 pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
183 pblocktemplate->vTxFees[0] = -nFees;
185 uint64_t nSerializeSize = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION);
186 LogPrintf("CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize, GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
188 // Fill in header
189 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
190 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
191 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
192 pblock->nNonce = 0;
193 pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
195 CValidationState state;
196 if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
197 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
200 return std::move(pblocktemplate);
203 bool BlockAssembler::isStillDependent(CTxMemPool::txiter iter)
205 BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
207 if (!inBlock.count(parent)) {
208 return true;
211 return false;
214 void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
216 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
217 // Only test txs not already in the block
218 if (inBlock.count(*iit)) {
219 testSet.erase(iit++);
221 else {
222 iit++;
227 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
229 // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
230 if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
231 return false;
232 if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
233 return false;
234 return true;
237 // Perform transaction-level checks before adding to block:
238 // - transaction finality (locktime)
239 // - premature witness (in case segwit transactions are added to mempool before
240 // segwit activation)
241 // - serialized size (in case -blockmaxsize is in use)
242 bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
244 uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
245 BOOST_FOREACH (const CTxMemPool::txiter it, package) {
246 if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
247 return false;
248 if (!fIncludeWitness && it->GetTx().HasWitness())
249 return false;
250 if (fNeedSizeAccounting) {
251 uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
252 if (nPotentialBlockSize + nTxSize >= nBlockMaxSize) {
253 return false;
255 nPotentialBlockSize += nTxSize;
258 return true;
261 bool BlockAssembler::TestForBlock(CTxMemPool::txiter iter)
263 if (nBlockWeight + iter->GetTxWeight() >= nBlockMaxWeight) {
264 // If the block is so close to full that no more txs will fit
265 // or if we've tried more than 50 times to fill remaining space
266 // then flag that the block is finished
267 if (nBlockWeight > nBlockMaxWeight - 400 || lastFewTxs > 50) {
268 blockFinished = true;
269 return false;
271 // Once we're within 4000 weight of a full block, only look at 50 more txs
272 // to try to fill the remaining space.
273 if (nBlockWeight > nBlockMaxWeight - 4000) {
274 lastFewTxs++;
276 return false;
279 if (fNeedSizeAccounting) {
280 if (nBlockSize + ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION) >= nBlockMaxSize) {
281 if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
282 blockFinished = true;
283 return false;
285 if (nBlockSize > nBlockMaxSize - 1000) {
286 lastFewTxs++;
288 return false;
292 if (nBlockSigOpsCost + iter->GetSigOpCost() >= MAX_BLOCK_SIGOPS_COST) {
293 // If the block has room for no more sig ops then
294 // flag that the block is finished
295 if (nBlockSigOpsCost > MAX_BLOCK_SIGOPS_COST - 8) {
296 blockFinished = true;
297 return false;
299 // Otherwise attempt to find another tx with fewer sigops
300 // to put in the block.
301 return false;
304 // Must check that lock times are still valid
305 // This can be removed once MTP is always enforced
306 // as long as reorgs keep the mempool consistent.
307 if (!IsFinalTx(iter->GetTx(), nHeight, nLockTimeCutoff))
308 return false;
310 return true;
313 void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
315 pblock->vtx.emplace_back(iter->GetSharedTx());
316 pblocktemplate->vTxFees.push_back(iter->GetFee());
317 pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
318 if (fNeedSizeAccounting) {
319 nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
321 nBlockWeight += iter->GetTxWeight();
322 ++nBlockTx;
323 nBlockSigOpsCost += iter->GetSigOpCost();
324 nFees += iter->GetFee();
325 inBlock.insert(iter);
327 bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
328 if (fPrintPriority) {
329 double dPriority = iter->GetPriority(nHeight);
330 CAmount dummy;
331 mempool.ApplyDeltas(iter->GetTx().GetHash(), dPriority, dummy);
332 LogPrintf("priority %.1f fee %s txid %s\n",
333 dPriority,
334 CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
335 iter->GetTx().GetHash().ToString());
339 void BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
340 indexed_modified_transaction_set &mapModifiedTx)
342 BOOST_FOREACH(const CTxMemPool::txiter it, alreadyAdded) {
343 CTxMemPool::setEntries descendants;
344 mempool.CalculateDescendants(it, descendants);
345 // Insert all descendants (not yet in block) into the modified set
346 BOOST_FOREACH(CTxMemPool::txiter desc, descendants) {
347 if (alreadyAdded.count(desc))
348 continue;
349 modtxiter mit = mapModifiedTx.find(desc);
350 if (mit == mapModifiedTx.end()) {
351 CTxMemPoolModifiedEntry modEntry(desc);
352 modEntry.nSizeWithAncestors -= it->GetTxSize();
353 modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
354 modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
355 mapModifiedTx.insert(modEntry);
356 } else {
357 mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
363 // Skip entries in mapTx that are already in a block or are present
364 // in mapModifiedTx (which implies that the mapTx ancestor state is
365 // stale due to ancestor inclusion in the block)
366 // Also skip transactions that we've already failed to add. This can happen if
367 // we consider a transaction in mapModifiedTx and it fails: we can then
368 // potentially consider it again while walking mapTx. It's currently
369 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
370 // failedTx and avoid re-evaluation, since the re-evaluation would be using
371 // cached size/sigops/fee values that are not actually correct.
372 bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
374 assert (it != mempool.mapTx.end());
375 if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
376 return true;
377 return false;
380 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
382 // Sort package by ancestor count
383 // If a transaction A depends on transaction B, then A's ancestor count
384 // must be greater than B's. So this is sufficient to validly order the
385 // transactions for block inclusion.
386 sortedEntries.clear();
387 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
388 std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
391 // This transaction selection algorithm orders the mempool based
392 // on feerate of a transaction including all unconfirmed ancestors.
393 // Since we don't remove transactions from the mempool as we select them
394 // for block inclusion, we need an alternate method of updating the feerate
395 // of a transaction with its not-yet-selected ancestors as we go.
396 // This is accomplished by walking the in-mempool descendants of selected
397 // transactions and storing a temporary modified state in mapModifiedTxs.
398 // Each time through the loop, we compare the best transaction in
399 // mapModifiedTxs with the next transaction in the mempool to decide what
400 // transaction package to work on next.
401 void BlockAssembler::addPackageTxs()
403 // mapModifiedTx will store sorted packages after they are modified
404 // because some of their txs are already in the block
405 indexed_modified_transaction_set mapModifiedTx;
406 // Keep track of entries that failed inclusion, to avoid duplicate work
407 CTxMemPool::setEntries failedTx;
409 // Start by adding all descendants of previously added txs to mapModifiedTx
410 // and modifying them for their already included ancestors
411 UpdatePackagesForAdded(inBlock, mapModifiedTx);
413 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
414 CTxMemPool::txiter iter;
415 while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
417 // First try to find a new transaction in mapTx to evaluate.
418 if (mi != mempool.mapTx.get<ancestor_score>().end() &&
419 SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
420 ++mi;
421 continue;
424 // Now that mi is not stale, determine which transaction to evaluate:
425 // the next entry from mapTx, or the best from mapModifiedTx?
426 bool fUsingModified = false;
428 modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
429 if (mi == mempool.mapTx.get<ancestor_score>().end()) {
430 // We're out of entries in mapTx; use the entry from mapModifiedTx
431 iter = modit->iter;
432 fUsingModified = true;
433 } else {
434 // Try to compare the mapTx entry to the mapModifiedTx entry
435 iter = mempool.mapTx.project<0>(mi);
436 if (modit != mapModifiedTx.get<ancestor_score>().end() &&
437 CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
438 // The best entry in mapModifiedTx has higher score
439 // than the one from mapTx.
440 // Switch which transaction (package) to consider
441 iter = modit->iter;
442 fUsingModified = true;
443 } else {
444 // Either no entry in mapModifiedTx, or it's worse than mapTx.
445 // Increment mi for the next loop iteration.
446 ++mi;
450 // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
451 // contain anything that is inBlock.
452 assert(!inBlock.count(iter));
454 uint64_t packageSize = iter->GetSizeWithAncestors();
455 CAmount packageFees = iter->GetModFeesWithAncestors();
456 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
457 if (fUsingModified) {
458 packageSize = modit->nSizeWithAncestors;
459 packageFees = modit->nModFeesWithAncestors;
460 packageSigOpsCost = modit->nSigOpCostWithAncestors;
463 if (packageFees < ::minRelayTxFee.GetFee(packageSize)) {
464 // Everything else we might consider has a lower fee rate
465 return;
468 if (!TestPackage(packageSize, packageSigOpsCost)) {
469 if (fUsingModified) {
470 // Since we always look at the best entry in mapModifiedTx,
471 // we must erase failed entries so that we can consider the
472 // next best entry on the next loop iteration
473 mapModifiedTx.get<ancestor_score>().erase(modit);
474 failedTx.insert(iter);
476 continue;
479 CTxMemPool::setEntries ancestors;
480 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
481 std::string dummy;
482 mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
484 onlyUnconfirmed(ancestors);
485 ancestors.insert(iter);
487 // Test if all tx's are Final
488 if (!TestPackageTransactions(ancestors)) {
489 if (fUsingModified) {
490 mapModifiedTx.get<ancestor_score>().erase(modit);
491 failedTx.insert(iter);
493 continue;
496 // Package can be added. Sort the entries in a valid order.
497 vector<CTxMemPool::txiter> sortedEntries;
498 SortForBlock(ancestors, iter, sortedEntries);
500 for (size_t i=0; i<sortedEntries.size(); ++i) {
501 AddToBlock(sortedEntries[i]);
502 // Erase from the modified set, if present
503 mapModifiedTx.erase(sortedEntries[i]);
506 // Update transactions that depend on each of these
507 UpdatePackagesForAdded(ancestors, mapModifiedTx);
511 void BlockAssembler::addPriorityTxs()
513 // How much of the block should be dedicated to high-priority transactions,
514 // included regardless of the fees they pay
515 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
516 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
518 if (nBlockPrioritySize == 0) {
519 return;
522 bool fSizeAccounting = fNeedSizeAccounting;
523 fNeedSizeAccounting = true;
525 // This vector will be sorted into a priority queue:
526 vector<TxCoinAgePriority> vecPriority;
527 TxCoinAgePriorityCompare pricomparer;
528 std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
529 typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
530 double actualPriority = -1;
532 vecPriority.reserve(mempool.mapTx.size());
533 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
534 mi != mempool.mapTx.end(); ++mi)
536 double dPriority = mi->GetPriority(nHeight);
537 CAmount dummy;
538 mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
539 vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
541 std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
543 CTxMemPool::txiter iter;
544 while (!vecPriority.empty() && !blockFinished) { // add a tx from priority queue to fill the blockprioritysize
545 iter = vecPriority.front().second;
546 actualPriority = vecPriority.front().first;
547 std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
548 vecPriority.pop_back();
550 // If tx already in block, skip
551 if (inBlock.count(iter)) {
552 assert(false); // shouldn't happen for priority txs
553 continue;
556 // cannot accept witness transactions into a non-witness block
557 if (!fIncludeWitness && iter->GetTx().HasWitness())
558 continue;
560 // If tx is dependent on other mempool txs which haven't yet been included
561 // then put it in the waitSet
562 if (isStillDependent(iter)) {
563 waitPriMap.insert(std::make_pair(iter, actualPriority));
564 continue;
567 // If this tx fits in the block add it, otherwise keep looping
568 if (TestForBlock(iter)) {
569 AddToBlock(iter);
571 // If now that this txs is added we've surpassed our desired priority size
572 // or have dropped below the AllowFreeThreshold, then we're done adding priority txs
573 if (nBlockSize >= nBlockPrioritySize || !AllowFree(actualPriority)) {
574 break;
577 // This tx was successfully added, so
578 // add transactions that depend on this one to the priority queue to try again
579 BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
581 waitPriIter wpiter = waitPriMap.find(child);
582 if (wpiter != waitPriMap.end()) {
583 vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
584 std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
585 waitPriMap.erase(wpiter);
590 fNeedSizeAccounting = fSizeAccounting;
593 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
595 // Update nExtraNonce
596 static uint256 hashPrevBlock;
597 if (hashPrevBlock != pblock->hashPrevBlock)
599 nExtraNonce = 0;
600 hashPrevBlock = pblock->hashPrevBlock;
602 ++nExtraNonce;
603 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
604 CMutableTransaction txCoinbase(*pblock->vtx[0]);
605 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
606 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
608 pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
609 pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);