45 #include <boost/algorithm/string/replace.hpp>
46 #include <boost/algorithm/string/join.hpp>
47 #include <boost/bind/bind.hpp>
48 #include <boost/filesystem.hpp>
49 #include <boost/filesystem/fstream.hpp>
50 #include <boost/math/distributions/poisson.hpp>
51 #include <boost/thread.hpp>
54 # error "Dogecoin cannot be compiled without assertions."
106 struct CBlockIndexWorkComparator
119 if (pa < pb)
return false;
120 if (pa > pb)
return true;
134 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
138 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
141 std::vector<CBlockFileInfo> vinfoBlockFile;
142 int nLastBlockFile = 0;
147 bool fCheckForPruning =
false;
155 int32_t nBlockSequenceId = 1;
157 int32_t nBlockReverseSequenceId = -1;
162 std::set<CBlockIndex*> setDirtyBlockIndex;
165 std::set<int> setDirtyFileInfo;
184 this, boost::placeholders::_1,
185 boost::placeholders::_2));
196 this, boost::placeholders::_1,
197 boost::placeholders::_2));
241 if ((int64_t)tx.
nLockTime < ((int64_t)tx.
nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
243 for (
const auto& txin : tx.
vin) {
279 return IsFinalTx(tx, nBlockHeight, nBlockTime);
288 static std::pair<int, int64_t> CalculateSequenceLocks(
const CTransaction &tx,
int flags, std::vector<int>* prevHeights,
const CBlockIndex& block)
290 assert(prevHeights->size() == tx.
vin.size());
298 int64_t nMinTime = -1;
303 bool fEnforceBIP68 =
static_cast<uint32_t
>(tx.
nVersion) >= 2
308 if (!fEnforceBIP68) {
309 return std::make_pair(nMinHeight, nMinTime);
312 for (
size_t txinIndex = 0; txinIndex < tx.
vin.size(); txinIndex++) {
313 const CTxIn& txin = tx.
vin[txinIndex];
320 (*prevHeights)[txinIndex] = 0;
324 int nCoinHeight = (*prevHeights)[txinIndex];
347 return std::make_pair(nMinHeight, nMinTime);
350 static bool EvaluateSequenceLocks(
const CBlockIndex& block, std::pair<int, int64_t> lockPair)
354 if (lockPair.first >= block.
nHeight || lockPair.second >= nBlockTime)
362 return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx,
flags, prevHeights, block));
399 std::pair<int, int64_t> lockPair;
400 if (useExistingLockPoints) {
402 lockPair.first = lp->
height;
403 lockPair.second = lp->
time;
408 std::vector<int> prevheights;
409 prevheights.resize(tx.
vin.size());
410 for (
size_t txinIndex = 0; txinIndex < tx.
vin.size(); txinIndex++) {
411 const CTxIn& txin = tx.
vin[txinIndex];
414 return error(
"%s: Missing input", __func__);
416 if (coins.
nHeight == MEMPOOL_HEIGHT) {
418 prevheights[txinIndex] = tip->
nHeight + 1;
420 prevheights[txinIndex] = coins.
nHeight;
423 lockPair = CalculateSequenceLocks(tx,
flags, &prevheights, index);
425 lp->
height = lockPair.first;
426 lp->
time = lockPair.second;
440 int maxInputHeight = 0;
441 BOOST_FOREACH(
int height, prevheights) {
443 if (height != tip->
nHeight+1) {
444 maxInputHeight = std::max(maxInputHeight, height);
450 return EvaluateSequenceLocks(index, lockPair);
456 unsigned int nSigOps = 0;
457 for (
const auto& txin : tx.
vin)
461 for (
const auto& txout : tx.
vout)
463 nSigOps += txout.scriptPubKey.GetSigOpCount(
false);
473 unsigned int nSigOps = 0;
474 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
494 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
510 return state.
DoS(10,
false, REJECT_INVALID,
"bad-txns-vin-empty");
512 return state.
DoS(10,
false, REJECT_INVALID,
"bad-txns-vout-empty");
515 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-oversize");
519 for (
const auto& txout : tx.
vout)
521 if (txout.nValue < 0)
522 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-vout-negative");
523 if (txout.nValue > MAX_MONEY)
524 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-vout-toolarge");
525 nValueOut += txout.nValue;
527 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-txouttotal-toolarge");
531 if (fCheckDuplicateInputs) {
532 std::set<COutPoint> vInOutPoints;
533 for (
const auto& txin : tx.
vin)
535 if (!vInOutPoints.insert(txin.
prevout).second)
536 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-inputs-duplicate");
542 if (tx.
vin[0].scriptSig.size() < 2 || tx.
vin[0].scriptSig.size() > 100)
543 return state.
DoS(100,
false, REJECT_INVALID,
"bad-cb-length");
547 for (
const auto& txin : tx.
vin)
549 return state.
DoS(10,
false, REJECT_INVALID,
"bad-txns-prevout-null");
558 LogPrint(
"mempool",
"Expired %i transactions from the memory pool\n", expired);
560 std::vector<uint256> vNoSpendsRemaining;
562 BOOST_FOREACH(
const uint256& removed, vNoSpendsRemaining)
575 static bool IsCurrentForFeeEstimation()
588 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
589 bool fOverrideMempoolLimit,
const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
595 *pfMissingInputs =
false;
602 return state.
DoS(100,
false, REJECT_INVALID,
"coinbase");
607 return state.
DoS(0,
false, REJECT_NONSTANDARD,
"no-witness-yet",
true);
613 return state.
DoS(0,
false, REJECT_NONSTANDARD, reason);
619 return state.
DoS(0,
false, REJECT_NONSTANDARD,
"non-final");
623 return state.
Invalid(
false, REJECT_ALREADY_KNOWN,
"txn-already-in-mempool");
626 std::set<uint256> setConflicts;
629 BOOST_FOREACH(
const CTxIn &txin, tx.
vin)
634 const CTransaction *ptxConflicting = itConflicting->second;
635 if (!setConflicts.count(ptxConflicting->
GetHash()))
649 bool fReplacementOptOut =
true;
652 BOOST_FOREACH(
const CTxIn &_txin, ptxConflicting->
vin)
654 if (_txin.
nSequence < std::numeric_limits<unsigned int>::max()-1)
656 fReplacementOptOut =
false;
661 if (fReplacementOptOut)
662 return state.
Invalid(
false, REJECT_CONFLICT,
"txn-mempool-conflict");
664 setConflicts.insert(ptxConflicting->
GetHash());
685 vHashTxnToUncache.push_back(hash);
686 return state.
Invalid(
false, REJECT_ALREADY_KNOWN,
"txn-already-known");
692 BOOST_FOREACH(
const CTxIn txin, tx.
vin) {
697 *pfMissingInputs =
true;
704 return state.
Invalid(
false, REJECT_DUPLICATE,
"bad-txns-inputs-spent");
720 return state.
DoS(0,
false, REJECT_NONSTANDARD,
"non-BIP68-final");
725 return state.
Invalid(
false, REJECT_NONSTANDARD,
"bad-txns-nonstandard-inputs");
729 return state.
DoS(0,
false, REJECT_NONSTANDARD,
"bad-witness-nonstandard",
true);
734 CAmount nFees = nValueIn-nValueOut;
737 double nPriorityDummy = 0;
738 pool.
ApplyDeltas(hash, nPriorityDummy, nModifiedFees);
745 bool fSpendsCoinbase =
false;
746 BOOST_FOREACH(
const CTxIn &txin, tx.
vin) {
749 fSpendsCoinbase =
true;
755 inChainInputValue, fSpendsCoinbase, nSigOpsCost, lp);
763 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
764 return state.
DoS(0,
false, REJECT_NONSTANDARD,
"bad-txns-too-many-sigops",
false,
768 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
769 return state.
DoS(0,
false, REJECT_INSUFFICIENTFEE,
"mempool min fee not met",
false,
strprintf(
"%d < %d", nFees, mempoolRejectFee));
772 return state.
DoS(0,
false, REJECT_INSUFFICIENTFEE,
"insufficient priority");
781 static double dFreeCount;
782 static int64_t nLastTime;
788 dFreeCount *= pow(1.0 - 1.0/600.0, (
double)(nNow - nLastTime));
792 if (dFreeCount + nSize >=
GetArg(
"-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000)
793 return state.
DoS(0,
false, REJECT_INSUFFICIENTFEE,
"rate limited free transaction");
794 LogPrint(
"mempool",
"Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
798 if (nAbsurdFee && nFees > nAbsurdFee)
800 REJECT_HIGHFEE,
"absurdly-high-fee",
801 strprintf(
"%d > %d", nFees, nAbsurdFee));
805 size_t nLimitAncestors =
GetArg(
"-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
806 size_t nLimitAncestorSize =
GetArg(
"-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
807 size_t nLimitDescendants =
GetArg(
"-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
808 size_t nLimitDescendantSize =
GetArg(
"-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
809 std::string errString;
810 if (!pool.
CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
811 return state.
DoS(0,
false, REJECT_NONSTANDARD,
"too-long-mempool-chain",
false, errString);
820 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
821 if (setConflicts.count(hashAncestor))
823 return state.
DoS(10,
false,
824 REJECT_INVALID,
"bad-txns-spends-conflicting-tx",
false,
825 strprintf(
"%s spends conflicting transaction %s",
834 size_t nConflictingSize = 0;
835 uint64_t nConflictingCount = 0;
842 const bool fReplacementTransaction = setConflicts.size();
843 if (fReplacementTransaction)
845 CFeeRate newFeeRate(nModifiedFees, nSize);
846 std::set<uint256> setConflictsParents;
847 const int maxDescendantsToVisit = 100;
849 BOOST_FOREACH(
const uint256 &hashConflicting, setConflicts)
852 if (mi == pool.
mapTx.end())
856 setIterConflicting.insert(mi);
874 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
875 if (newFeeRate <= oldFeeRate)
877 return state.
DoS(0,
false,
878 REJECT_INSUFFICIENTFEE,
"insufficient fee",
false,
879 strprintf(
"rejecting replacement %s; new feerate %s <= old feerate %s",
885 BOOST_FOREACH(
const CTxIn &txin, mi->GetTx().vin)
890 nConflictingCount += mi->GetCountWithDescendants();
895 if (nConflictingCount <= maxDescendantsToVisit) {
902 nConflictingFees += it->GetModifiedFee();
903 nConflictingSize += it->GetTxSize();
906 return state.
DoS(0,
false,
907 REJECT_NONSTANDARD,
"too many potential replacements",
false,
908 strprintf(
"rejecting replacement %s; too many potential replacements (%d > %d)\n",
911 maxDescendantsToVisit));
914 for (
unsigned int j = 0; j < tx.
vin.size(); j++)
920 if (!setConflictsParents.count(tx.
vin[j].prevout.hash))
925 if (pool.
mapTx.find(tx.
vin[j].prevout.hash) != pool.
mapTx.end())
926 return state.
DoS(0,
false,
927 REJECT_NONSTANDARD,
"replacement-adds-unconfirmed",
false,
928 strprintf(
"replacement %s adds unconfirmed input, idx %d",
936 if (nModifiedFees < nConflictingFees)
938 return state.
DoS(0,
false,
939 REJECT_INSUFFICIENTFEE,
"insufficient fee",
false,
940 strprintf(
"rejecting replacement %s, less fees than conflicting txs; %s < %s",
946 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
949 return state.
DoS(0,
false,
950 REJECT_INSUFFICIENTFEE,
"insufficient fee",
false,
951 strprintf(
"rejecting replacement %s, not enough additional fees to relay; %s < %s",
958 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
959 if (!
Params().RequireStandard()) {
960 scriptVerifyFlags =
GetArg(
"-promiscuousmempoolflags", scriptVerifyFlags);
966 if (!
CheckInputs(tx, state, view,
true, scriptVerifyFlags,
true, txdata)) {
988 if (!
CheckInputs(tx, state, view,
true, MANDATORY_SCRIPT_VERIFY_FLAGS,
true, txdata))
990 return error(
"%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
997 LogPrint(
"mempool",
"replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
998 it->GetTx().GetHash().ToString(),
1001 (
int)nSize - (
int)nConflictingSize);
1003 plTxnReplaced->push_back(it->GetSharedTx());
1011 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.
HasNoInputsOf(tx);
1014 pool.
addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
1017 if (!fOverrideMempoolLimit) {
1018 LimitMempoolSize(pool,
GetArg(
"-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
GetArg(
"-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
1020 return state.
DoS(0,
false, REJECT_INSUFFICIENTFEE,
"mempool full");
1030 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
1031 bool fOverrideMempoolLimit,
const CAmount nAbsurdFee)
1033 std::vector<uint256> vHashTxToUncache;
1034 bool res =
AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
1036 BOOST_FOREACH(
const uint256& hashTx, vHashTxToUncache)
1046 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
1047 bool fOverrideMempoolLimit,
const CAmount nAbsurdFee)
1071 return error(
"%s: OpenBlockFile failed", __func__);
1077 }
catch (
const std::exception& e) {
1078 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
1081 if (txOut->GetHash() != hash)
1082 return error(
"%s: txid mismatch", __func__);
1102 for (
const auto& tx : block.
vtx) {
1130 return error(
"WriteBlockToDisk: OpenBlockFile failed");
1134 fileout <<
FLATDATA(messageStart) << nSize;
1137 long fileOutPos = ftell(fileout.
Get());
1139 return error(
"WriteBlockToDisk: ftell failed");
1140 pos.
nPos = (
unsigned int)fileOutPos;
1149 template<
typename T>
1156 if (filein.IsNull())
1157 return error(
"ReadBlockFromDisk: OpenBlockFile failed for %s", pos.
ToString());
1163 catch (
const std::exception& e) {
1164 return error(
"%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.
ToString());
1169 return error(
"ReadBlockFromDisk: Errors in block header at %s", pos.
ToString());
1174 template<
typename T>
1177 if (!ReadBlockOrHeader(block, pindex->
GetBlockPos(), consensusParams, fCheckPOW))
1180 return error(
"ReadBlockOrHeader(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1187 return ReadBlockOrHeader(block, pos, consensusParams, fCheckPOW);
1192 return ReadBlockOrHeader(block, pindex, consensusParams, fCheckPOW);
1197 return ReadBlockOrHeader(block, pindex, consensusParams, fCheckPOW);
1209 nSubsidy >>= halvings;
1218 static std::atomic<bool> latchToFalse{
false};
1220 if (latchToFalse.load(std::memory_order_relaxed))
1224 if (latchToFalse.load(std::memory_order_relaxed))
1234 latchToFalse.store(
true, std::memory_order_relaxed);
1240 static void AlertNotify(
const std::string& strMessage)
1262 std::string warning = std::string(
"'Warning: Large-work fork detected, forking after block ") +
1264 AlertNotify(warning);
1268 LogPrintf(
"%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
1275 LogPrintf(
"%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1292 while (pfork && pfork != plonger)
1295 plonger = plonger->
pprev;
1296 if (pfork == plonger)
1298 pfork = pfork->
pprev;
1319 void static InvalidChainFound(
CBlockIndex* pindexNew)
1321 if (!pindexBestInvalid || pindexNew->
nChainWork > pindexBestInvalid->nChainWork)
1322 pindexBestInvalid = pindexNew;
1324 LogPrintf(
"%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1330 LogPrintf(
"%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1339 setDirtyBlockIndex.insert(pindex);
1340 setBlockIndexCandidates.erase(pindex);
1341 InvalidChainFound(pindex);
1350 BOOST_FOREACH(
const CTxIn &txin, tx.
vin) {
1354 if (nPos >= coins->
vout.size() || coins->
vout[nPos].IsNull())
1359 if (coins->
vout.size() == 0) {
1390 return pindexPrev->
nHeight + 1;
1399 return state.
Invalid(
false, 0,
"",
"Inputs unavailable");
1403 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
1413 if (nSpendHeight - coins->
nHeight < nCoinbaseMaturity)
1415 REJECT_INVALID,
"bad-txns-premature-spend-of-coinbase",
1416 strprintf(
"tried to spend coinbase at depth %d", nSpendHeight - coins->
nHeight));
1420 nValueIn += coins->
vout[prevout.
n].nValue;
1422 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-inputvalues-outofrange");
1427 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-in-belowout",
false,
1433 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-fee-negative");
1436 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-fee-outofrange");
1449 pvChecks->reserve(tx.
vin.size());
1460 if (fScriptChecks) {
1461 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
1470 check.
swap(pvChecks->back());
1471 }
else if (!check()) {
1472 if (
flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1480 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1506 if (fileout.IsNull())
1507 return error(
"%s: OpenUndoFile failed", __func__);
1511 fileout <<
FLATDATA(messageStart) << nSize;
1514 long fileOutPos = ftell(fileout.Get());
1516 return error(
"%s: ftell failed", __func__);
1517 pos.
nPos = (
unsigned int)fileOutPos;
1518 fileout << blockundo;
1522 hasher << hashBlock;
1523 hasher << blockundo;
1524 fileout << hasher.GetHash();
1533 if (filein.IsNull())
1534 return error(
"%s: OpenUndoFile failed", __func__);
1539 filein >> blockundo;
1540 filein >> hashChecksum;
1542 catch (
const std::exception& e) {
1543 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
1548 hasher << hashBlock;
1549 hasher << blockundo;
1550 if (hashChecksum != hasher.GetHash())
1551 return error(
"%s: Checksum mismatch", __func__);
1557 bool AbortNode(
const std::string& strMessage,
const std::string& userMessage=
"")
1562 userMessage.empty() ?
_(
"Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1568 bool AbortNode(
CValidationState& state,
const std::string& strMessage,
const std::string& userMessage=
"")
1570 AbortNode(strMessage, userMessage);
1571 return state.
Error(strMessage);
1591 fClean = fClean &&
error(
"%s: undo data overwriting existing transaction", __func__);
1598 fClean = fClean &&
error(
"%s: undo data adding output to missing transaction", __func__);
1601 fClean = fClean &&
error(
"%s: undo data overwriting existing output", __func__);
1602 if (coins->
vout.size() < out.
n+1)
1603 coins->
vout.resize(out.
n+1);
1621 return error(
"DisconnectBlock(): no undo data available");
1623 return error(
"DisconnectBlock(): failure reading undo data");
1625 if (blockUndo.
vtxundo.size() + 1 != block.
vtx.size())
1626 return error(
"DisconnectBlock(): block and undo data inconsistent");
1629 for (
int i = block.
vtx.size() - 1; i >= 0; i--) {
1645 if (*outs != outsBlock)
1646 fClean = fClean &&
error(
"DisconnectBlock(): added transaction mismatch? database corrupted");
1656 return error(
"DisconnectBlock(): transaction and undo data inconsistent");
1657 for (
unsigned int j = tx.
vin.size(); j-- > 0;) {
1677 void static FlushBlockFile(
bool fFinalize =
false)
1679 LOCK(cs_LastBlockFile);
1686 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1694 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1706 scriptcheckqueue.Thread();
1715 int32_t nVersion = VERSIONBITS_TOP_BITS;
1745 return ((pindex->
nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1754 static int64_t nTimeCheck = 0;
1755 static int64_t nTimeForks = 0;
1756 static int64_t nTimeVerify = 0;
1757 static int64_t nTimeConnect = 0;
1758 static int64_t nTimeIndex = 0;
1759 static int64_t nTimeCallbacks = 0;
1760 static int64_t nTimeTotal = 0;
1771 if (!
CheckBlock(block, state, !fJustCheck, !fJustCheck))
1780 if (block.
GetHash() ==
Params().GetConsensus(0).hashGenesisBlock) {
1786 bool fScriptChecks =
true;
1795 if (it->second->GetAncestor(pindex->
nHeight) == pindex &&
1812 int64_t nTime1 =
GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1813 LogPrint(
"bench",
" - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1828 bool fEnforceBIP30 =
true;
1840 if (fEnforceBIP30) {
1841 for (
const auto& tx : block.
vtx) {
1844 return state.
DoS(100,
error(
"ConnectBlock(): tried to overwrite transaction"),
1845 REJECT_INVALID,
"bad-txns-BIP30");
1851 bool fStrictPayToScriptHash =
true;
1866 int nLockTimeFlags = 0;
1878 int64_t nTime2 =
GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1879 LogPrint(
"bench",
" - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1885 std::vector<int> prevheights;
1888 int64_t nSigOpsCost = 0;
1890 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1891 vPos.reserve(block.
vtx.size());
1892 blockundo.
vtxundo.reserve(block.
vtx.size() - 1);
1893 std::vector<PrecomputedTransactionData> txdata;
1894 txdata.reserve(block.
vtx.size());
1895 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
1899 nInputs += tx.
vin.size();
1904 return state.
DoS(100,
error(
"ConnectBlock(): inputs missing/spent"),
1905 REJECT_INVALID,
"bad-txns-inputs-missingorspent");
1910 prevheights.resize(tx.
vin.size());
1911 for (
size_t j = 0; j < tx.
vin.size(); j++) {
1915 if (!
SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1916 return state.
DoS(100,
error(
"%s: contains a non-BIP68-final transaction", __func__),
1917 REJECT_INVALID,
"bad-txns-nonfinal");
1926 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1927 return state.
DoS(100,
error(
"ConnectBlock(): too many sigops"),
1928 REJECT_INVALID,
"bad-blk-sigops");
1930 txdata.emplace_back(tx);
1935 std::vector<CScriptCheck> vChecks;
1936 bool fCacheResults = fJustCheck;
1938 return error(
"ConnectBlock(): CheckInputs on %s failed with %s",
1940 control.
Add(vChecks);
1949 vPos.push_back(std::make_pair(tx.
GetHash(), pos));
1952 int64_t nTime3 =
GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1953 LogPrint(
"bench",
" - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (
unsigned)block.
vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.
vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
1956 if (block.
vtx[0]->GetValueOut() > blockReward)
1957 return state.
DoS(100,
1958 error(
"ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1959 block.
vtx[0]->GetValueOut(), blockReward),
1960 REJECT_INVALID,
"bad-cb-amount");
1962 if (!control.
Wait())
1963 return state.
DoS(100,
false);
1964 int64_t nTime4 =
GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1965 LogPrint(
"bench",
" - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
1976 return error(
"ConnectBlock(): FindUndoPos failed");
1978 return AbortNode(state,
"Failed to write undo data");
1986 setDirtyBlockIndex.insert(pindex);
1991 return AbortNode(state,
"Failed to write transaction index");
1996 int64_t nTime5 =
GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1997 LogPrint(
"bench",
" - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
2000 static uint256 hashPrevBestCoinBase;
2002 hashPrevBestCoinBase = block.
vtx[0]->GetHash();
2005 int64_t nTime6 =
GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
2006 LogPrint(
"bench",
" - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
2021 static int64_t nLastWrite = 0;
2022 static int64_t nLastFlush = 0;
2023 static int64_t nLastSetChain = 0;
2024 std::set<int> setFilesToPrune;
2025 bool fFlushForPrune =
false;
2028 if (nManualPruneHeight > 0) {
2032 fCheckForPruning =
false;
2034 if (!setFilesToPrune.empty()) {
2035 fFlushForPrune =
true;
2044 if (nLastWrite == 0) {
2047 if (nLastFlush == 0) {
2050 if (nLastSetChain == 0) {
2051 nLastSetChain = nNow;
2053 int64_t nMempoolSizeMax =
GetArg(
"-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2055 int64_t nTotalSpace =
nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
2057 bool fCacheLarge = mode ==
FLUSH_STATE_PERIODIC && cacheSize > std::min(std::max(nTotalSpace / 2, nTotalSpace - MIN_BLOCK_COINSDB_USAGE * 1024 * 1024),
2058 std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024));
2062 bool fPeriodicWrite = mode ==
FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2064 bool fPeriodicFlush = mode ==
FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2066 bool fDoFullFlush = (mode ==
FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2068 if (fDoFullFlush || fPeriodicWrite) {
2071 return state.
Error(
"out of disk space");
2076 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2077 vFiles.reserve(setDirtyFileInfo.size());
2078 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2079 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2080 setDirtyFileInfo.erase(it++);
2082 std::vector<const CBlockIndex*> vBlocks;
2083 vBlocks.reserve(setDirtyBlockIndex.size());
2084 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2085 vBlocks.push_back(*it);
2086 setDirtyBlockIndex.erase(it++);
2089 return AbortNode(state,
"Failed to write to block index database");
2105 return state.
Error(
"out of disk space");
2108 return AbortNode(state,
"Failed to write to coin database");
2114 nLastSetChain = nNow;
2116 }
catch (
const std::runtime_error& e) {
2117 return AbortNode(state, std::string(
"System error while flushing: ") + e.what());
2129 fCheckForPruning =
true;
2142 static bool fWarned =
false;
2143 std::vector<std::string> warningMessages;
2148 for (
int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2153 std::string strWarning =
strprintf(
_(
"Warning: unknown new rules activated (versionbit %i)"), bit);
2156 AlertNotify(strWarning);
2160 warningMessages.push_back(
strprintf(
"unknown new rules are about to activate (versionbit %i)", bit));
2165 for (
int i = 0; i < 100 && pindex != NULL; i++)
2170 pindex = pindex->
pprev;
2173 warningMessages.push_back(
strprintf(
"%d of last 100 blocks have unexpected version", nUpgraded));
2174 if (nUpgraded > 100/2)
2176 std::string strWarning =
_(
"Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2180 AlertNotify(strWarning);
2185 LogPrintf(
"%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
2190 if (!warningMessages.empty())
2191 LogPrintf(
" warning='%s'", boost::algorithm::join(warningMessages,
", "));
2200 assert(pindexDelete);
2204 return AbortNode(state,
"Failed to read block");
2211 bool flushed = view.Flush();
2221 std::vector<uint256> vHashUpdate;
2222 for (
const auto& it : block.
vtx) {
2229 vHashUpdate.push_back(tx.
GetHash());
2241 UpdateTip(pindexDelete->
pprev, chainparams);
2244 for (
const auto& tx : block.
vtx) {
2250 static int64_t nTimeReadFromDisk = 0;
2251 static int64_t nTimeConnectTotal = 0;
2252 static int64_t nTimeFlush = 0;
2253 static int64_t nTimeChainState = 0;
2254 static int64_t nTimePostConnect = 0;
2278 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2281 return AbortNode(state,
"Failed to read block");
2287 int64_t nTime2 =
GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2289 LogPrint(
"bench",
" - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2292 bool rv =
ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2296 InvalidBlockFound(pindexNew, state);
2299 nTime3 =
GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2300 LogPrint(
"bench",
" - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2301 bool flushed = view.Flush();
2304 int64_t nTime4 =
GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2305 LogPrint(
"bench",
" - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2309 int64_t nTime5 =
GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2310 LogPrint(
"bench",
" - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2314 UpdateTip(pindexNew, chainparams);
2316 int64_t nTime6 =
GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2317 LogPrint(
"bench",
" - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2318 LogPrint(
"bench",
"- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2332 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2333 if (it == setBlockIndexCandidates.rend())
2341 bool fInvalidAncestor =
false;
2351 if (fFailedChain || fMissingData) {
2353 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->
nChainWork > pindexBestInvalid->nChainWork))
2354 pindexBestInvalid = pindexNew;
2357 while (pindexTest != pindexFailed) {
2360 }
else if (fMissingData) {
2364 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->
pprev, pindexFailed));
2366 setBlockIndexCandidates.erase(pindexFailed);
2367 pindexFailed = pindexFailed->
pprev;
2369 setBlockIndexCandidates.erase(pindexTest);
2370 fInvalidAncestor =
true;
2373 pindexTest = pindexTest->
pprev;
2375 if (!fInvalidAncestor)
2381 static void PruneBlockIndexCandidates() {
2384 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2385 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it,
chainActive.
Tip())) {
2386 setBlockIndexCandidates.erase(it++);
2389 assert(!setBlockIndexCandidates.empty());
2403 bool fBlocksDisconnected =
false;
2405 if (!DisconnectTip(state, chainparams))
2407 fBlocksDisconnected =
true;
2411 std::vector<CBlockIndex*> vpindexToConnect;
2412 bool fContinue =
true;
2413 int nHeight = pindexFork ? pindexFork->
nHeight : -1;
2414 while (fContinue && nHeight != pindexMostWork->
nHeight) {
2417 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->
nHeight);
2418 vpindexToConnect.clear();
2419 vpindexToConnect.reserve(nTargetHeight - nHeight);
2421 while (pindexIter && pindexIter->
nHeight != nHeight) {
2422 vpindexToConnect.push_back(pindexIter);
2423 pindexIter = pindexIter->
pprev;
2425 nHeight = nTargetHeight;
2428 BOOST_REVERSE_FOREACH(
CBlockIndex *pindexConnect, vpindexToConnect) {
2429 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2433 InvalidChainFound(vpindexToConnect.back());
2435 fInvalidFound =
true;
2445 PruneBlockIndexCandidates();
2455 if (fBlocksDisconnected) {
2470 static void NotifyHeaderTip() {
2471 bool fNotify =
false;
2472 bool fInitialBlockDownload =
false;
2479 if (pindexHeader != pindexHeaderOld) {
2482 pindexHeaderOld = pindexHeader;
2505 boost::this_thread::interruption_point();
2511 bool fInitialDownload;
2523 if (pindexMostWork == NULL) {
2524 pindexMostWork = FindMostWorkChain();
2528 if (pindexMostWork == NULL || pindexMostWork ==
chainActive.
Tip())
2531 bool fInvalidFound =
false;
2532 std::shared_ptr<const CBlock> nullBlockPtr;
2533 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->
GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2536 if (fInvalidFound) {
2538 pindexMostWork = NULL;
2550 assert(pair.second);
2551 const CBlock& block = *(pair.second);
2552 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
2564 if (pindexFork != pindexNewTip) {
2567 }
while (pindexNewTip != pindexMostWork);
2589 nBlockReverseSequenceId = -1;
2592 setBlockIndexCandidates.erase(pindex);
2594 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2597 nBlockReverseSequenceId--;
2600 setBlockIndexCandidates.insert(pindex);
2601 PruneBlockIndexCandidates();
2614 setDirtyBlockIndex.insert(pindex);
2615 setBlockIndexCandidates.erase(pindex);
2620 setDirtyBlockIndex.insert(pindexWalk);
2621 setBlockIndexCandidates.erase(pindexWalk);
2624 if (!DisconnectTip(state, chainparams)) {
2637 setBlockIndexCandidates.insert(it->second);
2642 InvalidChainFound(pindex);
2651 int nHeight = pindex->
nHeight;
2656 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2658 setDirtyBlockIndex.insert(it->second);
2660 setBlockIndexCandidates.insert(it->second);
2662 if (it->second == pindexBestInvalid) {
2664 pindexBestInvalid = NULL;
2671 while (pindex != NULL) {
2674 setDirtyBlockIndex.insert(pindex);
2676 pindex = pindex->
pprev;
2696 BlockMap::iterator mi =
mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2701 pindexNew->
pprev = (*miPrev).second;
2711 setDirtyBlockIndex.insert(pindexNew);
2719 pindexNew->
nTx = block.
vtx.size();
2729 setDirtyBlockIndex.insert(pindexNew);
2733 std::deque<CBlockIndex*> queue;
2734 queue.push_back(pindexNew);
2737 while (!queue.empty()) {
2742 LOCK(cs_nBlockSequenceId);
2746 setBlockIndexCandidates.insert(pindex);
2748 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2749 while (range.first != range.second) {
2750 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2751 queue.push_back(it->second);
2753 mapBlocksUnlinked.erase(it);
2758 mapBlocksUnlinked.insert(std::make_pair(pindexNew->
pprev, pindexNew));
2767 LOCK(cs_LastBlockFile);
2769 unsigned int nFile = fKnown ? pos.
nFile : nLastBlockFile;
2770 if (vinfoBlockFile.size() <= nFile) {
2771 vinfoBlockFile.resize(nFile + 1);
2775 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2777 if (vinfoBlockFile.size() <= nFile) {
2778 vinfoBlockFile.resize(nFile + 1);
2782 pos.
nPos = vinfoBlockFile[nFile].nSize;
2785 if ((
int)nFile != nLastBlockFile) {
2787 LogPrintf(
"Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2789 FlushBlockFile(!fKnown);
2790 nLastBlockFile = nFile;
2793 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2795 vinfoBlockFile[nFile].nSize = std::max(pos.
nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2797 vinfoBlockFile[nFile].nSize += nAddSize;
2800 unsigned int nOldChunks = (pos.
nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2801 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2802 if (nNewChunks > nOldChunks) {
2804 fCheckForPruning =
true;
2808 LogPrintf(
"Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.
nFile);
2814 return state.
Error(
"out of disk space");
2818 setDirtyFileInfo.insert(nFile);
2826 LOCK(cs_LastBlockFile);
2828 unsigned int nNewSize;
2829 pos.
nPos = vinfoBlockFile[nFile].nUndoSize;
2830 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2831 setDirtyFileInfo.insert(nFile);
2833 unsigned int nOldChunks = (pos.
nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2834 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2835 if (nNewChunks > nOldChunks) {
2837 fCheckForPruning =
true;
2841 LogPrintf(
"Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.
nFile);
2847 return state.
Error(
"out of disk space");
2860 return state.
DoS(50,
false, REJECT_INVALID,
"high-hash",
false,
"proof of work failed");
2878 if (fCheckMerkleRoot) {
2882 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txnmrklroot",
true,
"hashMerkleRoot mismatch");
2888 return state.
DoS(100,
false, REJECT_INVALID,
"bad-txns-duplicate",
true,
"duplicate transaction");
2898 if (block.
vtx.empty() || block.
vtx.size() > MAX_BLOCK_BASE_SIZE || ::
GetSerializeSize(block,
SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)
2899 return state.
DoS(100,
false, REJECT_INVALID,
"bad-blk-length",
false,
"size limits failed");
2902 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase())
2903 return state.
DoS(100,
false, REJECT_INVALID,
"bad-cb-missing",
false,
"first tx is not coinbase");
2904 for (
unsigned int i = 1; i < block.
vtx.size(); i++)
2905 if (block.
vtx[i]->IsCoinBase())
2906 return state.
DoS(100,
false, REJECT_INVALID,
"bad-cb-multiple",
false,
"more than one coinbase");
2909 for (
const auto& tx : block.
vtx)
2914 unsigned int nSigOps = 0;
2915 for (
const auto& tx : block.
vtx)
2919 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2920 return state.
DoS(100,
false, REJECT_INVALID,
"bad-blk-sigops",
false,
"out-of-bounds SigOpCount");
2922 if (fCheckPOW && fCheckMerkleRoot)
2933 int nHeight = pindexPrev->
nHeight+1;
2936 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2937 return state.
DoS(100,
error(
"%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2952 static int GetWitnessCommitmentIndex(
const CBlock& block)
2955 if (!block.
vtx.empty()) {
2956 for (
size_t o = 0; o < block.
vtx[0]->vout.size(); o++) {
2957 if (block.
vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.
vtx[0]->vout[o].scriptPubKey[0] ==
OP_RETURN && block.
vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.
vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.
vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.
vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.
vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
2967 int commitpos = GetWitnessCommitmentIndex(block);
2968 static const std::vector<unsigned char> nonce(32, 0x00);
2969 if (commitpos != -1 &&
IsWitnessEnabled(pindexPrev, consensusParams) && !block.
vtx[0]->HasWitness()) {
2971 tx.
vin[0].scriptWitness.stack.resize(1);
2972 tx.
vin[0].scriptWitness.stack[0] = nonce;
2973 block.
vtx[0] = MakeTransactionRef(std::move(tx));
2979 std::vector<unsigned char> commitment;
2980 int commitpos = GetWitnessCommitmentIndex(block);
2981 std::vector<unsigned char> ret(32, 0x00);
2983 if (commitpos == -1) {
2998 tx.
vout.push_back(out);
2999 block.
vtx[0] = MakeTransactionRef(std::move(tx));
3008 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->
nHeight + 1;
3014 return state.
DoS(100,
error(
"%s : legacy block after auxpow start",
3016 REJECT_INVALID,
"late-legacy-block");
3023 return state.
DoS(100,
error(
"%s : auxpow blocks are not allowed at height %d, parameters effective from %d",
3025 REJECT_INVALID,
"early-auxpow-block");
3029 return state.
DoS(100,
false, REJECT_INVALID,
"bad-diffbits",
false,
"incorrect proof of work");
3033 return state.
Invalid(
false, REJECT_INVALID,
"time-too-old",
"block's timestamp is too early");
3036 if (block.
GetBlockTime() > nAdjustedTime + 2 * 60 * 60)
3037 return state.
Invalid(
false, REJECT_INVALID,
"time-too-new",
"block timestamp too far in the future");
3052 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->
nHeight + 1;
3058 int nLockTimeFlags = 0;
3068 for (
const auto& tx : block.
vtx) {
3069 if (!
IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3070 return state.
DoS(10,
false, REJECT_INVALID,
"bad-txns-nonfinal",
false,
"non-final transaction");
3078 if (block.
vtx[0]->vin[0].scriptSig.size() <
expect.size() ||
3079 !std::equal(
expect.begin(),
expect.end(), block.
vtx[0]->vin[0].scriptSig.begin())) {
3080 return state.
DoS(100,
false, REJECT_INVALID,
"bad-cb-height",
false,
"block height mismatch in coinbase");
3092 bool fHaveWitness =
false;
3094 int commitpos = GetWitnessCommitmentIndex(block);
3095 if (commitpos != -1) {
3096 bool malleated =
false;
3101 if (block.
vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.
vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3102 return state.
DoS(100,
false, REJECT_INVALID,
"bad-witness-nonce-size",
true,
strprintf(
"%s : invalid witness nonce size", __func__));
3105 if (memcmp(hashWitness.
begin(), &block.
vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3106 return state.
DoS(100,
false, REJECT_INVALID,
"bad-witness-merkle-match",
true,
strprintf(
"%s : witness merkle commitment mismatch", __func__));
3108 fHaveWitness =
true;
3113 if (!fHaveWitness) {
3114 for (
size_t i = 0; i < block.
vtx.size(); i++) {
3115 if (block.
vtx[i]->HasWitness()) {
3116 return state.
DoS(100,
false, REJECT_INVALID,
"unexpected-witness",
true,
strprintf(
"%s : unexpected witness data found", __func__));
3128 return state.
DoS(100,
false, REJECT_INVALID,
"bad-blk-weight",
false,
strprintf(
"%s : weight limit failed", __func__));
3145 pindex = miSelf->second;
3149 return state.
Invalid(
error(
"%s: block %s is marked invalid", __func__, hash.
ToString()), 0,
"duplicate");
3160 return state.
DoS(10,
error(
"%s: prev block not found", __func__), 0,
"bad-prevblk");
3161 pindexPrev = (*mi).second;
3163 return state.
DoS(100,
error(
"%s: prev block invalid", __func__), REJECT_INVALID,
"bad-prevblk");
3166 if (
fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
3167 return error(
"%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.
GetRejectReason().c_str());
3190 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3205 const CBlock& block = *pblock;
3207 if (fNewBlock) *fNewBlock =
false;
3211 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3213 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3235 if (fAlreadyHave)
return true;
3237 if (pindex->
nTx != 0)
return true;
3238 if (!fHasMoreWork)
return true;
3239 if (fTooFarAhead)
return true;
3241 if (fNewBlock) *fNewBlock =
true;
3247 setDirtyBlockIndex.insert(pindex);
3257 int nHeight = pindex->
nHeight;
3266 return error(
"AcceptBlock(): FindBlockPos failed");
3269 AbortNode(state,
"Failed to write block");
3271 return error(
"AcceptBlock(): ReceivedBlockTransactions failed");
3272 }
catch (
const std::runtime_error& e) {
3273 return AbortNode(state, std::string(
"System error: ") + e.what());
3276 if (fCheckForPruning)
3284 unsigned int nFound = 0;
3285 for (
int i = 0; i < consensusParams.
nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3289 pstart = pstart->
pprev;
3291 return (nFound >= nRequired);
3298 if (fNewBlock) *fNewBlock =
false;
3308 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
3313 return error(
"%s: AcceptBlock FAILED", __func__);
3321 return error(
"%s: ActivateBestChain failed", __func__);
3331 return error(
"%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.
GetRejectReason().c_str());
3335 indexDummy.
pprev = pindexPrev;
3341 if (!
CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
3345 if (!
ConnectBlock(block, state, &indexDummy, viewNew, chainparams,
true))
3359 LOCK(cs_LastBlockFile);
3361 uint64_t retval = 0;
3371 LOCK(cs_LastBlockFile);
3375 if (pindex->
nFile == fileNumber) {
3381 setDirtyBlockIndex.insert(pindex);
3387 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->
pprev);
3388 while (range.first != range.second) {
3389 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3391 if (_it->second == pindex) {
3392 mapBlocksUnlinked.erase(_it);
3398 vinfoBlockFile[fileNumber].SetNull();
3399 setDirtyFileInfo.insert(fileNumber);
3405 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3409 LogPrintf(
"Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3416 assert(
fPruneMode && nManualPruneHeight > 0);
3423 unsigned int nLastBlockWeCanPrune = std::min((
unsigned)nManualPruneHeight,
chainActive.
Height() - MIN_BLOCKS_TO_KEEP);
3425 for (
int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3426 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3429 setFilesToPrune.insert(fileNumber);
3432 LogPrintf(
"Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3458 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3459 uint64_t nBytesToPrune;
3463 for (
int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3464 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3466 if (vinfoBlockFile[fileNumber].nSize == 0)
3473 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3478 setFilesToPrune.insert(fileNumber);
3479 nCurrentUsage -= nBytesToPrune;
3484 LogPrint(
"prune",
"Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3486 ((int64_t)
nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3487 nLastBlockWeCanPrune, count);
3492 uint64_t nFreeBytesAvailable = boost::filesystem::space(
GetDataDir()).available;
3495 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3496 return AbortNode(
"Disk space is low!",
_(
"Error: Disk space is low!"));
3506 boost::filesystem::create_directories(path.parent_path());
3507 FILE* file = fopen(path.string().c_str(),
"rb+");
3508 if (!file && !fReadOnly)
3509 file = fopen(path.string().c_str(),
"wb+");
3511 LogPrintf(
"Unable to open file %s\n", path.string());
3515 if (fseek(file, pos.
nPos, SEEK_SET)) {
3516 LogPrintf(
"Unable to seek to position %u of %s\n", pos.
nPos, path.string());
3545 return (*mi).second;
3550 throw std::runtime_error(std::string(__func__) +
": new CBlockIndex failed");
3551 mi =
mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3557 bool static LoadBlockIndexDB(
const CChainParams& chainparams)
3562 boost::this_thread::interruption_point();
3565 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3570 vSortedByHeight.push_back(std::make_pair(pindex->
nHeight, pindex));
3572 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3580 if (pindex->
nTx > 0) {
3581 if (pindex->
pprev) {
3586 mapBlocksUnlinked.insert(std::make_pair(pindex->
pprev, pindex));
3593 setBlockIndexCandidates.insert(pindex);
3595 pindexBestInvalid = pindex;
3604 vinfoBlockFile.resize(nLastBlockFile + 1);
3605 LogPrintf(
"%s: last block file = %i\n", __func__, nLastBlockFile);
3606 for (
int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3609 LogPrintf(
"%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3610 for (
int nFile = nLastBlockFile + 1;
true; nFile++) {
3613 vinfoBlockFile.push_back(info);
3620 LogPrintf(
"Checking all blk files are present...\n");
3621 std::set<int> setBlkDataFiles;
3626 setBlkDataFiles.insert(pindex->
nFile);
3629 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3640 LogPrintf(
"LoadBlockIndexDB(): Block files have previously been pruned\n");
3643 bool fReindexing =
false;
3649 LogPrintf(
"%s: transaction index %s\n", __func__,
fTxIndex ?
"enabled" :
"disabled");
3657 PruneBlockIndexCandidates();
3659 LogPrintf(
"%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3684 if (nCheckDepth <= 0)
3685 nCheckDepth = 1000000000;
3688 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3689 LogPrintf(
"Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3693 int nGoodTransactions = 0;
3699 boost::this_thread::interruption_point();
3700 int percentageDone = std::max(1, std::min(99, (
int)(((
double)(
chainActive.
Height() - pindex->
nHeight)) / (
double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3701 if (reportDone < percentageDone/10) {
3704 reportDone = percentageDone/10;
3711 LogPrintf(
"VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->
nHeight);
3719 if (nCheckLevel >= 1 && !
CheckBlock(block, state))
3720 return error(
"%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3723 if (nCheckLevel >= 2 && pindex) {
3736 pindexState = pindex->
pprev;
3738 nGoodTransactions = 0;
3739 pindexFailure = pindex;
3741 nGoodTransactions += block.
vtx.size();
3747 return error(
"VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n",
chainActive.
Height() - pindexFailure->
nHeight + 1, nGoodTransactions);
3750 if (nCheckLevel >= 4) {
3753 boost::this_thread::interruption_point();
3759 if (!
ConnectBlock(block, state, pindex, coins, chainparams))
3794 if (!DisconnectTip(state, params,
true)) {
3795 return error(
"RewindBlockIndex: unable to disconnect block at height %i", pindex->
nHeight);
3819 pindexIter->
nFile = 0;
3823 pindexIter->
nTx = 0;
3827 setDirtyBlockIndex.insert(pindexIter);
3829 setBlockIndexCandidates.erase(pindexIter);
3830 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->
pprev);
3831 while (ret.first != ret.second) {
3832 if (ret.first->second == pindexIter) {
3833 mapBlocksUnlinked.erase(ret.first++);
3839 setBlockIndexCandidates.insert(pindexIter);
3843 PruneBlockIndexCandidates();
3860 setBlockIndexCandidates.clear();
3862 pindexBestInvalid = NULL;
3865 mapBlocksUnlinked.clear();
3866 vinfoBlockFile.clear();
3868 nBlockSequenceId = 1;
3869 setDirtyBlockIndex.clear();
3870 setDirtyFileInfo.clear();
3872 for (
int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3873 warningcache[b].clear();
3877 delete entry.second;
3886 if (!
fReindex && !LoadBlockIndexDB(chainparams))
3902 LogPrintf(
"Initializing databases...\n");
3913 return error(
"LoadBlockIndex(): FindBlockPos failed");
3915 return error(
"LoadBlockIndex(): writing genesis block to disk failed");
3918 return error(
"LoadBlockIndex(): genesis block not accepted");
3921 }
catch (
const std::runtime_error& e) {
3922 return error(
"LoadBlockIndex(): failed to initialize block database: %s", e.what());
3932 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3938 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8,
SER_DISK, CLIENT_VERSION);
3939 uint64_t nRewind = blkdat.
GetPos();
3940 while (!blkdat.
eof()) {
3941 boost::this_thread::interruption_point();
3946 unsigned int nSize = 0;
3951 nRewind = blkdat.
GetPos()+1;
3957 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3959 }
catch (
const std::exception&) {
3965 uint64_t nBlockPos = blkdat.
GetPos();
3967 dbp->
nPos = nBlockPos;
3968 blkdat.
SetLimit(nBlockPos + nSize);
3969 blkdat.
SetPos(nBlockPos);
3970 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3973 nRewind = blkdat.
GetPos();
3978 LogPrint(
"reindex",
"%s: Out of order block %s, parent %s not known\n", __func__, hash.
ToString(),
3981 mapBlocksUnknownParent.insert(std::make_pair(block.
hashPrevBlock, *dbp));
3989 if (AcceptBlock(pblock, state, chainparams, NULL,
true, dbp, NULL))
4008 std::deque<uint256> queue;
4009 queue.push_back(hash);
4010 while (!queue.empty()) {
4013 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4014 while (range.first != range.second) {
4015 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4016 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4020 LogPrint(
"reindex",
"%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4024 if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL,
true, &it->second, NULL))
4027 queue.push_back(pblockrecursive->GetHash());
4031 mapBlocksUnknownParent.erase(it);
4035 }
catch (
const std::exception& e) {
4036 LogPrintf(
"%s: Deserialize or I/O error - %s\n", __func__, e.what());
4039 }
catch (
const std::runtime_error& e) {
4040 AbortNode(std::string(
"System error: ") + e.what());
4064 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4066 forward.insert(std::make_pair(it->second->pprev, it->second));
4071 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4073 rangeGenesis.first++;
4074 assert(rangeGenesis.first == rangeGenesis.second);
4085 CBlockIndex* pindexFirstNotTransactionsValid = NULL;
4088 while (pindex != NULL) {
4092 if (pindexFirstNeverProcessed == NULL && pindex->
nTx == 0) pindexFirstNeverProcessed = pindex;
4099 if (pindex->
pprev == NULL) {
4110 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4118 assert((pindexFirstNeverProcessed != NULL) == (pindex->
nChainTx == 0));
4119 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->
nChainTx == 0));
4120 assert(pindex->
nHeight == nHeight);
4123 assert(pindexFirstNotTreeValid == NULL);
4127 if (pindexFirstInvalid == NULL) {
4131 if (!CBlockIndexWorkComparator()(pindex,
chainActive.
Tip()) && pindexFirstNeverProcessed == NULL) {
4132 if (pindexFirstInvalid == NULL) {
4138 assert(setBlockIndexCandidates.count(pindex));
4145 assert(setBlockIndexCandidates.count(pindex) == 0);
4148 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->
pprev);
4149 bool foundInUnlinked =
false;
4150 while (rangeUnlinked.first != rangeUnlinked.second) {
4151 assert(rangeUnlinked.first->first == pindex->
pprev);
4152 if (rangeUnlinked.first->second == pindex) {
4153 foundInUnlinked =
true;
4156 rangeUnlinked.first++;
4160 assert(foundInUnlinked);
4163 if (pindexFirstMissing == NULL) assert(!foundInUnlinked);
4175 if (!CBlockIndexWorkComparator()(pindex,
chainActive.
Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4176 if (pindexFirstInvalid == NULL) {
4177 assert(foundInUnlinked);
4185 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4186 if (range.first != range.second) {
4188 pindex = range.first->second;
4197 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4198 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4199 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4200 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4201 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4202 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4203 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4207 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4208 while (rangePar.first->second != pindex) {
4209 assert(rangePar.first != rangePar.second);
4214 if (rangePar.first != rangePar.second) {
4216 pindex = rangePar.first->second;
4228 assert(nNodes == forward.size());
4233 return strprintf(
"CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)",
nBlocks,
nSize,
nHeightFirst,
nHeightLast,
DateTimeStrFormat(
"%Y-%m-%d",
nTimeFirst),
DateTimeStrFormat(
"%Y-%m-%d",
nTimeLast));
4238 LOCK(cs_LastBlockFile);
4240 return &vinfoBlockFile.at(n);
4255 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4259 int64_t nExpiryTimeout =
GetArg(
"-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4260 FILE* filestr = fopen((
GetDataDir() /
"mempool.dat").
string().c_str(),
"rb");
4263 LogPrintf(
"Failed to open mempool file from disk. Continuing anyway.\n");
4268 int64_t skipped = 0;
4275 if (version != MEMPOOL_DUMP_VERSION) {
4280 double prioritydummy = 0;
4289 CAmount amountdelta = nFeeDelta;
4294 if (nTime + nExpiryTimeout > nNow) {
4308 std::map<uint256, CAmount> mapDeltas;
4311 for (
const auto& i : mapDeltas) {
4314 }
catch (
const std::exception& e) {
4315 LogPrintf(
"Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4319 LogPrintf(
"Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4327 std::map<uint256, CAmount> mapDeltas;
4328 std::vector<TxMempoolInfo> vinfo;
4333 mapDeltas[i.first] = i.second.second;
4341 FILE* filestr = fopen((
GetDataDir() /
"mempool.dat.new").
string().c_str(),
"wb");
4348 uint64_t version = MEMPOOL_DUMP_VERSION;
4351 file << (uint64_t)vinfo.size();
4352 for (
const auto& i : vinfo) {
4354 file << (int64_t)i.nTime;
4355 file << (int64_t)i.nFeeDelta;
4356 mapDeltas.erase(i.tx->GetHash());
4364 LogPrintf(
"Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4365 }
catch (
const std::exception& e) {
4366 LogPrintf(
"Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4375 int64_t nNow = time(NULL);
4385 return pindex->
nChainTx / fTxTotal;
4396 delete (*it1).second;
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative)
arith_uint256 UintToArith256(const uint256 &a)
int64_t GetBlockWeight(const CBlock &block)
Compute the consensus-critical block weight (see BIP 141).
arith_uint256 GetBlockProof(const CBlockIndex &block)
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params ¶ms)
Return the time it would take to redo the work difference between from and to, assuming the current h...
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ BLOCK_VALID_MASK
All validity bits.
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
@ BLOCK_HAVE_DATA
full block available in blk*.dat
@ BLOCK_FAILED_CHILD
descends from failed block
@ BLOCK_FAILED_VALID
stage after last reached validness failed
@ BLOCK_OPT_WITNESS
block data in blk*.data was received with a witness-enforcing client
const CChainParams & Params()
Return the currently selected parameters.
Abstract class that implements BIP9-style threshold logic, and caches results.
Template mixin that adds -Wthread-safety locking annotations to a subset of the mutex API.
static void Notify(const std::string &strMessage, bool fThread=true)
Non-refcounted RAII wrapper for FILE*.
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
bool IsNull() const
Return true if the wrapped FILE* is NULL, false otherwise.
uint64_t nTimeFirst
earliest time of block in file
uint64_t nTimeLast
latest time of block in file
std::string ToString() const
unsigned int nHeightFirst
lowest height of block in file
unsigned int nHeightLast
highest height of block in file
unsigned int nUndoSize
number of used bytes in the undo file
unsigned int nBlocks
number of blocks stored in file
unsigned int nSize
number of used bytes of block file
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
std::string ToString() const
CBlockIndex * pprev
pointer to the index of the predecessor of this block
void BuildSkip()
Build the skiplist pointer for this entry.
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
int nFile
Which # file this block is stored in (blk?????.dat)
int GetBaseVersion() const
unsigned int nTimeMax
(memory only) Maximum nTime in the chain upto and including this block.
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
uint256 GetBlockHash() const
int64_t GetBlockTime() const
CDiskBlockPos GetUndoPos() const
int64_t GetMedianTimePast() const
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
unsigned int nTx
Number of transactions in this block.
CDiskBlockPos GetBlockPos() const
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
int nHeight
height of the entry in the chain. The genesis block has height 0
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Access to the block database (blocks/index/)
bool ReadReindexing(bool &fReindex)
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
bool LoadBlockIndexGuts(boost::function< CBlockIndex *(const uint256 &)> insertBlockIndex)
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo * > > &fileInfo, int nLastFile, const std::vector< const CBlockIndex * > &blockinfo)
bool ReadFlag(const std::string &name, bool &fValue)
bool ReadLastBlockFile(int &nFile)
bool WriteFlag(const std::string &name, bool fValue)
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from.
bool SetPos(uint64_t nPos)
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
An in-memory indexed chain of blocks.
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const ChainTxData & TxData() const
const CMessageHeader::MessageStartChars & MessageStart() const
const CCheckpointData & Checkpoints() const
const Consensus::Params & GetConsensus(uint32_t nTargetHeight) const
uint64_t PruneAfterHeight() const
const CBlock & GenesisBlock() const
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
void Add(std::vector< T > &vChecks)
Queue for verifications that have to be performed.
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
New block has been accepted.
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyHeaderTip
Best header has changed.
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Pruned version of CTransaction: only retains metadata and unspent transaction outputs.
bool Spend(uint32_t nPos)
mark a vout spent
std::vector< CTxOut > vout
unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are d...
bool IsPruned() const
check whether the entire CCoins is spent note that only !IsPruned() CCoins can be serialized
int nVersion
version of the CTransaction; accesses to this value should probably check for nHeight as well,...
bool IsAvailable(unsigned int nPos) const
check whether a particular output is still available
void FromTx(const CTransaction &tx, int nHeightIn)
bool fCoinBase
whether transaction is a coinbase
int nHeight
at which height this transaction was included in the active block chain
A reference to a mutable cache entry.
void SetBackend(CCoinsView &viewIn)
CCoinsView that adds a memory cache for transactions to another CCoinsView.
uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
CAmount GetValueIn(const CTransaction &tx) const
Amount of bitcoins coming in to a transaction Note that lightweight clients may not know anything bes...
const CTxOut & GetOutputFor(const CTxIn &input) const
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view.
bool HaveCoinsInCache(const uint256 &txid) const
Check if we have the given tx already loaded in this cache.
const CCoins * AccessCoins(const uint256 &txid) const
Return a pointer to CCoins in the cache, or NULL if not found.
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transactions)
double GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const
Return priority of tx at height nHeight.
void SetBestBlock(const uint256 &hashBlock)
bool HaveCoins(const uint256 &txid) const
Just check whether we have data for a given txid.
void Uncache(const uint256 &txid)
Removes the transaction with the given hash from the cache, if it is not modified.
CCoinsModifier ModifyCoins(const uint256 &txid)
Return a modifiable reference to a CCoins.
bool Flush()
Push the modifications applied to this cache to its base.
CCoinsModifier ModifyNewCoins(const uint256 &txid, bool coinbase)
Return a modifiable reference to a CCoins.
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Abstract view on the open txout dataset.
CCoinsView that brings transactions from a memorypool into view.
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Fee rate in satoshis per kilobyte: CAmount / kB.
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
std::string ToString() const
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
CHash256 & Write(const unsigned char *data, size_t len)
void Finalize(unsigned char hash[OUTPUT_SIZE])
A writer stream (for serialization) that computes a 256-bit hash.
An outpoint - a combination of a transaction hash and an index n into its vout.
Closure representing one script verification Note that this stores references to the spending transac...
ScriptError GetScriptError() const
PrecomputedTransactionData * txdata
void swap(CScriptCheck &check)
const CTransaction * ptxTo
Serialized script, used inside transaction inputs and outputs.
bool IsPayToScriptHash() const
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
const uint256 & GetHash() const
CAmount GetValueOut() const
const std::vector< CTxIn > vin
An input of a transaction.
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
static const uint32_t SEQUENCE_LOCKTIME_MASK
static const uint32_t SEQUENCE_FINAL
Only serialized through CTransaction.
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
static const int SEQUENCE_LOCKTIME_GRANULARITY
Undo information for a CTxIn.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
double GetPriority(unsigned int currentHeight) const
Fast calculation of lower bound of current priority as update from entry priority.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
int Expire(int64_t time)
Expire all transaction (and their dependencies) in the mempool older than time.
void AddTransactionsUpdated(unsigned int n)
std::map< uint256, std::pair< double, CAmount > > mapDeltas
CTransactionRef get(const uint256 &hash) const
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool validFeeEstimate=true)
size_t DynamicMemoryUsage() const
std::vector< TxMempoolInfo > infoAll() const
indirectmap< COutPoint, const CTransaction * > mapNextTx
void TrimToSize(size_t sizelimit, std::vector< uint256 > *pvNoSpendsRemaining=NULL)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
bool HasNoInputsOf(const CTransaction &tx) const
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
void UpdateTransactionsFromBlock(const std::vector< uint256 > &hashesToUpdate)
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
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.
bool exists(uint256 hash) const
void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const
std::set< txiter, CompareIteratorByHash > setEntries
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Remove a set of transactions from the mempool.
indexed_transaction_set mapTx
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
boost::signals2::signal< void(CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight)
Called when a block is connected.
An output of a transaction.
Undo information for a CTransaction.
std::vector< CTxInUndo > vprevout
Capture information about block/transaction validation.
unsigned int GetRejectCode() const
bool DoS(int level, bool ret=false, unsigned int chRejectCodeIn=0, const std::string &strRejectReasonIn="", bool corruptionIn=false, const std::string &strDebugMessageIn="")
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
bool Error(const std::string &strRejectReasonIn)
void SetCorruptionPossible()
std::string GetRejectReason() const
bool CorruptionPossible() const
std::string GetDebugMessage() const
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
std::vector< CTransactionRef > conflictedTxs
~MemPoolConflictRemovalTracker()
MemPoolConflictRemovalTracker(CTxMemPool &_pool)
void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason)
Threshold condition checker that triggers when unknown versionbits are seen on the network.
WarningBitsConditionChecker(int bitIn)
bool Condition(const CBlockIndex *pindex, const Consensus::Params ¶ms) const
int64_t BeginTime(const Consensus::Params ¶ms) const
int64_t EndTime(const Consensus::Params ¶ms) const
int Threshold(const Consensus::Params ¶ms) const
int Period(const Consensus::Params ¶ms) const
256-bit unsigned big integer.
std::string ToString() const
iterator find(const K &key)
void resize(size_type new_size)
@ LOCKTIME_MEDIAN_TIME_PAST
@ LOCKTIME_VERIFY_SEQUENCE
CAmount GetDogecoinMinRelayFee(const CTransaction &tx, unsigned int nBytes, bool fAllowFree)
bool CheckAuxPowProofOfWork(const CBlockHeader &block, const Consensus::Params ¶ms)
Check proof-of-work of a block header, taking auxpow into account.
CAmount GetDogecoinBlockSubsidy(int nHeight, const Consensus::Params &consensusParams, uint256 prevHash)
void * memcpy(void *a, const void *b, size_t c)
size_t CountWitnessSigOps(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
@ SCRIPT_VERIFY_NULLDUMMY
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
@ SCRIPT_VERIFY_CLEANSTACK
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
uint256 BlockWitnessMerkleRoot(const CBlock &block, bool *mutated)
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data)
Returns last CBlockIndex* in mapBlockIndex that is a checkpoint.
bool CheckTxInputs(const CChainParams ¶ms, const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
@ MAX_VERSION_BITS_DEPLOYMENTS
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check for standard transaction types.
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
CFeeRate incrementalRelayFee
bool IsStandardTx(const CTransaction &tx, std::string &reason, const bool witnessEnabled)
Check for standard transaction types.
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
const char * ScriptErrorString(const ScriptError serror)
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< uint256 > vHave
std::string ToString() const
boost::signals2::signal< void(const CBlockLocator &)> SetBestChain
Notifies listeners of a new active block chain.
boost::signals2::signal< void(const uint256 &)> UpdatedTransaction
Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becomi...
static const int SYNC_TRANSACTION_NOT_IN_BLOCK
A posInBlock value for SyncTransaction calls for tranactions not included in connected blocks such as...
boost::signals2::signal< void(const CBlock &, const CValidationState &)> BlockChecked
Notifies listeners of a block validation result.
boost::signals2::signal< void(const CBlockIndex *, const std::shared_ptr< const CBlock > &)> NewPoWValidBlock
Notifies listeners that a block which builds directly on our current tip has been received and connec...
boost::signals2::signal< void(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip
Notifies listeners of updated block chain tip.
boost::signals2::signal< void(const CTransaction &, const CBlockIndex *pindex, int posInBlock)> SyncTransaction
Notifies listeners of updated transaction data (transaction, and optionally the block it is found in)...
A mutable version of CTransaction.
std::vector< CTxOut > vout
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
std::vector< std::pair< CBlockIndex *, std::shared_ptr< const CBlock > > > blocksConnected
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Parameters that influence chain consensus.
int BIP65Height
Block height at which BIP65 becomes active.
uint32_t nMinerConfirmationWindow
int BIP34Height
Block height and hash at which BIP34 becomes active.
int nSubsidyHalvingInterval
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
uint256 nMinimumChainWork
uint32_t nRuleChangeActivationThreshold
Minimum blocks including miner confirmation of the total of 2016 blocks in a retargeting period,...
uint32_t nCoinbaseMaturity
int BIP66Height
Block height at which BIP66 becomes active.
uint32_t nHeightEffective
Height-aware consensus parameters.
CBlockIndex * maxInputBlock
#define AssertLockHeld(cs)
boost::condition_variable CConditionVariable
Just a typedef for boost::condition_variable, can be wrapped later if desired.
int64_t GetAdjustedTime()
std::shared_ptr< const CTransaction > CTransactionRef
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
@ REPLACED
Removed for conflict with in-block transaction.
@ CONFLICT
Removed for block.
@ REORG
Removed in size limiting.
bool AllowFree(double dPriority)
CClientUIInterface uiInterface
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
void RenameThread(const char *name)
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
bool TruncateFile(FILE *file, unsigned int length)
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
void FileCommit(FILE *file)
#define LogPrint(category,...)
bool error(const char *fmt, const Args &... args)
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
#define PAIRTYPE(t1, t2)
This is needed because the foreach macro can't get over the comma in pair<t1, t2>
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units.
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
bool PreciousBlock(CValidationState &state, const CChainParams ¶ms, CBlockIndex *pindex)
Mark a block as precious and reorganize.
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
CCriticalSection cs_main
Global state.
bool WriteBlockToDisk(const CBlock &block, CDiskBlockPos &pos, const CMessageHeader::MessageStartChars &messageStart)
Functions for disk access for blocks.
const std::string strMessageMagic
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain.
bool RewindBlockIndex(const CChainParams ¶ms)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
std::atomic_bool fImporting(false)
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &headers, CValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex)
Process incoming block headers.
VersionBitsCache versionbitscache
bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, const CBlockIndex *pindexPrev, int64_t nAdjustedTime)
Context-dependent validity checks.
bool CheckBlockHeader(const CBlockHeader &block, CValidationState &state, bool fCheckPOW)
Functions for validating blocks and updating the block tree.
bool fHavePruned
Pruning-related variables and constants.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
CBlockIndex * AddToBlockIndex(const CBlockHeader &block)
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot)
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
bool ConnectBlock(const CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, const CChainParams &chainparams, bool fJustCheck)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
CTxMemPool mempool(::minRelayTxFee)
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock.
void DumpMempool(void)
Dump the mempool to disk.
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight)
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
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,...
void LimitMempoolSize(CTxMemPool &pool, size_t limit, unsigned long age)
class CMainCleanup instance_of_cmaincleanup
void CheckForkWarningConditions()
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...
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
CAmount maxTxFee
Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendra...
bool ReceivedBlockTransactions(const CBlock &block, CValidationState &state, CBlockIndex *pindexNew, const CDiskBlockPos &pos)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
bool AcceptToMemoryPoolWorker(CTxMemPool &pool, CValidationState &state, const CTransactionRef &ptx, bool fLimitFree, bool *pfMissingInputs, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount &nAbsurdFee, std::vector< uint256 > &vHashTxnToUncache)
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
bool CheckFinalTx(const CTransaction &tx, int flags)
Check if transaction will be final in the next block to be created.
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
bool AcceptToMemoryPoolWithTime(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
(try to) add transaction to memory pool with a specified acceptance time
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
void ThreadScriptCheck()
Run an instance of the script checking thread.
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness nonce).
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Compute total signature operation cost of a transaction.
CBlockIndex * pindexBestForkBase
ThresholdState VersionBitsTipState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
bool InitBlockIndex(const CChainParams &chainparams)
Initialize a new block tree database + block data on disk.
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
bool ContextualCheckBlock(const CBlock &block, CValidationState &state, const CBlockIndex *pindexPrev)
bool fPruneMode
True if we're running in -prune mode.
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks)
Check whether all inputs of this transaction are valid (no double spends, scripts & sigs,...
CBlockIndex * pindexBestForkTip
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams, bool fCheckPOW)
bool DisconnectBlock(const CBlock &block, CValidationState &state, const CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
void PruneOneBlockFile(const int fileNumber)
Mark one block file as pruned.
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk.
CWaitableCriticalSection csBestBlock
int VersionBitsTipStateSinceHeight(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
void UnloadBlockIndex()
Unload database information.
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Check whether witness commitments are required for block.
bool ApplyTxInUndo(const CTxInUndo &undo, CCoinsViewCache &view, const COutPoint &out)
Apply the undo operation of a CTxInUndo to the given chain state.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
bool CheckTransaction(const CTransaction &tx, CValidationState &state, bool fCheckDuplicateInputs)
Transaction validation functions.
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Check if transaction will be BIP 68 final in the next block to be created.
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
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.
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
CConditionVariable cvBlockChange
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
bool LoadMempool(void)
Load the mempool from disk.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
Open an undo file (rev?????.dat)
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
bool ReadBlockHeaderFromDisk(CBlockHeader &block, const CBlockIndex *pindex, const Consensus::Params &consensusParams, bool fCheckPOW)
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
void PruneAndFlush()
Prune block files and flush state to disk.
boost::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
CMainSignals & GetMainSignals()
uint32_t VersionBitsMask(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
int VersionBitsStateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos, VersionBitsCache &cache)
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos, VersionBitsCache &cache)
std::map< const CBlockIndex *, ThresholdState > ThresholdConditionCache
void SetfLargeWorkInvalidChainFound(bool flag)
void SetfLargeWorkForkFound(bool flag)
bool GetfLargeWorkForkFound()
void SetMiscWarning(const std::string &strWarning)