35 #include <boost/thread.hpp> 62 int64_t nOldTime = pblock->
nTime;
65 if (nOldTime < nNewTime)
66 pblock->
nTime = nNewTime;
72 return nNewTime - nOldTime;
140 assert(pindexPrev !=
nullptr);
164 int nPackagesSelected = 0;
165 int nDescendantsUpdated = 0;
175 coinbaseTx.
vin.resize(1);
176 coinbaseTx.
vin[0].prevout.SetNull();
177 coinbaseTx.
vout.resize(1);
178 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
181 pblock->
vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
200 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));
207 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
210 testSet.erase(iit++);
245 pblock->
vtx.emplace_back(iter->GetSharedTx());
251 nFees += iter->GetFee();
254 bool fPrintPriority =
gArgs.
GetBoolArg(
"-printpriority", DEFAULT_PRINTPRIORITY);
255 if (fPrintPriority) {
257 CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
258 iter->GetTx().GetHash().
ToString());
265 int nDescendantsUpdated = 0;
271 if (alreadyAdded.count(desc))
273 ++nDescendantsUpdated;
274 modtxiter mit = mapModifiedTx.find(desc);
275 if (mit == mapModifiedTx.end()) {
280 mapModifiedTx.insert(modEntry);
286 return nDescendantsUpdated;
301 return mapModifiedTx.count(it) ||
inBlock.count(it) || failedTx.count(it);
310 sortedEntries.clear();
311 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
343 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
344 int64_t nConsecutiveFailed = 0;
357 bool fUsingModified =
false;
363 fUsingModified =
true;
373 fUsingModified =
true;
385 uint64_t packageSize = iter->GetSizeWithAncestors();
386 CAmount packageFees = iter->GetModFeesWithAncestors();
387 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
388 if (fUsingModified) {
389 packageSize = modit->nSizeWithAncestors;
390 packageFees = modit->nModFeesWithAncestors;
391 packageSigOpsCost = modit->nSigOpCostWithAncestors;
399 if (!
TestPackage(packageSize, packageSigOpsCost)) {
400 if (fUsingModified) {
405 failedTx.insert(iter);
408 ++nConsecutiveFailed;
410 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
nBlockWeight >
419 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
424 ancestors.insert(iter);
428 if (fUsingModified) {
430 failedTx.insert(iter);
436 nConsecutiveFailed = 0;
439 std::vector<CTxMemPool::txiter> sortedEntries;
442 for (
size_t i=0; i<sortedEntries.size(); ++i) {
445 mapModifiedTx.erase(sortedEntries[i]);
468 assert(txCoinbase.
vin[0].scriptSig.size() <= 100);
470 pblock->
vtx[0] = MakeTransactionRef(std::move(txCoinbase));
484 return error(
"ProcessBlockFound -- generated block is stale");
493 std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
495 return error(
"ProcessBlockFound -- ProcessNewBlock() failed, block not accepted");
516 unsigned int nExtraNonce = 0;
526 LogPrintf(
"RavenMiner -- Wallet not available\n");
536 std::shared_ptr<CReserveScript> coinbaseScript;
545 if (coinbaseScript->reserveScript.empty())
552 if (!coinbaseScript || coinbaseScript->reserveScript.empty())
554 throw std::runtime_error(
"No coinbase script available (mining requires a wallet)");
578 if(!pindexPrev)
break;
584 if (!pblocktemplate.get())
586 LogPrintf(
"RavenMiner -- Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
589 CBlock *pblock = &pblocktemplate->block;
592 LogPrintf(
"RavenMiner -- Running miner with %u transactions in block (%u bytes)\n", pblock->
vtx.size(),
611 LogPrintf(
"RavenMiner:\n proof-of-work found\n hash: %s\n target: %s\n", hash.
GetHex(), hashTarget.
GetHex());
612 ProcessBlockFound(pblock, chainparams);
614 coinbaseScript->KeepScript();
619 throw boost::thread_interrupted();
628 if ((pblock->
nNonce & 0xFF) == 0)
633 boost::this_thread::interruption_point();
637 if (pblock->
nNonce >= 0xffff0000)
656 catch (
const boost::thread_interrupted&)
661 catch (
const std::runtime_error &e)
663 LogPrintf(
"RavenMiner -- runtime error: %s\n", e.what());
671 static boost::thread_group* minerThreads = NULL;
677 if (minerThreads != NULL)
679 minerThreads->interrupt_all();
684 if (nThreads == 0 || !fGenerate)
687 minerThreads =
new boost::thread_group();
694 for (
int i = 0; i < nThreads; i++){
695 minerThreads->create_thread(boost::bind(&RavenMiner, 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)
void MilliSleep(int64_t n)
void SortForBlock(const CTxMemPool::setEntries &package, CTxMemPool::txiter entry, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
unsigned int GetMaxBlockWeight()
bool EnsureWalletIsAvailable(CWallet *const pwallet, bool avoidException)
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
std::string ToString() const
CCriticalSection cs_main
Global state.
CTxMemPool::setEntries inBlock
std::unique_ptr< CBlockTemplate > pblocktemplate
void BlockFound(const uint256 &)
bool fPowAllowMinDifficultyBlocks
std::set< txiter, CompareIteratorByHash > setEntries
std::vector< CWalletRef > vpwallets
CWallet * GetFirstWallet()
CChainParams defines various tweakable parameters of a given instance of the Raven 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)
int GenerateRavens(bool fGenerate, int nThreads, const CChainParams &chainparams)
arith_uint256 UintToArith256(const uint256 &a)
uint64_t nLastBlockWeight
uint64_t nMiningTimeStart
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
indexed_transaction_set mapTx
int64_t CAmount
Amount in corbies (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)
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
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)
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
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
Try to calculate all in-mempool ancestors of entry.
Parameters that influence chain consensus.
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
std::vector< CTxOut > vout
int UpdatePackagesForAdded(const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
uint64_t nSizeWithAncestors
#define LogPrint(category,...)
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
uint64_t nBlockSigOpsCost
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
Return true if given transaction from mapTx has already been evaluated, or if the transaction's cache...
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 >, CompareModifiedEntry > >> indexed_modified_transaction_set
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...
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.
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
A mutable version of CTransaction.
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 physical cores available on the current system.
const Consensus::Params & GetConsensus() const
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.