[test] Add getblockchaininfo functional test
[bitcoinplatinum.git] / src / miner.cpp
bloba9989f4b1723614836e4cb8fd970dd019fe88ed8
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.
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/tx_verify.h"
14 #include "consensus/merkle.h"
15 #include "consensus/validation.h"
16 #include "hash.h"
17 #include "validation.h"
18 #include "net.h"
19 #include "policy/feerate.h"
20 #include "policy/policy.h"
21 #include "pow.h"
22 #include "primitives/transaction.h"
23 #include "script/standard.h"
24 #include "timedata.h"
25 #include "txmempool.h"
26 #include "util.h"
27 #include "utilmoneystr.h"
28 #include "validationinterface.h"
30 #include <algorithm>
31 #include <queue>
32 #include <utility>
34 //////////////////////////////////////////////////////////////////////////////
36 // BitcoinMiner
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 fee rate of a transaction combined with all
43 // its ancestors.
45 uint64_t nLastBlockTx = 0;
46 uint64_t nLastBlockWeight = 0;
48 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
50 int64_t nOldTime = pblock->nTime;
51 int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
53 if (nOldTime < nNewTime)
54 pblock->nTime = nNewTime;
56 // Updating time can change work required on testnet:
57 if (consensusParams.fPowAllowMinDifficultyBlocks)
58 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
60 return nNewTime - nOldTime;
63 BlockAssembler::Options::Options() {
64 blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
65 nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
68 BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params)
70 blockMinFeeRate = options.blockMinFeeRate;
71 // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
72 nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
75 static BlockAssembler::Options DefaultOptions(const CChainParams& params)
77 // Block resource limits
78 // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
79 // If only one is given, only restrict the specified resource.
80 // If both are given, restrict both.
81 BlockAssembler::Options options;
82 options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
83 if (gArgs.IsArgSet("-blockmintxfee")) {
84 CAmount n = 0;
85 ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n);
86 options.blockMinFeeRate = CFeeRate(n);
87 } else {
88 options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
90 return options;
93 BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {}
95 void BlockAssembler::resetBlock()
97 inBlock.clear();
99 // Reserve space for coinbase tx
100 nBlockWeight = 4000;
101 nBlockSigOpsCost = 400;
102 fIncludeWitness = false;
104 // These counters do not include coinbase tx
105 nBlockTx = 0;
106 nFees = 0;
109 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx)
111 int64_t nTimeStart = GetTimeMicros();
113 resetBlock();
115 pblocktemplate.reset(new CBlockTemplate());
117 if(!pblocktemplate.get())
118 return nullptr;
119 pblock = &pblocktemplate->block; // pointer for convenience
121 // Add dummy coinbase tx as first transaction
122 pblock->vtx.emplace_back();
123 pblocktemplate->vTxFees.push_back(-1); // updated at end
124 pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
126 LOCK2(cs_main, mempool.cs);
127 CBlockIndex* pindexPrev = chainActive.Tip();
128 assert(pindexPrev != nullptr);
129 nHeight = pindexPrev->nHeight + 1;
131 pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
132 // -regtest only: allow overriding block.nVersion with
133 // -blockversion=N to test forking scenarios
134 if (chainparams.MineBlocksOnDemand())
135 pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
137 pblock->nTime = GetAdjustedTime();
138 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
140 nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
141 ? nMedianTimePast
142 : pblock->GetBlockTime();
144 // Decide whether to include witness transactions
145 // This is only needed in case the witness softfork activation is reverted
146 // (which would require a very deep reorganization) or when
147 // -promiscuousmempoolflags is used.
148 // TODO: replace this with a call to main to assess validity of a mempool
149 // transaction (which in most cases can be a no-op).
150 fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
152 int nPackagesSelected = 0;
153 int nDescendantsUpdated = 0;
154 addPackageTxs(nPackagesSelected, nDescendantsUpdated);
156 int64_t nTime1 = GetTimeMicros();
158 nLastBlockTx = nBlockTx;
159 nLastBlockWeight = nBlockWeight;
161 // Create coinbase transaction.
162 CMutableTransaction coinbaseTx;
163 coinbaseTx.vin.resize(1);
164 coinbaseTx.vin[0].prevout.SetNull();
165 coinbaseTx.vout.resize(1);
166 coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
167 coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
168 coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
169 pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
170 pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
171 pblocktemplate->vTxFees[0] = -nFees;
173 LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
175 // Fill in header
176 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
177 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
178 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
179 pblock->nNonce = 0;
180 pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
182 CValidationState state;
183 if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
184 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
186 int64_t nTime2 = GetTimeMicros();
188 LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
190 return std::move(pblocktemplate);
193 void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
195 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
196 // Only test txs not already in the block
197 if (inBlock.count(*iit)) {
198 testSet.erase(iit++);
200 else {
201 iit++;
206 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
208 // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
209 if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
210 return false;
211 if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
212 return false;
213 return true;
216 // Perform transaction-level checks before adding to block:
217 // - transaction finality (locktime)
218 // - premature witness (in case segwit transactions are added to mempool before
219 // segwit activation)
220 bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
222 for (const CTxMemPool::txiter it : package) {
223 if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
224 return false;
225 if (!fIncludeWitness && it->GetTx().HasWitness())
226 return false;
228 return true;
231 void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
233 pblock->vtx.emplace_back(iter->GetSharedTx());
234 pblocktemplate->vTxFees.push_back(iter->GetFee());
235 pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
236 nBlockWeight += iter->GetTxWeight();
237 ++nBlockTx;
238 nBlockSigOpsCost += iter->GetSigOpCost();
239 nFees += iter->GetFee();
240 inBlock.insert(iter);
242 bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
243 if (fPrintPriority) {
244 LogPrintf("fee %s txid %s\n",
245 CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
246 iter->GetTx().GetHash().ToString());
250 int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
251 indexed_modified_transaction_set &mapModifiedTx)
253 int nDescendantsUpdated = 0;
254 for (const CTxMemPool::txiter it : alreadyAdded) {
255 CTxMemPool::setEntries descendants;
256 mempool.CalculateDescendants(it, descendants);
257 // Insert all descendants (not yet in block) into the modified set
258 for (CTxMemPool::txiter desc : descendants) {
259 if (alreadyAdded.count(desc))
260 continue;
261 ++nDescendantsUpdated;
262 modtxiter mit = mapModifiedTx.find(desc);
263 if (mit == mapModifiedTx.end()) {
264 CTxMemPoolModifiedEntry modEntry(desc);
265 modEntry.nSizeWithAncestors -= it->GetTxSize();
266 modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
267 modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
268 mapModifiedTx.insert(modEntry);
269 } else {
270 mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
274 return nDescendantsUpdated;
277 // Skip entries in mapTx that are already in a block or are present
278 // in mapModifiedTx (which implies that the mapTx ancestor state is
279 // stale due to ancestor inclusion in the block)
280 // Also skip transactions that we've already failed to add. This can happen if
281 // we consider a transaction in mapModifiedTx and it fails: we can then
282 // potentially consider it again while walking mapTx. It's currently
283 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
284 // failedTx and avoid re-evaluation, since the re-evaluation would be using
285 // cached size/sigops/fee values that are not actually correct.
286 bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
288 assert (it != mempool.mapTx.end());
289 return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
292 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
294 // Sort package by ancestor count
295 // If a transaction A depends on transaction B, then A's ancestor count
296 // must be greater than B's. So this is sufficient to validly order the
297 // transactions for block inclusion.
298 sortedEntries.clear();
299 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
300 std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
303 // This transaction selection algorithm orders the mempool based
304 // on feerate of a transaction including all unconfirmed ancestors.
305 // Since we don't remove transactions from the mempool as we select them
306 // for block inclusion, we need an alternate method of updating the feerate
307 // of a transaction with its not-yet-selected ancestors as we go.
308 // This is accomplished by walking the in-mempool descendants of selected
309 // transactions and storing a temporary modified state in mapModifiedTxs.
310 // Each time through the loop, we compare the best transaction in
311 // mapModifiedTxs with the next transaction in the mempool to decide what
312 // transaction package to work on next.
313 void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
315 // mapModifiedTx will store sorted packages after they are modified
316 // because some of their txs are already in the block
317 indexed_modified_transaction_set mapModifiedTx;
318 // Keep track of entries that failed inclusion, to avoid duplicate work
319 CTxMemPool::setEntries failedTx;
321 // Start by adding all descendants of previously added txs to mapModifiedTx
322 // and modifying them for their already included ancestors
323 UpdatePackagesForAdded(inBlock, mapModifiedTx);
325 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
326 CTxMemPool::txiter iter;
328 // Limit the number of attempts to add transactions to the block when it is
329 // close to full; this is just a simple heuristic to finish quickly if the
330 // mempool has a lot of entries.
331 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
332 int64_t nConsecutiveFailed = 0;
334 while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
336 // First try to find a new transaction in mapTx to evaluate.
337 if (mi != mempool.mapTx.get<ancestor_score>().end() &&
338 SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
339 ++mi;
340 continue;
343 // Now that mi is not stale, determine which transaction to evaluate:
344 // the next entry from mapTx, or the best from mapModifiedTx?
345 bool fUsingModified = false;
347 modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
348 if (mi == mempool.mapTx.get<ancestor_score>().end()) {
349 // We're out of entries in mapTx; use the entry from mapModifiedTx
350 iter = modit->iter;
351 fUsingModified = true;
352 } else {
353 // Try to compare the mapTx entry to the mapModifiedTx entry
354 iter = mempool.mapTx.project<0>(mi);
355 if (modit != mapModifiedTx.get<ancestor_score>().end() &&
356 CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
357 // The best entry in mapModifiedTx has higher score
358 // than the one from mapTx.
359 // Switch which transaction (package) to consider
360 iter = modit->iter;
361 fUsingModified = true;
362 } else {
363 // Either no entry in mapModifiedTx, or it's worse than mapTx.
364 // Increment mi for the next loop iteration.
365 ++mi;
369 // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
370 // contain anything that is inBlock.
371 assert(!inBlock.count(iter));
373 uint64_t packageSize = iter->GetSizeWithAncestors();
374 CAmount packageFees = iter->GetModFeesWithAncestors();
375 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
376 if (fUsingModified) {
377 packageSize = modit->nSizeWithAncestors;
378 packageFees = modit->nModFeesWithAncestors;
379 packageSigOpsCost = modit->nSigOpCostWithAncestors;
382 if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
383 // Everything else we might consider has a lower fee rate
384 return;
387 if (!TestPackage(packageSize, packageSigOpsCost)) {
388 if (fUsingModified) {
389 // Since we always look at the best entry in mapModifiedTx,
390 // we must erase failed entries so that we can consider the
391 // next best entry on the next loop iteration
392 mapModifiedTx.get<ancestor_score>().erase(modit);
393 failedTx.insert(iter);
396 ++nConsecutiveFailed;
398 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
399 nBlockMaxWeight - 4000) {
400 // Give up if we're close to full and haven't succeeded in a while
401 break;
403 continue;
406 CTxMemPool::setEntries ancestors;
407 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
408 std::string dummy;
409 mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
411 onlyUnconfirmed(ancestors);
412 ancestors.insert(iter);
414 // Test if all tx's are Final
415 if (!TestPackageTransactions(ancestors)) {
416 if (fUsingModified) {
417 mapModifiedTx.get<ancestor_score>().erase(modit);
418 failedTx.insert(iter);
420 continue;
423 // This transaction will make it in; reset the failed counter.
424 nConsecutiveFailed = 0;
426 // Package can be added. Sort the entries in a valid order.
427 std::vector<CTxMemPool::txiter> sortedEntries;
428 SortForBlock(ancestors, iter, sortedEntries);
430 for (size_t i=0; i<sortedEntries.size(); ++i) {
431 AddToBlock(sortedEntries[i]);
432 // Erase from the modified set, if present
433 mapModifiedTx.erase(sortedEntries[i]);
436 ++nPackagesSelected;
438 // Update transactions that depend on each of these
439 nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
443 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
445 // Update nExtraNonce
446 static uint256 hashPrevBlock;
447 if (hashPrevBlock != pblock->hashPrevBlock)
449 nExtraNonce = 0;
450 hashPrevBlock = pblock->hashPrevBlock;
452 ++nExtraNonce;
453 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
454 CMutableTransaction txCoinbase(*pblock->vtx[0]);
455 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
456 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
458 pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
459 pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);