71
73
return nNewTime - nOldTime;
74
CBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& scriptPubKeyIn)
77
auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
76
BlockAssembler::BlockAssembler(const CChainParams& _chainparams)
77
: chainparams(_chainparams)
79
// Block resource limits
80
// If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
81
// If only one is given, only restrict the specified resource.
82
// If both are given, restrict both.
83
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
84
nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
85
bool fWeightSet = false;
86
if (mapArgs.count("-blockmaxweight")) {
87
nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
88
nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
91
if (mapArgs.count("-blockmaxsize")) {
92
nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
94
nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR;
98
// Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
99
nBlockMaxWeight = std::max((unsigned int)4000, std::min((unsigned int)(MAX_BLOCK_WEIGHT-4000), nBlockMaxWeight));
100
// Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
101
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SERIALIZED_SIZE-1000), nBlockMaxSize));
103
// Whether we need to account for byte usage (in addition to weight usage)
104
fNeedSizeAccounting = (nBlockMaxSize < MAX_BLOCK_SERIALIZED_SIZE-1000);
107
void BlockAssembler::resetBlock()
111
// Reserve space for coinbase tx
114
nBlockSigOpsCost = 400;
115
fIncludeWitness = false;
117
// These counters do not include coinbase tx
122
blockFinished = false;
125
CBlockTemplate* BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn)
129
pblocktemplate.reset(new CBlockTemplate());
78
131
if(!pblocktemplate.get())
80
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
83
CMutableTransaction txNew;
85
txNew.vin[0].prevout.SetNull();
87
txNew.vout[0].scriptPubKey = scriptPubKeyIn;
133
pblock = &pblocktemplate->block; // pointer for convenience
89
135
// Add dummy coinbase tx as first transaction
90
136
pblock->vtx.push_back(CTransaction());
91
137
pblocktemplate->vTxFees.push_back(-1); // updated at end
92
pblocktemplate->vTxSigOps.push_back(-1); // updated at end
94
// Largest block you're willing to create:
95
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
96
// Limit to between 1K and MAX_BLOCK_SIZE-1K for sanity:
97
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
138
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
140
LOCK2(cs_main, mempool.cs);
141
CBlockIndex* pindexPrev = chainActive.Tip();
142
nHeight = pindexPrev->nHeight + 1;
144
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
145
// -regtest only: allow overriding block.nVersion with
146
// -blockversion=N to test forking scenarios
147
if (chainparams.MineBlocksOnDemand())
148
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
150
pblock->nTime = GetAdjustedTime();
151
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
153
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
155
: pblock->GetBlockTime();
157
// Decide whether to include witness transactions
158
// This is only needed in case the witness softfork activation is reverted
159
// (which would require a very deep reorganization) or when
160
// -promiscuousmempoolflags is used.
161
// TODO: replace this with a call to main to assess validity of a mempool
162
// transaction (which in most cases can be a no-op).
163
fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus());
168
nLastBlockTx = nBlockTx;
169
nLastBlockSize = nBlockSize;
170
nLastBlockWeight = nBlockWeight;
171
LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOpsCost);
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] = coinbaseTx;
182
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
183
pblocktemplate->vTxFees[0] = -nFees;
186
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
187
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
188
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
190
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(pblock->vtx[0]);
192
CValidationState state;
193
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
194
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
197
return pblocktemplate.release();
200
bool BlockAssembler::isStillDependent(CTxMemPool::txiter iter)
202
BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
204
if (!inBlock.count(parent)) {
211
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
213
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
214
// Only test txs not already in the block
215
if (inBlock.count(*iit)) {
216
testSet.erase(iit++);
224
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
226
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
227
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
229
if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
234
// Perform transaction-level checks before adding to block:
235
// - transaction finality (locktime)
236
// - premature witness (in case segwit transactions are added to mempool before
237
// segwit activation)
238
// - serialized size (in case -blockmaxsize is in use)
239
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
241
uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
242
BOOST_FOREACH (const CTxMemPool::txiter it, package) {
243
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
245
if (!fIncludeWitness && !it->GetTx().wit.IsNull())
247
if (fNeedSizeAccounting) {
248
uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
249
if (nPotentialBlockSize + nTxSize >= nBlockMaxSize) {
252
nPotentialBlockSize += nTxSize;
258
bool BlockAssembler::TestForBlock(CTxMemPool::txiter iter)
260
if (nBlockWeight + iter->GetTxWeight() >= nBlockMaxWeight) {
261
// If the block is so close to full that no more txs will fit
262
// or if we've tried more than 50 times to fill remaining space
263
// then flag that the block is finished
264
if (nBlockWeight > nBlockMaxWeight - 400 || lastFewTxs > 50) {
265
blockFinished = true;
268
// Once we're within 4000 weight of a full block, only look at 50 more txs
269
// to try to fill the remaining space.
270
if (nBlockWeight > nBlockMaxWeight - 4000) {
276
if (fNeedSizeAccounting) {
277
if (nBlockSize + ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION) >= nBlockMaxSize) {
278
if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
279
blockFinished = true;
282
if (nBlockSize > nBlockMaxSize - 1000) {
289
if (nBlockSigOpsCost + iter->GetSigOpCost() >= MAX_BLOCK_SIGOPS_COST) {
290
// If the block has room for no more sig ops then
291
// flag that the block is finished
292
if (nBlockSigOpsCost > MAX_BLOCK_SIGOPS_COST - 8) {
293
blockFinished = true;
296
// Otherwise attempt to find another tx with fewer sigops
297
// to put in the block.
301
// Must check that lock times are still valid
302
// This can be removed once MTP is always enforced
303
// as long as reorgs keep the mempool consistent.
304
if (!IsFinalTx(iter->GetTx(), nHeight, nLockTimeCutoff))
310
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
312
pblock->vtx.push_back(iter->GetTx());
313
pblocktemplate->vTxFees.push_back(iter->GetFee());
314
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
315
if (fNeedSizeAccounting) {
316
nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
318
nBlockWeight += iter->GetTxWeight();
320
nBlockSigOpsCost += iter->GetSigOpCost();
321
nFees += iter->GetFee();
322
inBlock.insert(iter);
324
bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
325
if (fPrintPriority) {
326
double dPriority = iter->GetPriority(nHeight);
328
mempool.ApplyDeltas(iter->GetTx().GetHash(), dPriority, dummy);
329
LogPrintf("priority %.1f fee %s txid %s\n",
331
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
332
iter->GetTx().GetHash().ToString());
336
void BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
337
indexed_modified_transaction_set &mapModifiedTx)
339
BOOST_FOREACH(const CTxMemPool::txiter it, alreadyAdded) {
340
CTxMemPool::setEntries descendants;
341
mempool.CalculateDescendants(it, descendants);
342
// Insert all descendants (not yet in block) into the modified set
343
BOOST_FOREACH(CTxMemPool::txiter desc, descendants) {
344
if (alreadyAdded.count(desc))
346
modtxiter mit = mapModifiedTx.find(desc);
347
if (mit == mapModifiedTx.end()) {
348
CTxMemPoolModifiedEntry modEntry(desc);
349
modEntry.nSizeWithAncestors -= it->GetTxSize();
350
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
351
modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
352
mapModifiedTx.insert(modEntry);
354
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
360
// Skip entries in mapTx that are already in a block or are present
361
// in mapModifiedTx (which implies that the mapTx ancestor state is
362
// stale due to ancestor inclusion in the block)
363
// Also skip transactions that we've already failed to add. This can happen if
364
// we consider a transaction in mapModifiedTx and it fails: we can then
365
// potentially consider it again while walking mapTx. It's currently
366
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
367
// failedTx and avoid re-evaluation, since the re-evaluation would be using
368
// cached size/sigops/fee values that are not actually correct.
369
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
371
assert (it != mempool.mapTx.end());
372
if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
377
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
379
// Sort package by ancestor count
380
// If a transaction A depends on transaction B, then A's ancestor count
381
// must be greater than B's. So this is sufficient to validly order the
382
// transactions for block inclusion.
383
sortedEntries.clear();
384
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
385
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
388
// This transaction selection algorithm orders the mempool based
389
// on feerate of a transaction including all unconfirmed ancestors.
390
// Since we don't remove transactions from the mempool as we select them
391
// for block inclusion, we need an alternate method of updating the feerate
392
// of a transaction with its not-yet-selected ancestors as we go.
393
// This is accomplished by walking the in-mempool descendants of selected
394
// transactions and storing a temporary modified state in mapModifiedTxs.
395
// Each time through the loop, we compare the best transaction in
396
// mapModifiedTxs with the next transaction in the mempool to decide what
397
// transaction package to work on next.
398
void BlockAssembler::addPackageTxs()
400
// mapModifiedTx will store sorted packages after they are modified
401
// because some of their txs are already in the block
402
indexed_modified_transaction_set mapModifiedTx;
403
// Keep track of entries that failed inclusion, to avoid duplicate work
404
CTxMemPool::setEntries failedTx;
406
// Start by adding all descendants of previously added txs to mapModifiedTx
407
// and modifying them for their already included ancestors
408
UpdatePackagesForAdded(inBlock, mapModifiedTx);
410
CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
411
CTxMemPool::txiter iter;
412
while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
414
// First try to find a new transaction in mapTx to evaluate.
415
if (mi != mempool.mapTx.get<ancestor_score>().end() &&
416
SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
421
// Now that mi is not stale, determine which transaction to evaluate:
422
// the next entry from mapTx, or the best from mapModifiedTx?
423
bool fUsingModified = false;
425
modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
426
if (mi == mempool.mapTx.get<ancestor_score>().end()) {
427
// We're out of entries in mapTx; use the entry from mapModifiedTx
429
fUsingModified = true;
431
// Try to compare the mapTx entry to the mapModifiedTx entry
432
iter = mempool.mapTx.project<0>(mi);
433
if (modit != mapModifiedTx.get<ancestor_score>().end() &&
434
CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
435
// The best entry in mapModifiedTx has higher score
436
// than the one from mapTx.
437
// Switch which transaction (package) to consider
439
fUsingModified = true;
441
// Either no entry in mapModifiedTx, or it's worse than mapTx.
442
// Increment mi for the next loop iteration.
447
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
448
// contain anything that is inBlock.
449
assert(!inBlock.count(iter));
451
uint64_t packageSize = iter->GetSizeWithAncestors();
452
CAmount packageFees = iter->GetModFeesWithAncestors();
453
int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
454
if (fUsingModified) {
455
packageSize = modit->nSizeWithAncestors;
456
packageFees = modit->nModFeesWithAncestors;
457
packageSigOpsCost = modit->nSigOpCostWithAncestors;
460
if (packageFees < ::minRelayTxFee.GetFee(packageSize)) {
461
// Everything else we might consider has a lower fee rate
465
if (!TestPackage(packageSize, packageSigOpsCost)) {
466
if (fUsingModified) {
467
// Since we always look at the best entry in mapModifiedTx,
468
// we must erase failed entries so that we can consider the
469
// next best entry on the next loop iteration
470
mapModifiedTx.get<ancestor_score>().erase(modit);
471
failedTx.insert(iter);
476
CTxMemPool::setEntries ancestors;
477
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
479
mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
481
onlyUnconfirmed(ancestors);
482
ancestors.insert(iter);
484
// Test if all tx's are Final
485
if (!TestPackageTransactions(ancestors)) {
486
if (fUsingModified) {
487
mapModifiedTx.get<ancestor_score>().erase(modit);
488
failedTx.insert(iter);
493
// Package can be added. Sort the entries in a valid order.
494
vector<CTxMemPool::txiter> sortedEntries;
495
SortForBlock(ancestors, iter, sortedEntries);
497
for (size_t i=0; i<sortedEntries.size(); ++i) {
498
AddToBlock(sortedEntries[i]);
499
// Erase from the modified set, if present
500
mapModifiedTx.erase(sortedEntries[i]);
503
// Update transactions that depend on each of these
504
UpdatePackagesForAdded(ancestors, mapModifiedTx);
508
void BlockAssembler::addPriorityTxs()
99
510
// How much of the block should be dedicated to high-priority transactions,
100
511
// included regardless of the fees they pay
101
512
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
102
513
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
104
// Minimum block size you want to create; block will be filled with free transactions
105
// until there are no more or the block reaches this size:
106
unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
107
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
515
if (nBlockPrioritySize == 0) {
109
// Collect memory pool transactions into the block
110
CTxMemPool::setEntries inBlock;
111
CTxMemPool::setEntries waitSet;
519
bool fSizeAccounting = fNeedSizeAccounting;
520
fNeedSizeAccounting = true;
113
522
// This vector will be sorted into a priority queue:
114
523
vector<TxCoinAgePriority> vecPriority;
117
526
typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
118
527
double actualPriority = -1;
120
std::priority_queue<CTxMemPool::txiter, std::vector<CTxMemPool::txiter>, ScoreCompare> clearedTxs;
121
bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
122
uint64_t nBlockSize = 1000;
123
uint64_t nBlockTx = 0;
124
unsigned int nBlockSigOps = 100;
529
vecPriority.reserve(mempool.mapTx.size());
530
for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
531
mi != mempool.mapTx.end(); ++mi)
129
LOCK2(cs_main, mempool.cs);
130
CBlockIndex* pindexPrev = chainActive.Tip();
131
const int nHeight = pindexPrev->nHeight + 1;
132
pblock->nTime = GetAdjustedTime();
133
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
135
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
136
// -regtest only: allow overriding block.nVersion with
137
// -blockversion=N to test forking scenarios
138
if (chainparams.MineBlocksOnDemand())
139
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
141
int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
143
: pblock->GetBlockTime();
145
bool fPriorityBlock = nBlockPrioritySize > 0;
146
if (fPriorityBlock) {
147
vecPriority.reserve(mempool.mapTx.size());
148
for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
149
mi != mempool.mapTx.end(); ++mi)
151
double dPriority = mi->GetPriority(nHeight);
153
mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
154
vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
156
std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
159
CTxMemPool::indexed_transaction_set::nth_index<3>::type::iterator mi = mempool.mapTx.get<3>().begin();
160
CTxMemPool::txiter iter;
162
while (mi != mempool.mapTx.get<3>().end() || !clearedTxs.empty())
164
bool priorityTx = false;
165
if (fPriorityBlock && !vecPriority.empty()) { // add a tx from priority queue to fill the blockprioritysize
167
iter = vecPriority.front().second;
168
actualPriority = vecPriority.front().first;
169
std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
170
vecPriority.pop_back();
172
else if (clearedTxs.empty()) { // add tx with next highest score
173
iter = mempool.mapTx.project<0>(mi);
176
else { // try to add a previously postponed child tx
177
iter = clearedTxs.top();
181
if (inBlock.count(iter))
182
continue; // could have been added to the priorityBlock
184
const CTransaction& tx = iter->GetTx();
186
bool fOrphan = false;
187
BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
189
if (!inBlock.count(parent)) {
196
waitPriMap.insert(std::make_pair(iter,actualPriority));
198
waitSet.insert(iter);
202
unsigned int nTxSize = iter->GetTxSize();
203
if (fPriorityBlock &&
204
(nBlockSize + nTxSize >= nBlockPrioritySize || !AllowFree(actualPriority))) {
205
fPriorityBlock = false;
209
(iter->GetModifiedFee() < ::minRelayTxFee.GetFee(nTxSize) && nBlockSize >= nBlockMinSize)) {
533
double dPriority = mi->GetPriority(nHeight);
535
mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
536
vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
538
std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
540
CTxMemPool::txiter iter;
541
while (!vecPriority.empty() && !blockFinished) { // add a tx from priority queue to fill the blockprioritysize
542
iter = vecPriority.front().second;
543
actualPriority = vecPriority.front().first;
544
std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
545
vecPriority.pop_back();
547
// If tx already in block, skip
548
if (inBlock.count(iter)) {
549
assert(false); // shouldn't happen for priority txs
553
// cannot accept witness transactions into a non-witness block
554
if (!fIncludeWitness && !iter->GetTx().wit.IsNull())
557
// If tx is dependent on other mempool txs which haven't yet been included
558
// then put it in the waitSet
559
if (isStillDependent(iter)) {
560
waitPriMap.insert(std::make_pair(iter, actualPriority));
564
// If this tx fits in the block add it, otherwise keep looping
565
if (TestForBlock(iter)) {
568
// If now that this txs is added we've surpassed our desired priority size
569
// or have dropped below the AllowFreeThreshold, then we're done adding priority txs
570
if (nBlockSize >= nBlockPrioritySize || !AllowFree(actualPriority)) {
212
if (nBlockSize + nTxSize >= nBlockMaxSize) {
213
if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
216
// Once we're within 1000 bytes of a full block, only look at 50 more txs
217
// to try to fill the remaining space.
218
if (nBlockSize > nBlockMaxSize - 1000) {
224
if (!IsFinalTx(tx, nHeight, nLockTimeCutoff))
227
unsigned int nTxSigOps = iter->GetSigOpCount();
228
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) {
229
if (nBlockSigOps > MAX_BLOCK_SIGOPS - 2) {
235
CAmount nTxFees = iter->GetFee();
237
pblock->vtx.push_back(tx);
238
pblocktemplate->vTxFees.push_back(nTxFees);
239
pblocktemplate->vTxSigOps.push_back(nTxSigOps);
240
nBlockSize += nTxSize;
242
nBlockSigOps += nTxSigOps;
247
double dPriority = iter->GetPriority(nHeight);
249
mempool.ApplyDeltas(tx.GetHash(), dPriority, dummy);
250
LogPrintf("priority %.1f fee %s txid %s\n",
251
dPriority , CFeeRate(iter->GetModifiedFee(), nTxSize).ToString(), tx.GetHash().ToString());
254
inBlock.insert(iter);
256
// Add transactions that depend on this one to the priority queue
574
// This tx was successfully added, so
575
// add transactions that depend on this one to the priority queue to try again
257
576
BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
259
if (fPriorityBlock) {
260
waitPriIter wpiter = waitPriMap.find(child);
261
if (wpiter != waitPriMap.end()) {
262
vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
263
std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
264
waitPriMap.erase(wpiter);
268
if (waitSet.count(child)) {
269
clearedTxs.push(child);
270
waitSet.erase(child);
578
waitPriIter wpiter = waitPriMap.find(child);
579
if (wpiter != waitPriMap.end()) {
580
vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
581
std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
582
waitPriMap.erase(wpiter);
275
nLastBlockTx = nBlockTx;
276
nLastBlockSize = nBlockSize;
277
LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps);
279
// Compute final coinbase transaction.
280
txNew.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
281
txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
282
pblock->vtx[0] = txNew;
283
pblocktemplate->vTxFees[0] = -nFees;
286
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
287
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
288
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
290
pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
292
CValidationState state;
293
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
294
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
298
return pblocktemplate.release();
587
fNeedSizeAccounting = fSizeAccounting;
301
590
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
316
605
pblock->vtx[0] = txCoinbase;
317
606
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
320
//////////////////////////////////////////////////////////////////////////////
326
// ScanHash scans nonces looking for a hash with at least some zero bits.
327
// The nonce is usually preserved between calls, but periodically or if the
328
// nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
331
bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash)
333
// Write the first 76 bytes of the block header to a double-SHA256 state.
335
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
337
assert(ss.size() == 80);
338
hasher.Write((unsigned char*)&ss[0], 76);
343
// Write the last 4 bytes of the block header (the nonce) to a copy of
344
// the double-SHA256 state, and compute the result.
345
CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash);
347
// Return the nonce if the hash has at least some zero bits,
348
// caller will check if it has enough to reach the target
349
if (((uint16_t*)phash)[15] == 0)
352
// If nothing found after trying for a while, return -1
353
if ((nNonce & 0xfff) == 0)
358
static bool ProcessBlockFound(const CBlock* pblock, const CChainParams& chainparams)
360
LogPrintf("%s\n", pblock->ToString());
361
LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
366
if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
367
return error("BitcoinMiner: generated block is stale");
370
// Inform about the new block
371
GetMainSignals().BlockFound(pblock->GetHash());
373
// Process this block the same as if we had received it from another node
374
CValidationState state;
375
if (!ProcessNewBlock(state, chainparams, NULL, pblock, true, NULL))
376
return error("BitcoinMiner: ProcessNewBlock, block not accepted");
381
void static BitcoinMiner(const CChainParams& chainparams)
383
LogPrintf("BitcoinMiner started\n");
384
SetThreadPriority(THREAD_PRIORITY_LOWEST);
385
RenameThread("bitcoin-miner");
387
unsigned int nExtraNonce = 0;
389
boost::shared_ptr<CReserveScript> coinbaseScript;
390
GetMainSignals().ScriptForMining(coinbaseScript);
393
// Throw an error if no script was provided. This can happen
394
// due to some internal error but also if the keypool is empty.
395
// In the latter case, already the pointer is NULL.
396
if (!coinbaseScript || coinbaseScript->reserveScript.empty())
397
throw std::runtime_error("No coinbase script available (mining requires a wallet)");
400
if (chainparams.MiningRequiresPeers()) {
401
// Busy-wait for the network to come online so we don't waste time mining
402
// on an obsolete chain. In regtest mode we expect to fly solo.
407
fvNodesEmpty = vNodes.empty();
409
if (!fvNodesEmpty && !IsInitialBlockDownload())
418
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
419
CBlockIndex* pindexPrev = chainActive.Tip();
421
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(chainparams, coinbaseScript->reserveScript));
422
if (!pblocktemplate.get())
424
LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
427
CBlock *pblock = &pblocktemplate->block;
428
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
430
LogPrintf("Running BitcoinMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
431
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
436
int64_t nStart = GetTime();
437
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
441
// Check if something found
442
if (ScanHash(pblock, nNonce, &hash))
444
if (UintToArith256(hash) <= hashTarget)
447
pblock->nNonce = nNonce;
448
assert(hash == pblock->GetHash());
450
SetThreadPriority(THREAD_PRIORITY_NORMAL);
451
LogPrintf("BitcoinMiner:\n");
452
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
453
ProcessBlockFound(pblock, chainparams);
454
SetThreadPriority(THREAD_PRIORITY_LOWEST);
455
coinbaseScript->KeepScript();
457
// In regression test mode, stop mining after a block is found.
458
if (chainparams.MineBlocksOnDemand())
459
throw boost::thread_interrupted();
465
// Check for stop or if block needs to be rebuilt
466
boost::this_thread::interruption_point();
467
// Regtest mode doesn't require peers
468
if (vNodes.empty() && chainparams.MiningRequiresPeers())
470
if (nNonce >= 0xffff0000)
472
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
474
if (pindexPrev != chainActive.Tip())
477
// Update nTime every few seconds
478
if (UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev) < 0)
479
break; // Recreate the block if the clock has run backwards,
480
// so that we can use the correct time.
481
if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
483
// Changing pblock->nTime can change work required on testnet:
484
hashTarget.SetCompact(pblock->nBits);
489
catch (const boost::thread_interrupted&)
491
LogPrintf("BitcoinMiner terminated\n");
494
catch (const std::runtime_error &e)
496
LogPrintf("BitcoinMiner runtime error: %s\n", e.what());
501
void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams& chainparams)
503
static boost::thread_group* minerThreads = NULL;
506
nThreads = GetNumCores();
508
if (minerThreads != NULL)
510
minerThreads->interrupt_all();
515
if (nThreads == 0 || !fGenerate)
518
minerThreads = new boost::thread_group();
519
for (int i = 0; i < nThreads; i++)
520
minerThreads->create_thread(boost::bind(&BitcoinMiner, boost::cref(chainparams)));