34 #include <boost/thread.hpp> 49 int64_t nOldTime = pblock->
nTime;
52 if (nOldTime < nNewTime)
53 pblock->
nTime = nNewTime;
59 return nNewTime - nOldTime;
125 assert(pindexPrev !=
nullptr);
137 nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
152 int nPackagesSelected = 0;
153 int nDescendantsUpdated = 0;
163 coinbaseTx.
vin.resize(1);
164 coinbaseTx.
vin[0].prevout.SetNull();
165 coinbaseTx.
vout.resize(1);
166 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
169 pblock->
vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
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));
195 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
198 testSet.erase(iit++);
233 pblock->
vtx.emplace_back(iter->GetSharedTx());
239 nFees += iter->GetFee();
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());
253 int nDescendantsUpdated = 0;
259 if (alreadyAdded.count(desc))
261 ++nDescendantsUpdated;
262 modtxiter mit = mapModifiedTx.find(desc);
263 if (mit == mapModifiedTx.end()) {
268 mapModifiedTx.insert(modEntry);
274 return nDescendantsUpdated;
288 assert (it !=
mempool.mapTx.end());
289 return mapModifiedTx.count(it) ||
inBlock.count(it) || failedTx.count(it);
298 sortedEntries.clear();
299 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
325 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi =
mempool.mapTx.
get<
ancestor_score>().begin();
331 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
332 int64_t nConsecutiveFailed = 0;
345 bool fUsingModified =
false;
351 fUsingModified =
true;
354 iter =
mempool.mapTx.project<0>(mi);
361 fUsingModified =
true;
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;
387 if (!
TestPackage(packageSize, packageSigOpsCost)) {
388 if (fUsingModified) {
393 failedTx.insert(iter);
396 ++nConsecutiveFailed;
398 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
nBlockWeight >
407 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
412 ancestors.insert(iter);
416 if (fUsingModified) {
418 failedTx.insert(iter);
424 nConsecutiveFailed = 0;
427 std::vector<CTxMemPool::txiter> sortedEntries;
430 for (
size_t i=0; i<sortedEntries.size(); ++i) {
433 mapModifiedTx.erase(sortedEntries[i]);
453 unsigned int nHeight = pindexPrev->
nHeight+1;
456 assert(txCoinbase.
vin[0].scriptSig.size() <= 100);
458 pblock->
vtx[0] = MakeTransactionRef(std::move(txCoinbase));
464 LogPrintf(
"%s\n", pblock->
ToString());
465 LogPrintf(
"generated %s\n",
FormatMoney(pblock->
vtx[0]->vout[0].nValue));
471 return error(
"ProcessBlockFound -- generated block is stale");
480 std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
482 return error(
"ProcessBlockFound -- ProcessNewBlock() failed, block not accepted");
489 while (vpwallets.size() == 0) {
492 if (vpwallets.size() == 0)
494 return vpwallets[0].get();
499 LogPrintf(
"BSHA3 Miner -- started\n");
503 unsigned int nExtraNonce = 0;
509 LogPrintf(
"BSHA3 Miner -- Wallet not available\n");
512 if (pWallet ==
nullptr)
513 LogPrintf(
"pWallet is null\n");
516 std::shared_ptr<CReserveScript> coinbaseScript;
523 LogPrintf(
"coinbaseScript is null\n");
525 if (coinbaseScript->reserveScript.empty())
526 LogPrintf(
"coinbaseScript is empty\n");
532 if (!coinbaseScript || coinbaseScript->reserveScript.empty())
534 throw std::runtime_error(
"No coinbase script available (mining requires a wallet)");
558 if(!pindexPrev)
break;
562 std::unique_ptr<CBlockTemplate> pblocktemplate(
BlockAssembler(
Params()).CreateNewBlock(coinbaseScript->reserveScript));
564 if (!pblocktemplate.get())
566 LogPrintf(
"BSHA3 Miner -- Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
569 CBlock *pblock = &pblocktemplate->block;
572 LogPrintf(
"BSHA3 Miner -- Running miner with %u transactions in block (%u bytes)\n", pblock->
vtx.size(),
591 LogPrintf(
"BSHA3 Miner:\n proof-of-work found\n hash: %s\n target: %s\n", hash.
GetHex(), hashTarget.
GetHex());
592 ProcessBlockFound(pblock, chainparams);
594 coinbaseScript->KeepScript();
599 throw boost::thread_interrupted();
608 if ((pblock->
nNonce & 0xFF) == 0)
613 boost::this_thread::interruption_point();
617 if (pblock->
nNonce >= 0xffff0000)
636 catch (
const boost::thread_interrupted&)
638 LogPrintf(
"BSHA3 Miner -- terminated\n");
641 catch (
const std::runtime_error &e)
643 LogPrintf(
"BSHA3 Miner -- runtime error: %s\n", e.what());
651 static boost::thread_group* minerThreads =
nullptr;
657 if (minerThreads !=
nullptr)
659 minerThreads->interrupt_all();
661 minerThreads =
nullptr;
664 if (nThreads == 0 || !fGenerate)
667 minerThreads =
new boost::thread_group();
674 for (
int i = 0; i < nThreads; i++){
675 minerThreads->create_thread(boost::bind(&BSHA3Miner, boost::cref(chainparams)));
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
bool TestPackageTransactions(const CTxMemPool::setEntries &package)
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
unsigned int nBlockMaxWeight
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
void SetThreadPriority(int nPriority)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
void MilliSleep(int64_t n)
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
bool EnsureWalletIsAvailable(CWallet *const pwallet, bool avoidException)
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
std::string ToString() const
CTxMemPool::setEntries inBlock
std::unique_ptr< CBlockTemplate > pblocktemplate
void BlockFound(const uint256 &)
bool fPowAllowMinDifficultyBlocks
std::set< txiter, CompareIteratorByHash > setEntries
CWallet * GetFirstWallet()
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
void RenameThread(const char *name)
size_t GetSerializeSize(const T &t, int nVersion=0)
arith_uint256 UintToArith256(const uint256 &a)
uint64_t nLastBlockWeight
uint64_t nMiningTimeStart
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
int64_t CAmount
Amount in satoshis (Can be negative)
uint256 GetBlockHash() const
#define THREAD_PRIORITY_NORMAL
#define THREAD_PRIORITY_LOWEST
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
const CChainParams & chainparams
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
boost::multi_index_container< CTxMemPoolModifiedEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< modifiedentry_iter, CompareCTxMemPoolIter >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareTxMemPoolEntryByAncestorFee > >> indexed_modified_transaction_set
bool MiningRequiresPeers() const
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
BlockAssembler(const CChainParams ¶ms)
CMainSignals & GetMainSignals()
Generate a new block, without valid proof-of-work.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
bool ParseMoney(const std::string &str, CAmount &nRet)
void SortForBlock(const CTxMemPool::setEntries &package, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
Parameters that influence chain consensus.
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
std::vector< CTxOut > vout
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
uint64_t nSizeWithAncestors
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
uint64_t nBlockSigOpsCost
Capture information about block/transaction validation.
CAmount nModFeesWithAncestors
void GetScriptForMining(std::shared_ptr< CReserveScript > &script)
std::vector< CTransactionRef > vtx
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
int64_t GetAdjustedTime()
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Return true if given transaction from mapTx has already been evaluated, or if the transaction's cache...
CCriticalSection cs_wallets
int64_t nSigOpCostWithAncestors
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
std::string GetHex() const
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Fee rate in satoshis per kilobyte: CAmount / kB.
std::unique_ptr< CConnman > g_connman
unsigned int GetTransactionsUpdated() const
bool error(const char *fmt, const Args &... args)
arith_uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Check whether witness commitments are required for block.
void resetBlock()
Clear the block's state and prepare for assembling a new block.
A mutable version of CTransaction.
CTransactionRef get(const uint256 &hash) const
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time...
std::string GetHex() const
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
std::string ToString() const
int nHeight
height of the entry in the chain. The genesis block has height 0
int GetNumCores()
Return the number of cores available on the current system.
const Consensus::Params & GetConsensus() const
int GenerateBSHA3s(bool fGenerate, int nThreads, const CChainParams &chainparams)
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
int UpdatePackagesForAdded(const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn, bool fMineWitnessTx=true)
Construct a new block template with coinbase to scriptPubKeyIn.
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.