Remove unused var UNLIKELY_PCT from fees.h
[bitcoinplatinum.git] / src / miner.cpp
blobebf2f21ffd1006ad5b8e7eb846accce0c06f9952
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 "main.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.push_back(CTransaction());
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;
172 LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOpsCost);
174 // Create coinbase transaction.
175 CMutableTransaction coinbaseTx;
176 coinbaseTx.vin.resize(1);
177 coinbaseTx.vin[0].prevout.SetNull();
178 coinbaseTx.vout.resize(1);
179 coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
180 coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
181 coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
182 pblock->vtx[0] = coinbaseTx;
183 pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
184 pblocktemplate->vTxFees[0] = -nFees;
186 // Fill in header
187 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
188 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
189 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
190 pblock->nNonce = 0;
191 pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(pblock->vtx[0]);
193 CValidationState state;
194 if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
195 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
198 return std::move(pblocktemplate);
201 bool BlockAssembler::isStillDependent(CTxMemPool::txiter iter)
203 BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
205 if (!inBlock.count(parent)) {
206 return true;
209 return false;
212 void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
214 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
215 // Only test txs not already in the block
216 if (inBlock.count(*iit)) {
217 testSet.erase(iit++);
219 else {
220 iit++;
225 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
227 // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
228 if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
229 return false;
230 if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
231 return false;
232 return true;
235 // Perform transaction-level checks before adding to block:
236 // - transaction finality (locktime)
237 // - premature witness (in case segwit transactions are added to mempool before
238 // segwit activation)
239 // - serialized size (in case -blockmaxsize is in use)
240 bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
242 uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
243 BOOST_FOREACH (const CTxMemPool::txiter it, package) {
244 if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
245 return false;
246 if (!fIncludeWitness && !it->GetTx().wit.IsNull())
247 return false;
248 if (fNeedSizeAccounting) {
249 uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
250 if (nPotentialBlockSize + nTxSize >= nBlockMaxSize) {
251 return false;
253 nPotentialBlockSize += nTxSize;
256 return true;
259 bool BlockAssembler::TestForBlock(CTxMemPool::txiter iter)
261 if (nBlockWeight + iter->GetTxWeight() >= nBlockMaxWeight) {
262 // If the block is so close to full that no more txs will fit
263 // or if we've tried more than 50 times to fill remaining space
264 // then flag that the block is finished
265 if (nBlockWeight > nBlockMaxWeight - 400 || lastFewTxs > 50) {
266 blockFinished = true;
267 return false;
269 // Once we're within 4000 weight of a full block, only look at 50 more txs
270 // to try to fill the remaining space.
271 if (nBlockWeight > nBlockMaxWeight - 4000) {
272 lastFewTxs++;
274 return false;
277 if (fNeedSizeAccounting) {
278 if (nBlockSize + ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION) >= nBlockMaxSize) {
279 if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
280 blockFinished = true;
281 return false;
283 if (nBlockSize > nBlockMaxSize - 1000) {
284 lastFewTxs++;
286 return false;
290 if (nBlockSigOpsCost + iter->GetSigOpCost() >= MAX_BLOCK_SIGOPS_COST) {
291 // If the block has room for no more sig ops then
292 // flag that the block is finished
293 if (nBlockSigOpsCost > MAX_BLOCK_SIGOPS_COST - 8) {
294 blockFinished = true;
295 return false;
297 // Otherwise attempt to find another tx with fewer sigops
298 // to put in the block.
299 return false;
302 // Must check that lock times are still valid
303 // This can be removed once MTP is always enforced
304 // as long as reorgs keep the mempool consistent.
305 if (!IsFinalTx(iter->GetTx(), nHeight, nLockTimeCutoff))
306 return false;
308 return true;
311 void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
313 pblock->vtx.push_back(iter->GetTx());
314 pblocktemplate->vTxFees.push_back(iter->GetFee());
315 pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
316 if (fNeedSizeAccounting) {
317 nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
319 nBlockWeight += iter->GetTxWeight();
320 ++nBlockTx;
321 nBlockSigOpsCost += iter->GetSigOpCost();
322 nFees += iter->GetFee();
323 inBlock.insert(iter);
325 bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
326 if (fPrintPriority) {
327 double dPriority = iter->GetPriority(nHeight);
328 CAmount dummy;
329 mempool.ApplyDeltas(iter->GetTx().GetHash(), dPriority, dummy);
330 LogPrintf("priority %.1f fee %s txid %s\n",
331 dPriority,
332 CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
333 iter->GetTx().GetHash().ToString());
337 void BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
338 indexed_modified_transaction_set &mapModifiedTx)
340 BOOST_FOREACH(const CTxMemPool::txiter it, alreadyAdded) {
341 CTxMemPool::setEntries descendants;
342 mempool.CalculateDescendants(it, descendants);
343 // Insert all descendants (not yet in block) into the modified set
344 BOOST_FOREACH(CTxMemPool::txiter desc, descendants) {
345 if (alreadyAdded.count(desc))
346 continue;
347 modtxiter mit = mapModifiedTx.find(desc);
348 if (mit == mapModifiedTx.end()) {
349 CTxMemPoolModifiedEntry modEntry(desc);
350 modEntry.nSizeWithAncestors -= it->GetTxSize();
351 modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
352 modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
353 mapModifiedTx.insert(modEntry);
354 } else {
355 mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
361 // Skip entries in mapTx that are already in a block or are present
362 // in mapModifiedTx (which implies that the mapTx ancestor state is
363 // stale due to ancestor inclusion in the block)
364 // Also skip transactions that we've already failed to add. This can happen if
365 // we consider a transaction in mapModifiedTx and it fails: we can then
366 // potentially consider it again while walking mapTx. It's currently
367 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
368 // failedTx and avoid re-evaluation, since the re-evaluation would be using
369 // cached size/sigops/fee values that are not actually correct.
370 bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
372 assert (it != mempool.mapTx.end());
373 if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
374 return true;
375 return false;
378 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
380 // Sort package by ancestor count
381 // If a transaction A depends on transaction B, then A's ancestor count
382 // must be greater than B's. So this is sufficient to validly order the
383 // transactions for block inclusion.
384 sortedEntries.clear();
385 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
386 std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
389 // This transaction selection algorithm orders the mempool based
390 // on feerate of a transaction including all unconfirmed ancestors.
391 // Since we don't remove transactions from the mempool as we select them
392 // for block inclusion, we need an alternate method of updating the feerate
393 // of a transaction with its not-yet-selected ancestors as we go.
394 // This is accomplished by walking the in-mempool descendants of selected
395 // transactions and storing a temporary modified state in mapModifiedTxs.
396 // Each time through the loop, we compare the best transaction in
397 // mapModifiedTxs with the next transaction in the mempool to decide what
398 // transaction package to work on next.
399 void BlockAssembler::addPackageTxs()
401 // mapModifiedTx will store sorted packages after they are modified
402 // because some of their txs are already in the block
403 indexed_modified_transaction_set mapModifiedTx;
404 // Keep track of entries that failed inclusion, to avoid duplicate work
405 CTxMemPool::setEntries failedTx;
407 // Start by adding all descendants of previously added txs to mapModifiedTx
408 // and modifying them for their already included ancestors
409 UpdatePackagesForAdded(inBlock, mapModifiedTx);
411 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
412 CTxMemPool::txiter iter;
413 while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
415 // First try to find a new transaction in mapTx to evaluate.
416 if (mi != mempool.mapTx.get<ancestor_score>().end() &&
417 SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
418 ++mi;
419 continue;
422 // Now that mi is not stale, determine which transaction to evaluate:
423 // the next entry from mapTx, or the best from mapModifiedTx?
424 bool fUsingModified = false;
426 modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
427 if (mi == mempool.mapTx.get<ancestor_score>().end()) {
428 // We're out of entries in mapTx; use the entry from mapModifiedTx
429 iter = modit->iter;
430 fUsingModified = true;
431 } else {
432 // Try to compare the mapTx entry to the mapModifiedTx entry
433 iter = mempool.mapTx.project<0>(mi);
434 if (modit != mapModifiedTx.get<ancestor_score>().end() &&
435 CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
436 // The best entry in mapModifiedTx has higher score
437 // than the one from mapTx.
438 // Switch which transaction (package) to consider
439 iter = modit->iter;
440 fUsingModified = true;
441 } else {
442 // Either no entry in mapModifiedTx, or it's worse than mapTx.
443 // Increment mi for the next loop iteration.
444 ++mi;
448 // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
449 // contain anything that is inBlock.
450 assert(!inBlock.count(iter));
452 uint64_t packageSize = iter->GetSizeWithAncestors();
453 CAmount packageFees = iter->GetModFeesWithAncestors();
454 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
455 if (fUsingModified) {
456 packageSize = modit->nSizeWithAncestors;
457 packageFees = modit->nModFeesWithAncestors;
458 packageSigOpsCost = modit->nSigOpCostWithAncestors;
461 if (packageFees < ::minRelayTxFee.GetFee(packageSize)) {
462 // Everything else we might consider has a lower fee rate
463 return;
466 if (!TestPackage(packageSize, packageSigOpsCost)) {
467 if (fUsingModified) {
468 // Since we always look at the best entry in mapModifiedTx,
469 // we must erase failed entries so that we can consider the
470 // next best entry on the next loop iteration
471 mapModifiedTx.get<ancestor_score>().erase(modit);
472 failedTx.insert(iter);
474 continue;
477 CTxMemPool::setEntries ancestors;
478 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
479 std::string dummy;
480 mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
482 onlyUnconfirmed(ancestors);
483 ancestors.insert(iter);
485 // Test if all tx's are Final
486 if (!TestPackageTransactions(ancestors)) {
487 if (fUsingModified) {
488 mapModifiedTx.get<ancestor_score>().erase(modit);
489 failedTx.insert(iter);
491 continue;
494 // Package can be added. Sort the entries in a valid order.
495 vector<CTxMemPool::txiter> sortedEntries;
496 SortForBlock(ancestors, iter, sortedEntries);
498 for (size_t i=0; i<sortedEntries.size(); ++i) {
499 AddToBlock(sortedEntries[i]);
500 // Erase from the modified set, if present
501 mapModifiedTx.erase(sortedEntries[i]);
504 // Update transactions that depend on each of these
505 UpdatePackagesForAdded(ancestors, mapModifiedTx);
509 void BlockAssembler::addPriorityTxs()
511 // How much of the block should be dedicated to high-priority transactions,
512 // included regardless of the fees they pay
513 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
514 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
516 if (nBlockPrioritySize == 0) {
517 return;
520 bool fSizeAccounting = fNeedSizeAccounting;
521 fNeedSizeAccounting = true;
523 // This vector will be sorted into a priority queue:
524 vector<TxCoinAgePriority> vecPriority;
525 TxCoinAgePriorityCompare pricomparer;
526 std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
527 typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
528 double actualPriority = -1;
530 vecPriority.reserve(mempool.mapTx.size());
531 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
532 mi != mempool.mapTx.end(); ++mi)
534 double dPriority = mi->GetPriority(nHeight);
535 CAmount dummy;
536 mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
537 vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
539 std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
541 CTxMemPool::txiter iter;
542 while (!vecPriority.empty() && !blockFinished) { // add a tx from priority queue to fill the blockprioritysize
543 iter = vecPriority.front().second;
544 actualPriority = vecPriority.front().first;
545 std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
546 vecPriority.pop_back();
548 // If tx already in block, skip
549 if (inBlock.count(iter)) {
550 assert(false); // shouldn't happen for priority txs
551 continue;
554 // cannot accept witness transactions into a non-witness block
555 if (!fIncludeWitness && !iter->GetTx().wit.IsNull())
556 continue;
558 // If tx is dependent on other mempool txs which haven't yet been included
559 // then put it in the waitSet
560 if (isStillDependent(iter)) {
561 waitPriMap.insert(std::make_pair(iter, actualPriority));
562 continue;
565 // If this tx fits in the block add it, otherwise keep looping
566 if (TestForBlock(iter)) {
567 AddToBlock(iter);
569 // If now that this txs is added we've surpassed our desired priority size
570 // or have dropped below the AllowFreeThreshold, then we're done adding priority txs
571 if (nBlockSize >= nBlockPrioritySize || !AllowFree(actualPriority)) {
572 break;
575 // This tx was successfully added, so
576 // add transactions that depend on this one to the priority queue to try again
577 BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
579 waitPriIter wpiter = waitPriMap.find(child);
580 if (wpiter != waitPriMap.end()) {
581 vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
582 std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
583 waitPriMap.erase(wpiter);
588 fNeedSizeAccounting = fSizeAccounting;
591 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
593 // Update nExtraNonce
594 static uint256 hashPrevBlock;
595 if (hashPrevBlock != pblock->hashPrevBlock)
597 nExtraNonce = 0;
598 hashPrevBlock = pblock->hashPrevBlock;
600 ++nExtraNonce;
601 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
602 CMutableTransaction txCoinbase(pblock->vtx[0]);
603 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
604 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
606 pblock->vtx[0] = txCoinbase;
607 pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);