You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

miner.cpp 18KB

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