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

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