1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
10 #include "chainparams.h"
12 #include "consensus/consensus.h"
13 #include "consensus/merkle.h"
14 #include "consensus/validation.h"
16 #include "validation.h"
18 #include "policy/policy.h"
20 #include "primitives/transaction.h"
21 #include "script/standard.h"
23 #include "txmempool.h"
25 #include "utilmoneystr.h"
26 #include "validationinterface.h"
29 #include <boost/thread.hpp>
30 #include <boost/tuple/tuple.hpp>
34 //////////////////////////////////////////////////////////////////////////////
40 // Unconfirmed transactions in the memory pool often depend on other
41 // transactions in the memory pool. When we select transactions from the
42 // pool, we select by highest priority or fee rate, so we might consider
43 // transactions that depend on transactions that aren't yet in the block.
45 uint64_t nLastBlockTx
= 0;
46 uint64_t nLastBlockSize
= 0;
47 uint64_t nLastBlockWeight
= 0;
54 bool operator()(const CTxMemPool::txiter a
, const CTxMemPool::txiter b
)
56 return CompareTxMemPoolEntryByScore()(*b
,*a
); // Convert to less than
60 int64_t UpdateTime(CBlockHeader
* pblock
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
)
62 int64_t nOldTime
= pblock
->nTime
;
63 int64_t nNewTime
= std::max(pindexPrev
->GetMedianTimePast()+1, GetAdjustedTime());
65 if (nOldTime
< nNewTime
)
66 pblock
->nTime
= nNewTime
;
68 // Updating time can change work required on testnet:
69 if (consensusParams
.fPowAllowMinDifficultyBlocks
)
70 pblock
->nBits
= GetNextWorkRequired(pindexPrev
, pblock
, consensusParams
);
72 return nNewTime
- nOldTime
;
75 BlockAssembler::BlockAssembler(const CChainParams
& _chainparams
)
76 : chainparams(_chainparams
)
78 // Block resource limits
79 // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
80 // If only one is given, only restrict the specified resource.
81 // If both are given, restrict both.
82 nBlockMaxWeight
= DEFAULT_BLOCK_MAX_WEIGHT
;
83 nBlockMaxSize
= DEFAULT_BLOCK_MAX_SIZE
;
84 bool fWeightSet
= false;
85 if (IsArgSet("-blockmaxweight")) {
86 nBlockMaxWeight
= GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT
);
87 nBlockMaxSize
= MAX_BLOCK_SERIALIZED_SIZE
;
90 if (IsArgSet("-blockmaxsize")) {
91 nBlockMaxSize
= GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE
);
93 nBlockMaxWeight
= nBlockMaxSize
* WITNESS_SCALE_FACTOR
;
96 if (IsArgSet("-blockmintxfee")) {
98 ParseMoney(GetArg("-blockmintxfee", ""), n
);
99 blockMinFeeRate
= CFeeRate(n
);
101 blockMinFeeRate
= CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE
);
104 // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
105 nBlockMaxWeight
= std::max((unsigned int)4000, std::min((unsigned int)(MAX_BLOCK_WEIGHT
-4000), nBlockMaxWeight
));
106 // Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
107 nBlockMaxSize
= std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SERIALIZED_SIZE
-1000), nBlockMaxSize
));
108 // Whether we need to account for byte usage (in addition to weight usage)
109 fNeedSizeAccounting
= (nBlockMaxSize
< MAX_BLOCK_SERIALIZED_SIZE
-1000);
112 void BlockAssembler::resetBlock()
116 // Reserve space for coinbase tx
119 nBlockSigOpsCost
= 400;
120 fIncludeWitness
= false;
122 // These counters do not include coinbase tx
127 blockFinished
= false;
130 std::unique_ptr
<CBlockTemplate
> BlockAssembler::CreateNewBlock(const CScript
& scriptPubKeyIn
)
134 pblocktemplate
.reset(new CBlockTemplate());
136 if(!pblocktemplate
.get())
138 pblock
= &pblocktemplate
->block
; // pointer for convenience
140 // Add dummy coinbase tx as first transaction
141 pblock
->vtx
.emplace_back();
142 pblocktemplate
->vTxFees
.push_back(-1); // updated at end
143 pblocktemplate
->vTxSigOpsCost
.push_back(-1); // updated at end
145 LOCK2(cs_main
, mempool
.cs
);
146 CBlockIndex
* pindexPrev
= chainActive
.Tip();
147 nHeight
= pindexPrev
->nHeight
+ 1;
149 pblock
->nVersion
= ComputeBlockVersion(pindexPrev
, chainparams
.GetConsensus());
150 // -regtest only: allow overriding block.nVersion with
151 // -blockversion=N to test forking scenarios
152 if (chainparams
.MineBlocksOnDemand())
153 pblock
->nVersion
= GetArg("-blockversion", pblock
->nVersion
);
155 pblock
->nTime
= GetAdjustedTime();
156 const int64_t nMedianTimePast
= pindexPrev
->GetMedianTimePast();
158 nLockTimeCutoff
= (STANDARD_LOCKTIME_VERIFY_FLAGS
& LOCKTIME_MEDIAN_TIME_PAST
)
160 : pblock
->GetBlockTime();
162 // Decide whether to include witness transactions
163 // This is only needed in case the witness softfork activation is reverted
164 // (which would require a very deep reorganization) or when
165 // -promiscuousmempoolflags is used.
166 // TODO: replace this with a call to main to assess validity of a mempool
167 // transaction (which in most cases can be a no-op).
168 fIncludeWitness
= IsWitnessEnabled(pindexPrev
, chainparams
.GetConsensus());
173 nLastBlockTx
= nBlockTx
;
174 nLastBlockSize
= nBlockSize
;
175 nLastBlockWeight
= nBlockWeight
;
177 // Create coinbase transaction.
178 CMutableTransaction coinbaseTx
;
179 coinbaseTx
.vin
.resize(1);
180 coinbaseTx
.vin
[0].prevout
.SetNull();
181 coinbaseTx
.vout
.resize(1);
182 coinbaseTx
.vout
[0].scriptPubKey
= scriptPubKeyIn
;
183 coinbaseTx
.vout
[0].nValue
= nFees
+ GetBlockSubsidy(nHeight
, chainparams
.GetConsensus());
184 coinbaseTx
.vin
[0].scriptSig
= CScript() << nHeight
<< OP_0
;
185 pblock
->vtx
[0] = MakeTransactionRef(std::move(coinbaseTx
));
186 pblocktemplate
->vchCoinbaseCommitment
= GenerateCoinbaseCommitment(*pblock
, pindexPrev
, chainparams
.GetConsensus());
187 pblocktemplate
->vTxFees
[0] = -nFees
;
189 uint64_t nSerializeSize
= GetSerializeSize(*pblock
, SER_NETWORK
, PROTOCOL_VERSION
);
190 LogPrintf("CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize
, GetBlockWeight(*pblock
), nBlockTx
, nFees
, nBlockSigOpsCost
);
193 pblock
->hashPrevBlock
= pindexPrev
->GetBlockHash();
194 UpdateTime(pblock
, chainparams
.GetConsensus(), pindexPrev
);
195 pblock
->nBits
= GetNextWorkRequired(pindexPrev
, pblock
, chainparams
.GetConsensus());
197 pblocktemplate
->vTxSigOpsCost
[0] = WITNESS_SCALE_FACTOR
* GetLegacySigOpCount(*pblock
->vtx
[0]);
199 CValidationState state
;
200 if (!TestBlockValidity(state
, chainparams
, *pblock
, pindexPrev
, false, false)) {
201 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__
, FormatStateMessage(state
)));
204 return std::move(pblocktemplate
);
207 bool BlockAssembler::isStillDependent(CTxMemPool::txiter iter
)
209 BOOST_FOREACH(CTxMemPool::txiter parent
, mempool
.GetMemPoolParents(iter
))
211 if (!inBlock
.count(parent
)) {
218 void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries
& testSet
)
220 for (CTxMemPool::setEntries::iterator iit
= testSet
.begin(); iit
!= testSet
.end(); ) {
221 // Only test txs not already in the block
222 if (inBlock
.count(*iit
)) {
223 testSet
.erase(iit
++);
231 bool BlockAssembler::TestPackage(uint64_t packageSize
, int64_t packageSigOpsCost
)
233 // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
234 if (nBlockWeight
+ WITNESS_SCALE_FACTOR
* packageSize
>= nBlockMaxWeight
)
236 if (nBlockSigOpsCost
+ packageSigOpsCost
>= MAX_BLOCK_SIGOPS_COST
)
241 // Perform transaction-level checks before adding to block:
242 // - transaction finality (locktime)
243 // - premature witness (in case segwit transactions are added to mempool before
244 // segwit activation)
245 // - serialized size (in case -blockmaxsize is in use)
246 bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries
& package
)
248 uint64_t nPotentialBlockSize
= nBlockSize
; // only used with fNeedSizeAccounting
249 BOOST_FOREACH (const CTxMemPool::txiter it
, package
) {
250 if (!IsFinalTx(it
->GetTx(), nHeight
, nLockTimeCutoff
))
252 if (!fIncludeWitness
&& it
->GetTx().HasWitness())
254 if (fNeedSizeAccounting
) {
255 uint64_t nTxSize
= ::GetSerializeSize(it
->GetTx(), SER_NETWORK
, PROTOCOL_VERSION
);
256 if (nPotentialBlockSize
+ nTxSize
>= nBlockMaxSize
) {
259 nPotentialBlockSize
+= nTxSize
;
265 bool BlockAssembler::TestForBlock(CTxMemPool::txiter iter
)
267 if (nBlockWeight
+ iter
->GetTxWeight() >= nBlockMaxWeight
) {
268 // If the block is so close to full that no more txs will fit
269 // or if we've tried more than 50 times to fill remaining space
270 // then flag that the block is finished
271 if (nBlockWeight
> nBlockMaxWeight
- 400 || lastFewTxs
> 50) {
272 blockFinished
= true;
275 // Once we're within 4000 weight of a full block, only look at 50 more txs
276 // to try to fill the remaining space.
277 if (nBlockWeight
> nBlockMaxWeight
- 4000) {
283 if (fNeedSizeAccounting
) {
284 if (nBlockSize
+ ::GetSerializeSize(iter
->GetTx(), SER_NETWORK
, PROTOCOL_VERSION
) >= nBlockMaxSize
) {
285 if (nBlockSize
> nBlockMaxSize
- 100 || lastFewTxs
> 50) {
286 blockFinished
= true;
289 if (nBlockSize
> nBlockMaxSize
- 1000) {
296 if (nBlockSigOpsCost
+ iter
->GetSigOpCost() >= MAX_BLOCK_SIGOPS_COST
) {
297 // If the block has room for no more sig ops then
298 // flag that the block is finished
299 if (nBlockSigOpsCost
> MAX_BLOCK_SIGOPS_COST
- 8) {
300 blockFinished
= true;
303 // Otherwise attempt to find another tx with fewer sigops
304 // to put in the block.
308 // Must check that lock times are still valid
309 // This can be removed once MTP is always enforced
310 // as long as reorgs keep the mempool consistent.
311 if (!IsFinalTx(iter
->GetTx(), nHeight
, nLockTimeCutoff
))
317 void BlockAssembler::AddToBlock(CTxMemPool::txiter iter
)
319 pblock
->vtx
.emplace_back(iter
->GetSharedTx());
320 pblocktemplate
->vTxFees
.push_back(iter
->GetFee());
321 pblocktemplate
->vTxSigOpsCost
.push_back(iter
->GetSigOpCost());
322 if (fNeedSizeAccounting
) {
323 nBlockSize
+= ::GetSerializeSize(iter
->GetTx(), SER_NETWORK
, PROTOCOL_VERSION
);
325 nBlockWeight
+= iter
->GetTxWeight();
327 nBlockSigOpsCost
+= iter
->GetSigOpCost();
328 nFees
+= iter
->GetFee();
329 inBlock
.insert(iter
);
331 bool fPrintPriority
= GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY
);
332 if (fPrintPriority
) {
333 double dPriority
= iter
->GetPriority(nHeight
);
335 mempool
.ApplyDeltas(iter
->GetTx().GetHash(), dPriority
, dummy
);
336 LogPrintf("priority %.1f fee %s txid %s\n",
338 CFeeRate(iter
->GetModifiedFee(), iter
->GetTxSize()).ToString(),
339 iter
->GetTx().GetHash().ToString());
343 void BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries
& alreadyAdded
,
344 indexed_modified_transaction_set
&mapModifiedTx
)
346 BOOST_FOREACH(const CTxMemPool::txiter it
, alreadyAdded
) {
347 CTxMemPool::setEntries descendants
;
348 mempool
.CalculateDescendants(it
, descendants
);
349 // Insert all descendants (not yet in block) into the modified set
350 BOOST_FOREACH(CTxMemPool::txiter desc
, descendants
) {
351 if (alreadyAdded
.count(desc
))
353 modtxiter mit
= mapModifiedTx
.find(desc
);
354 if (mit
== mapModifiedTx
.end()) {
355 CTxMemPoolModifiedEntry
modEntry(desc
);
356 modEntry
.nSizeWithAncestors
-= it
->GetTxSize();
357 modEntry
.nModFeesWithAncestors
-= it
->GetModifiedFee();
358 modEntry
.nSigOpCostWithAncestors
-= it
->GetSigOpCost();
359 mapModifiedTx
.insert(modEntry
);
361 mapModifiedTx
.modify(mit
, update_for_parent_inclusion(it
));
367 // Skip entries in mapTx that are already in a block or are present
368 // in mapModifiedTx (which implies that the mapTx ancestor state is
369 // stale due to ancestor inclusion in the block)
370 // Also skip transactions that we've already failed to add. This can happen if
371 // we consider a transaction in mapModifiedTx and it fails: we can then
372 // potentially consider it again while walking mapTx. It's currently
373 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
374 // failedTx and avoid re-evaluation, since the re-evaluation would be using
375 // cached size/sigops/fee values that are not actually correct.
376 bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it
, indexed_modified_transaction_set
&mapModifiedTx
, CTxMemPool::setEntries
&failedTx
)
378 assert (it
!= mempool
.mapTx
.end());
379 if (mapModifiedTx
.count(it
) || inBlock
.count(it
) || failedTx
.count(it
))
384 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries
& package
, CTxMemPool::txiter entry
, std::vector
<CTxMemPool::txiter
>& sortedEntries
)
386 // Sort package by ancestor count
387 // If a transaction A depends on transaction B, then A's ancestor count
388 // must be greater than B's. So this is sufficient to validly order the
389 // transactions for block inclusion.
390 sortedEntries
.clear();
391 sortedEntries
.insert(sortedEntries
.begin(), package
.begin(), package
.end());
392 std::sort(sortedEntries
.begin(), sortedEntries
.end(), CompareTxIterByAncestorCount());
395 // This transaction selection algorithm orders the mempool based
396 // on feerate of a transaction including all unconfirmed ancestors.
397 // Since we don't remove transactions from the mempool as we select them
398 // for block inclusion, we need an alternate method of updating the feerate
399 // of a transaction with its not-yet-selected ancestors as we go.
400 // This is accomplished by walking the in-mempool descendants of selected
401 // transactions and storing a temporary modified state in mapModifiedTxs.
402 // Each time through the loop, we compare the best transaction in
403 // mapModifiedTxs with the next transaction in the mempool to decide what
404 // transaction package to work on next.
405 void BlockAssembler::addPackageTxs()
407 // mapModifiedTx will store sorted packages after they are modified
408 // because some of their txs are already in the block
409 indexed_modified_transaction_set mapModifiedTx
;
410 // Keep track of entries that failed inclusion, to avoid duplicate work
411 CTxMemPool::setEntries failedTx
;
413 // Start by adding all descendants of previously added txs to mapModifiedTx
414 // and modifying them for their already included ancestors
415 UpdatePackagesForAdded(inBlock
, mapModifiedTx
);
417 CTxMemPool::indexed_transaction_set::index
<ancestor_score
>::type::iterator mi
= mempool
.mapTx
.get
<ancestor_score
>().begin();
418 CTxMemPool::txiter iter
;
419 while (mi
!= mempool
.mapTx
.get
<ancestor_score
>().end() || !mapModifiedTx
.empty())
421 // First try to find a new transaction in mapTx to evaluate.
422 if (mi
!= mempool
.mapTx
.get
<ancestor_score
>().end() &&
423 SkipMapTxEntry(mempool
.mapTx
.project
<0>(mi
), mapModifiedTx
, failedTx
)) {
428 // Now that mi is not stale, determine which transaction to evaluate:
429 // the next entry from mapTx, or the best from mapModifiedTx?
430 bool fUsingModified
= false;
432 modtxscoreiter modit
= mapModifiedTx
.get
<ancestor_score
>().begin();
433 if (mi
== mempool
.mapTx
.get
<ancestor_score
>().end()) {
434 // We're out of entries in mapTx; use the entry from mapModifiedTx
436 fUsingModified
= true;
438 // Try to compare the mapTx entry to the mapModifiedTx entry
439 iter
= mempool
.mapTx
.project
<0>(mi
);
440 if (modit
!= mapModifiedTx
.get
<ancestor_score
>().end() &&
441 CompareModifiedEntry()(*modit
, CTxMemPoolModifiedEntry(iter
))) {
442 // The best entry in mapModifiedTx has higher score
443 // than the one from mapTx.
444 // Switch which transaction (package) to consider
446 fUsingModified
= true;
448 // Either no entry in mapModifiedTx, or it's worse than mapTx.
449 // Increment mi for the next loop iteration.
454 // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
455 // contain anything that is inBlock.
456 assert(!inBlock
.count(iter
));
458 uint64_t packageSize
= iter
->GetSizeWithAncestors();
459 CAmount packageFees
= iter
->GetModFeesWithAncestors();
460 int64_t packageSigOpsCost
= iter
->GetSigOpCostWithAncestors();
461 if (fUsingModified
) {
462 packageSize
= modit
->nSizeWithAncestors
;
463 packageFees
= modit
->nModFeesWithAncestors
;
464 packageSigOpsCost
= modit
->nSigOpCostWithAncestors
;
467 if (packageFees
< blockMinFeeRate
.GetFee(packageSize
)) {
468 // Everything else we might consider has a lower fee rate
472 if (!TestPackage(packageSize
, packageSigOpsCost
)) {
473 if (fUsingModified
) {
474 // Since we always look at the best entry in mapModifiedTx,
475 // we must erase failed entries so that we can consider the
476 // next best entry on the next loop iteration
477 mapModifiedTx
.get
<ancestor_score
>().erase(modit
);
478 failedTx
.insert(iter
);
483 CTxMemPool::setEntries ancestors
;
484 uint64_t nNoLimit
= std::numeric_limits
<uint64_t>::max();
486 mempool
.CalculateMemPoolAncestors(*iter
, ancestors
, nNoLimit
, nNoLimit
, nNoLimit
, nNoLimit
, dummy
, false);
488 onlyUnconfirmed(ancestors
);
489 ancestors
.insert(iter
);
491 // Test if all tx's are Final
492 if (!TestPackageTransactions(ancestors
)) {
493 if (fUsingModified
) {
494 mapModifiedTx
.get
<ancestor_score
>().erase(modit
);
495 failedTx
.insert(iter
);
500 // Package can be added. Sort the entries in a valid order.
501 std::vector
<CTxMemPool::txiter
> sortedEntries
;
502 SortForBlock(ancestors
, iter
, sortedEntries
);
504 for (size_t i
=0; i
<sortedEntries
.size(); ++i
) {
505 AddToBlock(sortedEntries
[i
]);
506 // Erase from the modified set, if present
507 mapModifiedTx
.erase(sortedEntries
[i
]);
510 // Update transactions that depend on each of these
511 UpdatePackagesForAdded(ancestors
, mapModifiedTx
);
515 void BlockAssembler::addPriorityTxs()
517 // How much of the block should be dedicated to high-priority transactions,
518 // included regardless of the fees they pay
519 unsigned int nBlockPrioritySize
= GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE
);
520 nBlockPrioritySize
= std::min(nBlockMaxSize
, nBlockPrioritySize
);
522 if (nBlockPrioritySize
== 0) {
526 bool fSizeAccounting
= fNeedSizeAccounting
;
527 fNeedSizeAccounting
= true;
529 // This vector will be sorted into a priority queue:
530 std::vector
<TxCoinAgePriority
> vecPriority
;
531 TxCoinAgePriorityCompare pricomparer
;
532 std::map
<CTxMemPool::txiter
, double, CTxMemPool::CompareIteratorByHash
> waitPriMap
;
533 typedef std::map
<CTxMemPool::txiter
, double, CTxMemPool::CompareIteratorByHash
>::iterator waitPriIter
;
534 double actualPriority
= -1;
536 vecPriority
.reserve(mempool
.mapTx
.size());
537 for (CTxMemPool::indexed_transaction_set::iterator mi
= mempool
.mapTx
.begin();
538 mi
!= mempool
.mapTx
.end(); ++mi
)
540 double dPriority
= mi
->GetPriority(nHeight
);
542 mempool
.ApplyDeltas(mi
->GetTx().GetHash(), dPriority
, dummy
);
543 vecPriority
.push_back(TxCoinAgePriority(dPriority
, mi
));
545 std::make_heap(vecPriority
.begin(), vecPriority
.end(), pricomparer
);
547 CTxMemPool::txiter iter
;
548 while (!vecPriority
.empty() && !blockFinished
) { // add a tx from priority queue to fill the blockprioritysize
549 iter
= vecPriority
.front().second
;
550 actualPriority
= vecPriority
.front().first
;
551 std::pop_heap(vecPriority
.begin(), vecPriority
.end(), pricomparer
);
552 vecPriority
.pop_back();
554 // If tx already in block, skip
555 if (inBlock
.count(iter
)) {
556 assert(false); // shouldn't happen for priority txs
560 // cannot accept witness transactions into a non-witness block
561 if (!fIncludeWitness
&& iter
->GetTx().HasWitness())
564 // If tx is dependent on other mempool txs which haven't yet been included
565 // then put it in the waitSet
566 if (isStillDependent(iter
)) {
567 waitPriMap
.insert(std::make_pair(iter
, actualPriority
));
571 // If this tx fits in the block add it, otherwise keep looping
572 if (TestForBlock(iter
)) {
575 // If now that this txs is added we've surpassed our desired priority size
576 // or have dropped below the AllowFreeThreshold, then we're done adding priority txs
577 if (nBlockSize
>= nBlockPrioritySize
|| !AllowFree(actualPriority
)) {
581 // This tx was successfully added, so
582 // add transactions that depend on this one to the priority queue to try again
583 BOOST_FOREACH(CTxMemPool::txiter child
, mempool
.GetMemPoolChildren(iter
))
585 waitPriIter wpiter
= waitPriMap
.find(child
);
586 if (wpiter
!= waitPriMap
.end()) {
587 vecPriority
.push_back(TxCoinAgePriority(wpiter
->second
,child
));
588 std::push_heap(vecPriority
.begin(), vecPriority
.end(), pricomparer
);
589 waitPriMap
.erase(wpiter
);
594 fNeedSizeAccounting
= fSizeAccounting
;
597 void IncrementExtraNonce(CBlock
* pblock
, const CBlockIndex
* pindexPrev
, unsigned int& nExtraNonce
)
599 // Update nExtraNonce
600 static uint256 hashPrevBlock
;
601 if (hashPrevBlock
!= pblock
->hashPrevBlock
)
604 hashPrevBlock
= pblock
->hashPrevBlock
;
607 unsigned int nHeight
= pindexPrev
->nHeight
+1; // Height first in coinbase required for block.version=2
608 CMutableTransaction
txCoinbase(*pblock
->vtx
[0]);
609 txCoinbase
.vin
[0].scriptSig
= (CScript() << nHeight
<< CScriptNum(nExtraNonce
)) + COINBASE_FLAGS
;
610 assert(txCoinbase
.vin
[0].scriptSig
.size() <= 100);
612 pblock
->vtx
[0] = MakeTransactionRef(std::move(txCoinbase
));
613 pblock
->hashMerkleRoot
= BlockMerkleRoot(*pblock
);