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.
10 #include "chainparams.h"
12 #include "consensus/consensus.h"
13 #include "consensus/tx_verify.h"
14 #include "consensus/merkle.h"
15 #include "consensus/validation.h"
17 #include "validation.h"
19 #include "policy/feerate.h"
20 #include "policy/policy.h"
22 #include "primitives/transaction.h"
23 #include "script/standard.h"
25 #include "txmempool.h"
27 #include "utilmoneystr.h"
28 #include "validationinterface.h"
34 //////////////////////////////////////////////////////////////////////////////
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
45 uint64_t nLastBlockTx
= 0;
46 uint64_t nLastBlockSize
= 0;
47 uint64_t nLastBlockWeight
= 0;
49 int64_t UpdateTime(CBlockHeader
* pblock
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
)
51 int64_t nOldTime
= pblock
->nTime
;
52 int64_t nNewTime
= std::max(pindexPrev
->GetMedianTimePast()+1, GetAdjustedTime());
54 if (nOldTime
< nNewTime
)
55 pblock
->nTime
= nNewTime
;
57 // Updating time can change work required on testnet:
58 if (consensusParams
.fPowAllowMinDifficultyBlocks
)
59 pblock
->nBits
= GetNextWorkRequired(pindexPrev
, pblock
, consensusParams
);
61 return nNewTime
- nOldTime
;
64 BlockAssembler::Options::Options() {
65 blockMinFeeRate
= CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE
);
66 nBlockMaxWeight
= DEFAULT_BLOCK_MAX_WEIGHT
;
67 nBlockMaxSize
= DEFAULT_BLOCK_MAX_SIZE
;
70 BlockAssembler::BlockAssembler(const CChainParams
& params
, const Options
& options
) : chainparams(params
)
72 blockMinFeeRate
= options
.blockMinFeeRate
;
73 // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
74 nBlockMaxWeight
= std::max
<size_t>(4000, std::min
<size_t>(MAX_BLOCK_WEIGHT
- 4000, options
.nBlockMaxWeight
));
75 // Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
76 nBlockMaxSize
= std::max
<size_t>(1000, std::min
<size_t>(MAX_BLOCK_SERIALIZED_SIZE
- 1000, options
.nBlockMaxSize
));
77 // Whether we need to account for byte usage (in addition to weight usage)
78 fNeedSizeAccounting
= (nBlockMaxSize
< MAX_BLOCK_SERIALIZED_SIZE
- 1000);
81 static BlockAssembler::Options
DefaultOptions(const CChainParams
& params
)
83 // Block resource limits
84 // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
85 // If only one is given, only restrict the specified resource.
86 // If both are given, restrict both.
87 BlockAssembler::Options options
;
88 options
.nBlockMaxWeight
= DEFAULT_BLOCK_MAX_WEIGHT
;
89 options
.nBlockMaxSize
= DEFAULT_BLOCK_MAX_SIZE
;
90 bool fWeightSet
= false;
91 if (IsArgSet("-blockmaxweight")) {
92 options
.nBlockMaxWeight
= GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT
);
93 options
.nBlockMaxSize
= MAX_BLOCK_SERIALIZED_SIZE
;
96 if (IsArgSet("-blockmaxsize")) {
97 options
.nBlockMaxSize
= GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE
);
99 options
.nBlockMaxWeight
= options
.nBlockMaxSize
* WITNESS_SCALE_FACTOR
;
102 if (IsArgSet("-blockmintxfee")) {
104 ParseMoney(GetArg("-blockmintxfee", ""), n
);
105 options
.blockMinFeeRate
= CFeeRate(n
);
107 options
.blockMinFeeRate
= CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE
);
112 BlockAssembler::BlockAssembler(const CChainParams
& params
) : BlockAssembler(params
, DefaultOptions(params
)) {}
114 void BlockAssembler::resetBlock()
118 // Reserve space for coinbase tx
121 nBlockSigOpsCost
= 400;
122 fIncludeWitness
= false;
124 // These counters do not include coinbase tx
129 std::unique_ptr
<CBlockTemplate
> BlockAssembler::CreateNewBlock(const CScript
& scriptPubKeyIn
, bool fMineWitnessTx
)
131 int64_t nTimeStart
= GetTimeMicros();
135 pblocktemplate
.reset(new CBlockTemplate());
137 if(!pblocktemplate
.get())
139 pblock
= &pblocktemplate
->block
; // pointer for convenience
141 // Add dummy coinbase tx as first transaction
142 pblock
->vtx
.emplace_back();
143 pblocktemplate
->vTxFees
.push_back(-1); // updated at end
144 pblocktemplate
->vTxSigOpsCost
.push_back(-1); // updated at end
146 LOCK2(cs_main
, mempool
.cs
);
147 CBlockIndex
* pindexPrev
= chainActive
.Tip();
148 nHeight
= pindexPrev
->nHeight
+ 1;
150 pblock
->nVersion
= ComputeBlockVersion(pindexPrev
, chainparams
.GetConsensus());
151 // -regtest only: allow overriding block.nVersion with
152 // -blockversion=N to test forking scenarios
153 if (chainparams
.MineBlocksOnDemand())
154 pblock
->nVersion
= GetArg("-blockversion", pblock
->nVersion
);
156 pblock
->nTime
= GetAdjustedTime();
157 const int64_t nMedianTimePast
= pindexPrev
->GetMedianTimePast();
159 nLockTimeCutoff
= (STANDARD_LOCKTIME_VERIFY_FLAGS
& LOCKTIME_MEDIAN_TIME_PAST
)
161 : pblock
->GetBlockTime();
163 // Decide whether to include witness transactions
164 // This is only needed in case the witness softfork activation is reverted
165 // (which would require a very deep reorganization) or when
166 // -promiscuousmempoolflags is used.
167 // TODO: replace this with a call to main to assess validity of a mempool
168 // transaction (which in most cases can be a no-op).
169 fIncludeWitness
= IsWitnessEnabled(pindexPrev
, chainparams
.GetConsensus()) && fMineWitnessTx
;
171 int nPackagesSelected
= 0;
172 int nDescendantsUpdated
= 0;
173 addPackageTxs(nPackagesSelected
, nDescendantsUpdated
);
175 int64_t nTime1
= GetTimeMicros();
177 nLastBlockTx
= nBlockTx
;
178 nLastBlockSize
= nBlockSize
;
179 nLastBlockWeight
= nBlockWeight
;
181 // Create coinbase transaction.
182 CMutableTransaction coinbaseTx
;
183 coinbaseTx
.vin
.resize(1);
184 coinbaseTx
.vin
[0].prevout
.SetNull();
185 coinbaseTx
.vout
.resize(1);
186 coinbaseTx
.vout
[0].scriptPubKey
= scriptPubKeyIn
;
187 coinbaseTx
.vout
[0].nValue
= nFees
+ GetBlockSubsidy(nHeight
, chainparams
.GetConsensus());
188 coinbaseTx
.vin
[0].scriptSig
= CScript() << nHeight
<< OP_0
;
189 pblock
->vtx
[0] = MakeTransactionRef(std::move(coinbaseTx
));
190 pblocktemplate
->vchCoinbaseCommitment
= GenerateCoinbaseCommitment(*pblock
, pindexPrev
, chainparams
.GetConsensus());
191 pblocktemplate
->vTxFees
[0] = -nFees
;
193 uint64_t nSerializeSize
= GetSerializeSize(*pblock
, SER_NETWORK
, PROTOCOL_VERSION
);
194 LogPrintf("CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize
, GetBlockWeight(*pblock
), nBlockTx
, nFees
, nBlockSigOpsCost
);
197 pblock
->hashPrevBlock
= pindexPrev
->GetBlockHash();
198 UpdateTime(pblock
, chainparams
.GetConsensus(), pindexPrev
);
199 pblock
->nBits
= GetNextWorkRequired(pindexPrev
, pblock
, chainparams
.GetConsensus());
201 pblocktemplate
->vTxSigOpsCost
[0] = WITNESS_SCALE_FACTOR
* GetLegacySigOpCount(*pblock
->vtx
[0]);
203 CValidationState state
;
204 if (!TestBlockValidity(state
, chainparams
, *pblock
, pindexPrev
, false, false)) {
205 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__
, FormatStateMessage(state
)));
207 int64_t nTime2
= GetTimeMicros();
209 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
));
211 return std::move(pblocktemplate
);
214 void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries
& testSet
)
216 for (CTxMemPool::setEntries::iterator iit
= testSet
.begin(); iit
!= testSet
.end(); ) {
217 // Only test txs not already in the block
218 if (inBlock
.count(*iit
)) {
219 testSet
.erase(iit
++);
227 bool BlockAssembler::TestPackage(uint64_t packageSize
, int64_t packageSigOpsCost
)
229 // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
230 if (nBlockWeight
+ WITNESS_SCALE_FACTOR
* packageSize
>= nBlockMaxWeight
)
232 if (nBlockSigOpsCost
+ packageSigOpsCost
>= MAX_BLOCK_SIGOPS_COST
)
237 // Perform transaction-level checks before adding to block:
238 // - transaction finality (locktime)
239 // - premature witness (in case segwit transactions are added to mempool before
240 // segwit activation)
241 // - serialized size (in case -blockmaxsize is in use)
242 bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries
& package
)
244 uint64_t nPotentialBlockSize
= nBlockSize
; // only used with fNeedSizeAccounting
245 BOOST_FOREACH (const CTxMemPool::txiter it
, package
) {
246 if (!IsFinalTx(it
->GetTx(), nHeight
, nLockTimeCutoff
))
248 if (!fIncludeWitness
&& it
->GetTx().HasWitness())
250 if (fNeedSizeAccounting
) {
251 uint64_t nTxSize
= ::GetSerializeSize(it
->GetTx(), SER_NETWORK
, PROTOCOL_VERSION
);
252 if (nPotentialBlockSize
+ nTxSize
>= nBlockMaxSize
) {
255 nPotentialBlockSize
+= nTxSize
;
261 void BlockAssembler::AddToBlock(CTxMemPool::txiter iter
)
263 pblock
->vtx
.emplace_back(iter
->GetSharedTx());
264 pblocktemplate
->vTxFees
.push_back(iter
->GetFee());
265 pblocktemplate
->vTxSigOpsCost
.push_back(iter
->GetSigOpCost());
266 if (fNeedSizeAccounting
) {
267 nBlockSize
+= ::GetSerializeSize(iter
->GetTx(), SER_NETWORK
, PROTOCOL_VERSION
);
269 nBlockWeight
+= iter
->GetTxWeight();
271 nBlockSigOpsCost
+= iter
->GetSigOpCost();
272 nFees
+= iter
->GetFee();
273 inBlock
.insert(iter
);
275 bool fPrintPriority
= GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY
);
276 if (fPrintPriority
) {
277 LogPrintf("fee %s txid %s\n",
278 CFeeRate(iter
->GetModifiedFee(), iter
->GetTxSize()).ToString(),
279 iter
->GetTx().GetHash().ToString());
283 int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries
& alreadyAdded
,
284 indexed_modified_transaction_set
&mapModifiedTx
)
286 int nDescendantsUpdated
= 0;
287 BOOST_FOREACH(const CTxMemPool::txiter it
, alreadyAdded
) {
288 CTxMemPool::setEntries descendants
;
289 mempool
.CalculateDescendants(it
, descendants
);
290 // Insert all descendants (not yet in block) into the modified set
291 BOOST_FOREACH(CTxMemPool::txiter desc
, descendants
) {
292 if (alreadyAdded
.count(desc
))
294 ++nDescendantsUpdated
;
295 modtxiter mit
= mapModifiedTx
.find(desc
);
296 if (mit
== mapModifiedTx
.end()) {
297 CTxMemPoolModifiedEntry
modEntry(desc
);
298 modEntry
.nSizeWithAncestors
-= it
->GetTxSize();
299 modEntry
.nModFeesWithAncestors
-= it
->GetModifiedFee();
300 modEntry
.nSigOpCostWithAncestors
-= it
->GetSigOpCost();
301 mapModifiedTx
.insert(modEntry
);
303 mapModifiedTx
.modify(mit
, update_for_parent_inclusion(it
));
307 return nDescendantsUpdated
;
310 // Skip entries in mapTx that are already in a block or are present
311 // in mapModifiedTx (which implies that the mapTx ancestor state is
312 // stale due to ancestor inclusion in the block)
313 // Also skip transactions that we've already failed to add. This can happen if
314 // we consider a transaction in mapModifiedTx and it fails: we can then
315 // potentially consider it again while walking mapTx. It's currently
316 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
317 // failedTx and avoid re-evaluation, since the re-evaluation would be using
318 // cached size/sigops/fee values that are not actually correct.
319 bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it
, indexed_modified_transaction_set
&mapModifiedTx
, CTxMemPool::setEntries
&failedTx
)
321 assert (it
!= mempool
.mapTx
.end());
322 return mapModifiedTx
.count(it
) || inBlock
.count(it
) || failedTx
.count(it
);
325 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries
& package
, CTxMemPool::txiter entry
, std::vector
<CTxMemPool::txiter
>& sortedEntries
)
327 // Sort package by ancestor count
328 // If a transaction A depends on transaction B, then A's ancestor count
329 // must be greater than B's. So this is sufficient to validly order the
330 // transactions for block inclusion.
331 sortedEntries
.clear();
332 sortedEntries
.insert(sortedEntries
.begin(), package
.begin(), package
.end());
333 std::sort(sortedEntries
.begin(), sortedEntries
.end(), CompareTxIterByAncestorCount());
336 // This transaction selection algorithm orders the mempool based
337 // on feerate of a transaction including all unconfirmed ancestors.
338 // Since we don't remove transactions from the mempool as we select them
339 // for block inclusion, we need an alternate method of updating the feerate
340 // of a transaction with its not-yet-selected ancestors as we go.
341 // This is accomplished by walking the in-mempool descendants of selected
342 // transactions and storing a temporary modified state in mapModifiedTxs.
343 // Each time through the loop, we compare the best transaction in
344 // mapModifiedTxs with the next transaction in the mempool to decide what
345 // transaction package to work on next.
346 void BlockAssembler::addPackageTxs(int &nPackagesSelected
, int &nDescendantsUpdated
)
348 // mapModifiedTx will store sorted packages after they are modified
349 // because some of their txs are already in the block
350 indexed_modified_transaction_set mapModifiedTx
;
351 // Keep track of entries that failed inclusion, to avoid duplicate work
352 CTxMemPool::setEntries failedTx
;
354 // Start by adding all descendants of previously added txs to mapModifiedTx
355 // and modifying them for their already included ancestors
356 UpdatePackagesForAdded(inBlock
, mapModifiedTx
);
358 CTxMemPool::indexed_transaction_set::index
<ancestor_score
>::type::iterator mi
= mempool
.mapTx
.get
<ancestor_score
>().begin();
359 CTxMemPool::txiter iter
;
361 // Limit the number of attempts to add transactions to the block when it is
362 // close to full; this is just a simple heuristic to finish quickly if the
363 // mempool has a lot of entries.
364 const int64_t MAX_CONSECUTIVE_FAILURES
= 1000;
365 int64_t nConsecutiveFailed
= 0;
367 while (mi
!= mempool
.mapTx
.get
<ancestor_score
>().end() || !mapModifiedTx
.empty())
369 // First try to find a new transaction in mapTx to evaluate.
370 if (mi
!= mempool
.mapTx
.get
<ancestor_score
>().end() &&
371 SkipMapTxEntry(mempool
.mapTx
.project
<0>(mi
), mapModifiedTx
, failedTx
)) {
376 // Now that mi is not stale, determine which transaction to evaluate:
377 // the next entry from mapTx, or the best from mapModifiedTx?
378 bool fUsingModified
= false;
380 modtxscoreiter modit
= mapModifiedTx
.get
<ancestor_score
>().begin();
381 if (mi
== mempool
.mapTx
.get
<ancestor_score
>().end()) {
382 // We're out of entries in mapTx; use the entry from mapModifiedTx
384 fUsingModified
= true;
386 // Try to compare the mapTx entry to the mapModifiedTx entry
387 iter
= mempool
.mapTx
.project
<0>(mi
);
388 if (modit
!= mapModifiedTx
.get
<ancestor_score
>().end() &&
389 CompareModifiedEntry()(*modit
, CTxMemPoolModifiedEntry(iter
))) {
390 // The best entry in mapModifiedTx has higher score
391 // than the one from mapTx.
392 // Switch which transaction (package) to consider
394 fUsingModified
= true;
396 // Either no entry in mapModifiedTx, or it's worse than mapTx.
397 // Increment mi for the next loop iteration.
402 // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
403 // contain anything that is inBlock.
404 assert(!inBlock
.count(iter
));
406 uint64_t packageSize
= iter
->GetSizeWithAncestors();
407 CAmount packageFees
= iter
->GetModFeesWithAncestors();
408 int64_t packageSigOpsCost
= iter
->GetSigOpCostWithAncestors();
409 if (fUsingModified
) {
410 packageSize
= modit
->nSizeWithAncestors
;
411 packageFees
= modit
->nModFeesWithAncestors
;
412 packageSigOpsCost
= modit
->nSigOpCostWithAncestors
;
415 if (packageFees
< blockMinFeeRate
.GetFee(packageSize
)) {
416 // Everything else we might consider has a lower fee rate
420 if (!TestPackage(packageSize
, packageSigOpsCost
)) {
421 if (fUsingModified
) {
422 // Since we always look at the best entry in mapModifiedTx,
423 // we must erase failed entries so that we can consider the
424 // next best entry on the next loop iteration
425 mapModifiedTx
.get
<ancestor_score
>().erase(modit
);
426 failedTx
.insert(iter
);
429 ++nConsecutiveFailed
;
431 if (nConsecutiveFailed
> MAX_CONSECUTIVE_FAILURES
&& nBlockWeight
>
432 nBlockMaxWeight
- 4000) {
433 // Give up if we're close to full and haven't succeeded in a while
439 CTxMemPool::setEntries ancestors
;
440 uint64_t nNoLimit
= std::numeric_limits
<uint64_t>::max();
442 mempool
.CalculateMemPoolAncestors(*iter
, ancestors
, nNoLimit
, nNoLimit
, nNoLimit
, nNoLimit
, dummy
, false);
444 onlyUnconfirmed(ancestors
);
445 ancestors
.insert(iter
);
447 // Test if all tx's are Final
448 if (!TestPackageTransactions(ancestors
)) {
449 if (fUsingModified
) {
450 mapModifiedTx
.get
<ancestor_score
>().erase(modit
);
451 failedTx
.insert(iter
);
456 // This transaction will make it in; reset the failed counter.
457 nConsecutiveFailed
= 0;
459 // Package can be added. Sort the entries in a valid order.
460 std::vector
<CTxMemPool::txiter
> sortedEntries
;
461 SortForBlock(ancestors
, iter
, sortedEntries
);
463 for (size_t i
=0; i
<sortedEntries
.size(); ++i
) {
464 AddToBlock(sortedEntries
[i
]);
465 // Erase from the modified set, if present
466 mapModifiedTx
.erase(sortedEntries
[i
]);
471 // Update transactions that depend on each of these
472 nDescendantsUpdated
+= UpdatePackagesForAdded(ancestors
, mapModifiedTx
);
476 void IncrementExtraNonce(CBlock
* pblock
, const CBlockIndex
* pindexPrev
, unsigned int& nExtraNonce
)
478 // Update nExtraNonce
479 static uint256 hashPrevBlock
;
480 if (hashPrevBlock
!= pblock
->hashPrevBlock
)
483 hashPrevBlock
= pblock
->hashPrevBlock
;
486 unsigned int nHeight
= pindexPrev
->nHeight
+1; // Height first in coinbase required for block.version=2
487 CMutableTransaction
txCoinbase(*pblock
->vtx
[0]);
488 txCoinbase
.vin
[0].scriptSig
= (CScript() << nHeight
<< CScriptNum(nExtraNonce
)) + COINBASE_FLAGS
;
489 assert(txCoinbase
.vin
[0].scriptSig
.size() <= 100);
491 pblock
->vtx
[0] = MakeTransactionRef(std::move(txCoinbase
));
492 pblock
->hashMerkleRoot
= BlockMerkleRoot(*pblock
);