45 #include <boost/algorithm/string/replace.hpp> 46 #include <boost/filesystem.hpp> 47 #include <boost/filesystem/fstream.hpp> 48 #include <boost/lexical_cast.hpp> 49 #include <boost/math/distributions/poisson.hpp> 50 #include <boost/thread.hpp> 55 # error "Dash Core cannot be compiled without assertions." 114 struct CBlockIndexWorkComparator
127 if (pa < pb)
return false;
128 if (pa > pb)
return true;
142 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
146 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
149 std::vector<CBlockFileInfo> vinfoBlockFile;
150 int nLastBlockFile = 0;
155 bool fCheckForPruning =
false;
163 uint32_t nBlockSequenceId = 1;
166 set<CBlockIndex*> setDirtyBlockIndex;
169 set<int> setDirtyFileInfo;
206 BOOST_FOREACH(
const CTxIn& txin, tx.
vin) {
242 return IsFinalTx(tx, nBlockHeight, nBlockTime);
253 assert(prevHeights->size() == tx.
vin.size());
261 int64_t nMinTime = -1;
266 bool fEnforceBIP68 =
static_cast<uint32_t
>(tx.
nVersion) >= 2
271 if (!fEnforceBIP68) {
272 return std::make_pair(nMinHeight, nMinTime);
275 for (
size_t txinIndex = 0; txinIndex < tx.
vin.size(); txinIndex++) {
276 const CTxIn& txin = tx.
vin[txinIndex];
283 (*prevHeights)[txinIndex] = 0;
287 int nCoinHeight = (*prevHeights)[txinIndex];
310 return std::make_pair(nMinHeight, nMinTime);
317 if (lockPair.first >= block.
nHeight || lockPair.second >= nBlockTime)
362 std::pair<int, int64_t> lockPair;
363 if (useExistingLockPoints) {
365 lockPair.first = lp->
height;
366 lockPair.second = lp->
time;
371 std::vector<int> prevheights;
372 prevheights.resize(tx.
vin.size());
373 for (
size_t txinIndex = 0; txinIndex < tx.
vin.size(); txinIndex++) {
374 const CTxIn& txin = tx.
vin[txinIndex];
377 return error(
"%s: Missing input", __func__);
381 prevheights[txinIndex] = tip->
nHeight + 1;
383 prevheights[txinIndex] = coins.
nHeight;
388 lp->
height = lockPair.first;
389 lp->
time = lockPair.second;
403 int maxInputHeight = 0;
404 BOOST_FOREACH(
int height, prevheights) {
406 if (height != tip->
nHeight+1) {
407 maxInputHeight = std::max(maxInputHeight, height);
419 unsigned int nSigOps = 0;
420 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
436 unsigned int nSigOps = 0;
437 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
450 (
unsigned int)outpoint.
n>=coins.
vout.size() ||
451 coins.
vout[outpoint.
n].IsNull());
489 nValueOut += txout.
nValue;
495 set<COutPoint> vInOutPoints;
496 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
498 if (vInOutPoints.count(txin.
prevout))
500 vInOutPoints.insert(txin.
prevout);
505 if (tx.
vin[0].scriptSig.size() < 2 || tx.
vin[0].scriptSig.size() > 100)
510 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
532 LogPrint(
"mempool",
"Expired %i transactions from the memory pool\n", expired);
534 std::vector<uint256> vNoSpendsRemaining;
536 BOOST_FOREACH(
const uint256& removed, vNoSpendsRemaining)
550 bool* pfMissingInputs,
bool fOverrideMempoolLimit,
bool fRejectAbsurdFee,
551 std::vector<uint256>& vHashTxnToUncache,
bool fDryRun)
555 *pfMissingInputs =
false;
590 return state.
DoS(10,
error(
"AcceptToMemoryPool : CTxLockRequest %s is invalid", hash.
ToString()),
594 BOOST_FOREACH(
const CTxIn &txin, tx.
vin)
598 return state.
DoS(10,
error(
"AcceptToMemoryPool : Transaction %s conflicts with completed Transaction Lock %s",
604 set<uint256> setConflicts;
607 BOOST_FOREACH(
const CTxIn &txin, tx.
vin)
612 if (!setConflicts.count(ptxConflicting->
GetHash()))
617 return state.
DoS(0,
error(
"AcceptToMemoryPool : Transaction %s conflicts with Transaction Lock Request %s",
622 return state.
DoS(0,
error(
"AcceptToMemoryPool : Transaction Lock Request %s conflicts with transaction %s",
638 bool fReplacementOptOut =
true;
641 BOOST_FOREACH(
const CTxIn &txin, ptxConflicting->
vin)
643 if (txin.
nSequence < std::numeric_limits<unsigned int>::max()-1)
645 fReplacementOptOut =
false;
650 if (fReplacementOptOut)
653 setConflicts.insert(ptxConflicting->
GetHash());
674 vHashTxnToUncache.push_back(hash);
681 BOOST_FOREACH(
const CTxIn txin, tx.
vin) {
686 *pfMissingInputs =
true;
720 CAmount nFees = nValueIn-nValueOut;
723 double nPriorityDummy = 0;
724 pool.
ApplyDeltas(hash, nPriorityDummy, nModifiedFees);
731 bool fSpendsCoinbase =
false;
732 BOOST_FOREACH(
const CTxIn &txin, tx.
vin) {
735 fSpendsCoinbase =
true;
753 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
766 static double dFreeCount;
767 static int64_t nLastTime;
773 dFreeCount *= pow(1.0 - 1.0/600.0, (
double)(nNow - nLastTime));
779 LogPrint(
"mempool",
"Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
794 std::string errString;
795 if (!pool.
CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
806 if (setConflicts.count(hashAncestor))
808 return state.
DoS(10,
error(
"AcceptToMemoryPool: %s spends conflicting transaction %s",
818 size_t nConflictingSize = 0;
819 uint64_t nConflictingCount = 0;
826 if (setConflicts.size())
828 CFeeRate newFeeRate(nModifiedFees, nSize);
829 set<uint256> setConflictsParents;
830 const int maxDescendantsToVisit = 100;
832 BOOST_FOREACH(
const uint256 &hashConflicting, setConflicts)
835 if (mi == pool.
mapTx.end())
839 setIterConflicting.insert(mi);
849 error(
"AcceptToMemoryPool: rejecting replacement %s; cannot replace tx %s with untracked descendants",
851 mi->GetTx().GetHash().ToString()),
871 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
872 if (newFeeRate <= oldFeeRate)
875 error(
"AcceptToMemoryPool: rejecting replacement %s; new feerate %s <= old feerate %s",
878 oldFeeRate.ToString()),
882 BOOST_FOREACH(
const CTxIn &txin, mi->GetTx().vin)
887 nConflictingCount += mi->GetCountWithDescendants();
892 if (nConflictingCount <= maxDescendantsToVisit) {
899 nConflictingFees += it->GetModifiedFee();
900 nConflictingSize += it->GetTxSize();
904 error(
"AcceptToMemoryPool: rejecting replacement %s; too many potential replacements (%d > %d)\n",
907 maxDescendantsToVisit),
911 for (
unsigned int j = 0; j < tx.
vin.size(); j++)
917 if (!setConflictsParents.count(tx.
vin[j].prevout.hash))
922 if (pool.
mapTx.find(tx.
vin[j].prevout.hash) != pool.
mapTx.end())
923 return state.
DoS(0,
error(
"AcceptToMemoryPool: replacement %s adds unconfirmed input, idx %d",
932 if (nModifiedFees < nConflictingFees)
934 return state.
DoS(0,
error(
"AcceptToMemoryPool: rejecting replacement %s, less fees than conflicting txs; %s < %s",
941 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
945 error(
"AcceptToMemoryPool: rejecting replacement %s, not enough additional fees to relay; %s < %s",
954 if(fDryRun)
return true;
972 return error(
"%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
979 LogPrint(
"mempool",
"replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
980 it->GetTx().GetHash().ToString(),
983 (int)nSize - (
int)nConflictingSize);
1001 if (!fOverrideMempoolLimit) {
1015 bool* pfMissingInputs,
bool fOverrideMempoolLimit,
bool fRejectAbsurdFee,
bool fDryRun)
1017 std::vector<uint256> vHashTxToUncache;
1018 bool res =
AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, fOverrideMempoolLimit, fRejectAbsurdFee, vHashTxToUncache, fDryRun);
1019 if (!res || fDryRun) {
1021 BOOST_FOREACH(
const uint256& hashTx, vHashTxToUncache)
1033 return error(
"Timestamp index not enabled");
1036 return error(
"Unable to get hashes for timestamps");
1056 std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,
int start,
int end)
1059 return error(
"address index not enabled");
1062 return error(
"unable to get txids for address");
1068 std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs)
1071 return error(
"address index not enabled");
1074 return error(
"unable to get txids for address");
1096 return error(
"%s: OpenBlockFile failed", __func__);
1102 }
catch (
const std::exception& e) {
1103 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
1107 return error(
"%s: txid mismatch", __func__);
1155 return error(
"WriteBlockToDisk: OpenBlockFile failed");
1158 unsigned int nSize =
fileout.GetSerializeSize(block);
1162 long fileOutPos = ftell(
fileout.Get());
1164 return error(
"WriteBlockToDisk: ftell failed");
1165 pos.
nPos = (
unsigned int)fileOutPos;
1178 return error(
"ReadBlockFromDisk: OpenBlockFile failed for %s", pos.
ToString());
1184 catch (
const std::exception& e) {
1185 return error(
"%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.
ToString());
1190 return error(
"ReadBlockFromDisk: Errors in block header at %s", pos.
ToString());
1200 return error(
"ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1207 int nShift = (nBits >> 24) & 0xff;
1209 double dDiff = (double)0x0000ffff / (
double)(nBits & 0x00ffffff);
1237 dDiff = (double)0x0000ffff / (
double)(nPrevBits & 0x00ffffff);
1242 if (nPrevHeight < 5465) {
1245 nSubsidyBase = (1111.0 / (pow((dDiff+1.0),2.0)));
1246 if(nSubsidyBase > 500) nSubsidyBase = 500;
1247 else if(nSubsidyBase < 1) nSubsidyBase = 1;
1248 }
else if (nPrevHeight < 17000 || (dDiff <= 75 && nPrevHeight < 24000)) {
1251 nSubsidyBase = (11111.0 / (pow((dDiff+51.0)/6.0,2.0)));
1252 if(nSubsidyBase > 500) nSubsidyBase = 500;
1253 else if(nSubsidyBase < 25) nSubsidyBase = 25;
1257 nSubsidyBase = (2222222.0 / (pow((dDiff+2600.0)/9.0,2.0)));
1258 if(nSubsidyBase > 25) nSubsidyBase = 25;
1259 else if(nSubsidyBase < 5) nSubsidyBase = 5;
1267 nSubsidy -= nSubsidy/14;
1273 return fSuperblockPartOnly ? nSuperblockPart : nSubsidy - nSuperblockPart;
1284 if(nHeight > nMNPIBlock) ret += blockValue / 20;
1285 if(nHeight > nMNPIBlock+(nMNPIPeriod* 1)) ret += blockValue / 20;
1286 if(nHeight > nMNPIBlock+(nMNPIPeriod* 2)) ret += blockValue / 20;
1287 if(nHeight > nMNPIBlock+(nMNPIPeriod* 3)) ret += blockValue / 40;
1288 if(nHeight > nMNPIBlock+(nMNPIPeriod* 4)) ret += blockValue / 40;
1289 if(nHeight > nMNPIBlock+(nMNPIPeriod* 5)) ret += blockValue / 40;
1290 if(nHeight > nMNPIBlock+(nMNPIPeriod* 6)) ret += blockValue / 40;
1291 if(nHeight > nMNPIBlock+(nMNPIPeriod* 7)) ret += blockValue / 40;
1292 if(nHeight > nMNPIBlock+(nMNPIPeriod* 9)) ret += blockValue / 40;
1299 static bool lockIBDState =
false;
1312 lockIBDState =
true;
1338 std::string warning = std::string(
"'Warning: Large-work fork detected, forking after block ") +
1346 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__,
1355 LogPrintf(
"%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1357 LogPrintf(
"%s: Warning: Found invalid chain which has higher work (at least ~6 blocks worth of work) than our best chain.\nChain state database corruption likely.\n", __func__);
1374 while (pfork && pfork != plonger)
1377 plonger = plonger->
pprev;
1378 if (pfork == plonger)
1380 pfork = pfork->
pprev;
1403 if (!pindexBestInvalid || pindexNew->
nChainWork > pindexBestInvalid->nChainWork)
1404 pindexBestInvalid = pindexNew;
1406 LogPrintf(
"%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1412 LogPrintf(
"%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1421 setDirtyBlockIndex.insert(pindex);
1422 setBlockIndexCandidates.erase(pindex);
1432 BOOST_FOREACH(
const CTxIn &txin, tx.
vin) {
1436 if (nPos >= coins->
vout.size() || coins->
vout[nPos].IsNull())
1441 if (coins->
vout.size() == 0) {
1468 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1479 return pindexPrev->
nHeight + 1;
1488 return state.
Invalid(
false, 0,
"",
"Inputs unavailable");
1492 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
1503 strprintf(
"tried to spend coinbase at depth %d", nSpendHeight - coins->
nHeight));
1507 nValueIn += coins->
vout[prevout.
n].nValue;
1509 return state.
DoS(100,
false,
REJECT_INVALID,
"bad-txns-inputvalues-outofrange");
1536 pvChecks->reserve(tx.
vin.size());
1547 if (fScriptChecks) {
1548 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
1557 check.
swap(pvChecks->back());
1558 }
else if (!check()) {
1594 return error(
"%s: OpenUndoFile failed", __func__);
1597 unsigned int nSize =
fileout.GetSerializeSize(blockundo);
1601 long fileOutPos = ftell(
fileout.Get());
1603 return error(
"%s: ftell failed", __func__);
1604 pos.
nPos = (
unsigned int)fileOutPos;
1609 hasher << hashBlock;
1610 hasher << blockundo;
1620 if (filein.IsNull())
1621 return error(
"%s: OpenBlockFile failed", __func__);
1626 filein >> blockundo;
1627 filein >> hashChecksum;
1629 catch (
const std::exception& e) {
1630 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
1635 hasher << hashBlock;
1636 hasher << blockundo;
1637 if (hashChecksum != hasher.GetHash())
1638 return error(
"%s: Checksum mismatch", __func__);
1644 bool AbortNode(
const std::string& strMessage,
const std::string& userMessage=
"")
1649 userMessage.empty() ?
_(
"Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1655 bool AbortNode(
CValidationState& state,
const std::string& strMessage,
const std::string& userMessage=
"")
1657 AbortNode(strMessage, userMessage);
1658 return state.
Error(strMessage);
1678 fClean = fClean &&
error(
"%s: undo data overwriting existing transaction", __func__);
1685 fClean = fClean &&
error(
"%s: undo data adding output to missing transaction", __func__);
1688 fClean = fClean &&
error(
"%s: undo data overwriting existing output", __func__);
1689 if (coins->
vout.size() <
out.n+1)
1708 return error(
"DisconnectBlock(): no undo data available");
1710 return error(
"DisconnectBlock(): failure reading undo data");
1712 if (blockUndo.
vtxundo.size() + 1 != block.
vtx.size())
1713 return error(
"DisconnectBlock(): block and undo data inconsistent");
1715 std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
1716 std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > addressUnspentIndex;
1717 std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> > spentIndex;
1720 for (
int i = block.
vtx.size() - 1; i >= 0; i--) {
1726 for (
unsigned int k = tx.
vout.size(); k-- > 0;) {
1729 if (
out.scriptPubKey.IsPayToScriptHash()) {
1730 vector<unsigned char> hashBytes(
out.scriptPubKey.begin()+2,
out.scriptPubKey.begin()+22);
1738 }
else if (
out.scriptPubKey.IsPayToPublicKeyHash()) {
1739 vector<unsigned char> hashBytes(
out.scriptPubKey.begin()+3,
out.scriptPubKey.begin()+23);
1767 if (*outs != outsBlock)
1768 fClean = fClean &&
error(
"DisconnectBlock(): added transaction mismatch? database corrupted");
1778 return error(
"DisconnectBlock(): transaction and undo data inconsistent");
1779 for (
unsigned int j = tx.
vin.size(); j-- > 0;) {
1833 return AbortNode(state,
"Failed to delete address index");
1836 return AbortNode(state,
"Failed to write address unspent index");
1845 LOCK(cs_LastBlockFile);
1852 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1860 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1917 hashRet =
chainActive[nBlockHeight]->GetBlockHash();
1940 ((pindex->
nVersion >> bit) & 1) != 0 &&
1964 if (!
CheckBlock(block, state, !fJustCheck, !fJustCheck))
1979 bool fScriptChecks =
true;
1988 if (it->second->GetAncestor(pindex->
nHeight) == pindex &&
2006 LogPrint(
"bench",
" - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart),
nTimeCheck * 0.000001);
2020 bool fEnforceBIP30 = (!pindex->
phashBlock) ||
2021 !((pindex->
nHeight==91842 && pindex->
GetBlockHash() ==
uint256S(
"0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2022 (pindex->
nHeight==91880 && pindex->
GetBlockHash() ==
uint256S(
"0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2034 if (fEnforceBIP30) {
2038 return state.
DoS(100,
error(
"ConnectBlock(): tried to overwrite transaction"),
2044 int64_t nBIP16SwitchTime = 1333238400;
2045 bool fStrictPayToScriptHash = (pindex->
GetBlockTime() >= nBIP16SwitchTime);
2062 int nLockTimeFlags = 0;
2069 LogPrint(
"bench",
" - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1),
nTimeForks * 0.000001);
2075 std::vector<int> prevheights;
2078 unsigned int nSigOps = 0;
2080 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2081 vPos.reserve(block.
vtx.size());
2082 blockundo.
vtxundo.reserve(block.
vtx.size() - 1);
2083 std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
2084 std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > addressUnspentIndex;
2085 std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> > spentIndex;
2089 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
2094 nInputs += tx.
vin.size();
2097 return state.
DoS(100,
error(
"ConnectBlock(): too many sigops"),
2103 return state.
DoS(100,
error(
"ConnectBlock(): inputs missing/spent"),
2109 prevheights.resize(tx.
vin.size());
2110 for (
size_t j = 0; j < tx.
vin.size(); j++) {
2114 if (!
SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
2115 return state.
DoS(100,
error(
"%s: contains a non-BIP68-final transaction", __func__),
2121 for (
size_t j = 0; j < tx.
vin.size(); j++) {
2156 if (fStrictPayToScriptHash)
2163 return state.
DoS(100,
error(
"ConnectBlock(): too many sigops"),
2169 std::vector<CScriptCheck> vChecks;
2170 bool fCacheResults = fJustCheck;
2172 return error(
"ConnectBlock(): CheckInputs on %s failed with %s",
2174 control.
Add(vChecks);
2178 for (
unsigned int k = 0; k < tx.
vout.size(); k++) {
2181 if (
out.scriptPubKey.IsPayToScriptHash()) {
2182 vector<unsigned char> hashBytes(
out.scriptPubKey.begin()+2,
out.scriptPubKey.begin()+22);
2190 }
else if (
out.scriptPubKey.IsPayToPublicKeyHash()) {
2191 vector<unsigned char> hashBytes(
out.scriptPubKey.begin()+3,
out.scriptPubKey.begin()+23);
2212 vPos.push_back(std::make_pair(tx.
GetHash(), pos));
2216 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);
2227 std::string strError =
"";
2234 return state.
DoS(0,
error(
"ConnectBlock(DASH): couldn't find masternode or superblock payments"),
2239 if (!control.
Wait())
2240 return state.
DoS(100,
false);
2242 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);
2253 return error(
"ConnectBlock(): FindUndoPos failed");
2255 return AbortNode(state,
"Failed to write undo data");
2263 setDirtyBlockIndex.insert(pindex);
2268 return AbortNode(state,
"Failed to write transaction index");
2272 return AbortNode(state,
"Failed to write address index");
2276 return AbortNode(state,
"Failed to write address unspent index");
2282 return AbortNode(state,
"Failed to write transaction index");
2286 return AbortNode(state,
"Failed to write timestamp index");
2292 LogPrint(
"bench",
" - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4),
nTimeIndex * 0.000001);
2295 static uint256 hashPrevBestCoinBase;
2297 hashPrevBestCoinBase = block.
vtx[0].GetHash();
2300 LogPrint(
"bench",
" - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5),
nTimeCallbacks * 0.000001);
2314 static int64_t nLastWrite = 0;
2315 static int64_t nLastFlush = 0;
2316 static int64_t nLastSetChain = 0;
2317 std::set<int> setFilesToPrune;
2318 bool fFlushForPrune =
false;
2322 fCheckForPruning =
false;
2323 if (!setFilesToPrune.empty()) {
2324 fFlushForPrune =
true;
2333 if (nLastWrite == 0) {
2336 if (nLastFlush == 0) {
2339 if (nLastSetChain == 0) {
2340 nLastSetChain = nNow;
2352 bool fDoFullFlush = (mode ==
FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2354 if (fDoFullFlush || fPeriodicWrite) {
2357 return state.
Error(
"out of disk space");
2362 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2363 vFiles.reserve(setDirtyFileInfo.size());
2364 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2365 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2366 setDirtyFileInfo.erase(it++);
2368 std::vector<const CBlockIndex*> vBlocks;
2369 vBlocks.reserve(setDirtyBlockIndex.size());
2370 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2371 vBlocks.push_back(*it);
2372 setDirtyBlockIndex.erase(it++);
2375 return AbortNode(state,
"Files to write to block index database");
2391 return state.
Error(
"out of disk space");
2394 return AbortNode(state,
"Failed to write to coin database");
2400 nLastSetChain = nNow;
2402 }
catch (
const std::runtime_error& e) {
2403 return AbortNode(state, std::string(
"System error while flushing: ") + e.what());
2415 fCheckForPruning =
true;
2427 LogPrintf(
"%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2435 static bool fWarned =
false;
2451 LogPrintf(
"%s: unknown new rules are about to activate (versionbit %i)\n", __func__, bit);
2455 for (
int i = 0; i < 100 && pindex != NULL; i++)
2460 pindex = pindex->
pprev;
2463 LogPrintf(
"%s: %d of last 100 blocks have unexpected version\n", __func__, nUpgraded);
2464 if (nUpgraded > 100/2)
2467 strMiscWarning =
_(
"Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2480 assert(pindexDelete);
2484 return AbortNode(state,
"Failed to read block");
2491 assert(view.
Flush());
2498 std::vector<uint256> vHashUpdate;
2501 list<CTransaction> removed;
2506 vHashUpdate.push_back(tx.
GetHash());
2543 return AbortNode(state,
"Failed to read block");
2549 LogPrint(
"bench",
" - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001,
nTimeReadFromDisk * 0.000001);
2552 bool rv =
ConnectBlock(*pblock, state, pindexNew, view);
2561 assert(view.
Flush());
2564 LogPrint(
"bench",
" - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001,
nTimeFlush * 0.000001);
2569 LogPrint(
"bench",
" - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001,
nTimeChainState * 0.000001);
2571 list<CTransaction> txConflicted;
2586 LogPrint(
"bench",
" - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001,
nTimePostConnect * 0.000001);
2587 LogPrint(
"bench",
"- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001,
nTimeTotal * 0.000001);
2598 LogPrintf(
"DisconnectBlocks -- Got command to replay %d blocks\n", blocks);
2599 for(
int i = 0; i < blocks; i++) {
2615 if((*it).second >
GetTime() - (nBlocks*60*5)) {
2620 LogPrintf(
"ReprocessBlocks -- %s\n", (*it).first.ToString());
2645 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2646 if (it == setBlockIndexCandidates.rend())
2654 bool fInvalidAncestor =
false;
2664 if (fFailedChain || fMissingData) {
2666 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->
nChainWork > pindexBestInvalid->nChainWork))
2667 pindexBestInvalid = pindexNew;
2670 while (pindexTest != pindexFailed) {
2673 }
else if (fMissingData) {
2677 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->
pprev, pindexFailed));
2679 setBlockIndexCandidates.erase(pindexFailed);
2680 pindexFailed = pindexFailed->
pprev;
2682 setBlockIndexCandidates.erase(pindexTest);
2683 fInvalidAncestor =
true;
2686 pindexTest = pindexTest->
pprev;
2688 if (!fInvalidAncestor)
2697 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2698 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it,
chainActive.
Tip())) {
2699 setBlockIndexCandidates.erase(it++);
2702 assert(!setBlockIndexCandidates.empty());
2716 bool fBlocksDisconnected =
false;
2720 fBlocksDisconnected =
true;
2724 std::vector<CBlockIndex*> vpindexToConnect;
2725 bool fContinue =
true;
2726 int nHeight = pindexFork ? pindexFork->
nHeight : -1;
2727 while (fContinue && nHeight != pindexMostWork->
nHeight) {
2730 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->
nHeight);
2731 vpindexToConnect.clear();
2732 vpindexToConnect.reserve(nTargetHeight - nHeight);
2734 while (pindexIter && pindexIter->
nHeight != nHeight) {
2735 vpindexToConnect.push_back(pindexIter);
2736 pindexIter = pindexIter->
pprev;
2738 nHeight = nTargetHeight;
2741 BOOST_REVERSE_FOREACH(
CBlockIndex *pindexConnect, vpindexToConnect) {
2742 if (!
ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2748 fInvalidFound =
true;
2766 if (fBlocksDisconnected) {
2782 bool fNotify =
false;
2783 bool fInitialBlockDownload =
false;
2790 if (pindexHeader != pindexHeaderOld) {
2793 pindexHeaderOld = pindexHeader;
2812 boost::this_thread::interruption_point();
2817 bool fInitialDownload;
2821 if (pindexMostWork == NULL) {
2826 if (pindexMostWork == NULL || pindexMostWork ==
chainActive.
Tip())
2829 bool fInvalidFound =
false;
2833 if (fInvalidFound) {
2835 pindexMostWork = NULL;
2849 if (pindexFork != pindexNewTip) {
2852 }
while (pindexNewTip != pindexMostWork);
2869 setDirtyBlockIndex.insert(pindex);
2870 setBlockIndexCandidates.erase(pindex);
2875 setDirtyBlockIndex.insert(pindexWalk);
2876 setBlockIndexCandidates.erase(pindexWalk);
2892 setBlockIndexCandidates.insert(it->second);
2906 int nHeight = pindex->
nHeight;
2911 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2913 setDirtyBlockIndex.insert(it->second);
2915 setBlockIndexCandidates.insert(it->second);
2917 if (it->second == pindexBestInvalid) {
2919 pindexBestInvalid = NULL;
2926 while (pindex != NULL) {
2929 setDirtyBlockIndex.insert(pindex);
2931 pindex = pindex->
pprev;
2950 pindexNew->nSequenceId = 0;
2951 BlockMap::iterator mi =
mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2952 pindexNew->phashBlock = &((*mi).first);
2956 pindexNew->pprev = (*miPrev).second;
2957 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2958 pindexNew->BuildSkip();
2960 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) +
GetBlockProof(*pindexNew);
2965 setDirtyBlockIndex.insert(pindexNew);
2973 pindexNew->
nTx = block.
vtx.size();
2980 setDirtyBlockIndex.insert(pindexNew);
2984 deque<CBlockIndex*> queue;
2985 queue.push_back(pindexNew);
2988 while (!queue.empty()) {
2993 LOCK(cs_nBlockSequenceId);
2997 setBlockIndexCandidates.insert(pindex);
2999 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3000 while (range.first != range.second) {
3001 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3002 queue.push_back(it->second);
3004 mapBlocksUnlinked.erase(it);
3009 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3018 LOCK(cs_LastBlockFile);
3020 unsigned int nFile = fKnown ? pos.
nFile : nLastBlockFile;
3021 if (vinfoBlockFile.size() <= nFile) {
3022 vinfoBlockFile.resize(nFile + 1);
3028 if (vinfoBlockFile.size() <= nFile) {
3029 vinfoBlockFile.resize(nFile + 1);
3033 pos.
nPos = vinfoBlockFile[nFile].nSize;
3036 if ((
int)nFile != nLastBlockFile) {
3038 LogPrintf(
"Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
3041 nLastBlockFile = nFile;
3044 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3046 vinfoBlockFile[nFile].nSize = std::max(pos.
nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3048 vinfoBlockFile[nFile].nSize += nAddSize;
3053 if (nNewChunks > nOldChunks) {
3055 fCheckForPruning =
true;
3065 return state.
Error(
"out of disk space");
3069 setDirtyFileInfo.insert(nFile);
3077 LOCK(cs_LastBlockFile);
3079 unsigned int nNewSize;
3080 pos.
nPos = vinfoBlockFile[nFile].nUndoSize;
3081 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3082 setDirtyFileInfo.insert(nFile);
3086 if (nNewChunks > nOldChunks) {
3088 fCheckForPruning =
true;
3098 return state.
Error(
"out of disk space");
3108 return state.
DoS(50,
error(
"CheckBlockHeader(): proof of work failed"),
3113 return state.
Invalid(
error(
"CheckBlockHeader(): block timestamp too far in the future"),
3132 if (fCheckMerkleRoot) {
3136 return state.
DoS(100,
error(
"CheckBlock(): hashMerkleRoot mismatch"),
3143 return state.
DoS(100,
error(
"CheckBlock(): duplicate transaction"),
3153 return state.
DoS(100,
error(
"%s: size limits failed", __func__),
3157 if (block.
vtx.empty() || !block.
vtx[0].IsCoinBase())
3158 return state.
DoS(100,
error(
"CheckBlock(): first tx is not coinbase"),
3160 for (
unsigned int i = 1; i < block.
vtx.size(); i++)
3161 if (block.
vtx[i].IsCoinBase())
3162 return state.
DoS(100,
error(
"CheckBlock(): more than one coinbase"),
3176 BOOST_FOREACH(
const CTxIn& txin, tx.
vin) {
3183 return state.
DoS(0,
error(
"CheckBlock(DASH): transaction %s conflicts with transaction lock %s",
3190 LogPrintf(
"CheckBlock(DASH): spork is off, skipping transaction locking checks\n");
3198 return error(
"CheckBlock(): CheckTransaction of %s failed with %s",
3202 unsigned int nSigOps = 0;
3209 return state.
DoS(100,
error(
"CheckBlock(): out-of-bounds SigOpCount"),
3212 if (fCheckPOW && fCheckMerkleRoot)
3223 int nHeight = pindexPrev->
nHeight+1;
3226 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3227 return state.
DoS(100,
error(
"%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3235 int nHeight = pindexPrev->
nHeight + 1;
3243 if (abs(n1-n2) > n1*0.5)
3244 return state.
DoS(100,
error(
"%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, abs(n1-n2), n1, n2, nHeight),
3248 return state.
DoS(100,
error(
"%s : incorrect proof of work at %d", __func__, nHeight),
3254 return state.
Invalid(
error(
"%s: block's timestamp is too early", __func__),
3259 return state.
Invalid(
error(
"%s: rejected nVersion=1 block", __func__),
3264 return state.
Invalid(
error(
"%s: rejected nVersion=2 block", __func__),
3269 return state.
Invalid(
error(
"%s : rejected nVersion=3 block", __func__),
3277 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->
nHeight + 1;
3281 int nLockTimeFlags = 0;
3293 unsigned int nMaxBlockSize =
MaxBlockSize(fDIP0001Active_context);
3295 return state.
DoS(100,
error(
"%s: size limits failed", __func__),
3300 unsigned int nSigOps = 0;
3302 if (!
IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3303 return state.
DoS(10,
error(
"%s: contains a non-final transaction", __func__),
REJECT_INVALID,
"bad-txns-nonfinal");
3306 return state.
DoS(100,
error(
"%s: contains an over-sized transaction", __func__),
REJECT_INVALID,
"bad-txns-oversized");
3313 return state.
DoS(100,
error(
"%s: out-of-bounds SigOpCount", __func__),
3321 if (block.
vtx[0].vin[0].scriptSig.size() <
expect.size() ||
3322 !std::equal(
expect.begin(),
expect.end(), block.
vtx[0].vin[0].scriptSig.begin())) {
3323 return state.
DoS(100,
error(
"%s: block height mismatch in coinbase", __func__),
REJECT_INVALID,
"bad-cb-height");
3343 pindex = miSelf->second;
3347 return state.
Invalid(
error(
"%s: block is marked invalid", __func__), 0,
"duplicate");
3358 return state.
DoS(10,
error(
"%s: prev block not found", __func__), 0,
"bad-prevblk");
3359 pindexPrev = (*mi).second;
3365 return error(
"%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.
GetRejectReason().c_str());
3402 if (fNewBlock) *fNewBlock =
false;
3406 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3430 if (fAlreadyHave)
return true;
3432 if (pindex->
nTx != 0)
return true;
3433 if (!fHasMoreWork)
return true;
3434 if (fTooFarAhead)
return true;
3436 if (fNewBlock) *fNewBlock =
true;
3441 setDirtyBlockIndex.insert(pindex);
3446 int nHeight = pindex->
nHeight;
3455 return error(
"AcceptBlock(): FindBlockPos failed");
3458 AbortNode(state,
"Failed to write block");
3460 return error(
"AcceptBlock(): ReceivedBlockTransactions failed");
3461 }
catch (
const std::runtime_error& e) {
3462 return AbortNode(state, std::string(
"System error: ") + e.what());
3465 if (fCheckForPruning)
3473 unsigned int nFound = 0;
3474 for (
int i = 0; i < consensusParams.
nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3476 if (pstart->
nVersion >= minVersion)
3478 pstart = pstart->
pprev;
3480 return (nFound >= nRequired);
3491 if (fNewBlock) *fNewBlock =
false;
3493 bool ret =
AcceptBlock(*pblock, state, chainparams, &pindex, fForceProcessing, dbp, fNewBlock);
3497 return error(
"%s: AcceptBlock FAILED", __func__);
3505 return error(
"%s: ActivateBestChain failed", __func__);
3516 return error(
"%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.
GetRejectReason().c_str());
3520 indexDummy.
pprev = pindexPrev;
3526 if (!
CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
3530 if (!
ConnectBlock(block, state, &indexDummy, viewNew,
true))
3556 if (pindex->
nFile == fileNumber) {
3562 setDirtyBlockIndex.insert(pindex);
3568 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->
pprev);
3569 while (range.first != range.second) {
3570 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3572 if (it->second == pindex) {
3573 mapBlocksUnlinked.erase(it);
3579 vinfoBlockFile[fileNumber].SetNull();
3580 setDirtyFileInfo.insert(fileNumber);
3586 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3590 LogPrintf(
"Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3611 uint64_t nBytesToPrune;
3615 for (
int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3616 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3618 if (vinfoBlockFile[fileNumber].nSize == 0)
3625 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3630 setFilesToPrune.insert(fileNumber);
3631 nCurrentUsage -= nBytesToPrune;
3636 LogPrint(
"prune",
"Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3638 ((int64_t)
nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3639 nLastBlockWeCanPrune,
count);
3644 uint64_t nFreeBytesAvailable = boost::filesystem::space(
GetDataDir()).available;
3648 return AbortNode(
"Disk space is low!",
_(
"Error: Disk space is low!"));
3658 boost::filesystem::create_directories(path.parent_path());
3659 FILE*
file = fopen(path.string().c_str(),
"rb+");
3660 if (!
file && !fReadOnly)
3661 file = fopen(path.string().c_str(),
"wb+");
3663 LogPrintf(
"Unable to open file %s\n", path.string());
3667 if (fseek(
file, pos.
nPos, SEEK_SET)) {
3668 LogPrintf(
"Unable to seek to position %u of %s\n", pos.
nPos, path.string());
3697 return (*mi).second;
3702 throw runtime_error(
"InsertBlockIndex(): new CBlockIndex failed");
3703 mi =
mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3704 pindexNew->phashBlock = &((*mi).first);
3715 boost::this_thread::interruption_point();
3718 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3723 vSortedByHeight.push_back(make_pair(pindex->
nHeight, pindex));
3725 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3732 if (pindex->
nTx > 0) {
3733 if (pindex->
pprev) {
3738 mapBlocksUnlinked.insert(std::make_pair(pindex->
pprev, pindex));
3745 setBlockIndexCandidates.insert(pindex);
3747 pindexBestInvalid = pindex;
3756 vinfoBlockFile.resize(nLastBlockFile + 1);
3757 LogPrintf(
"%s: last block file = %i\n", __func__, nLastBlockFile);
3758 for (
int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3761 LogPrintf(
"%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3762 for (
int nFile = nLastBlockFile + 1;
true; nFile++) {
3765 vinfoBlockFile.push_back(info);
3772 LogPrintf(
"Checking all blk files are present...\n");
3773 set<int> setBlkDataFiles;
3778 setBlkDataFiles.insert(pindex->
nFile);
3781 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3792 LogPrintf(
"LoadBlockIndexDB(): Block files have previously been pruned\n");
3795 bool fReindexing =
false;
3801 LogPrintf(
"%s: transaction index %s\n", __func__,
fTxIndex ?
"enabled" :
"disabled");
3823 LogPrintf(
"%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3848 if (nCheckDepth <= 0)
3849 nCheckDepth = 1000000000;
3852 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3853 LogPrintf(
"Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3857 int nGoodTransactions = 0;
3861 boost::this_thread::interruption_point();
3868 return error(
"VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3870 if (nCheckLevel >= 1 && !
CheckBlock(block, state))
3871 return error(
"VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3873 if (nCheckLevel >= 2 && pindex) {
3877 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3878 return error(
"VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3885 return error(
"VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3886 pindexState = pindex->
pprev;
3888 nGoodTransactions = 0;
3889 pindexFailure = pindex;
3891 nGoodTransactions += block.
vtx.size();
3897 return error(
"VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n",
chainActive.
Height() - pindexFailure->
nHeight + 1, nGoodTransactions);
3900 if (nCheckLevel >= 4) {
3903 boost::this_thread::interruption_point();
3925 setBlockIndexCandidates.clear();
3927 pindexBestInvalid = NULL;
3930 mapBlocksUnlinked.clear();
3931 vinfoBlockFile.clear();
3933 nBlockSequenceId = 1;
3934 setDirtyBlockIndex.clear();
3935 setDirtyFileInfo.clear();
3942 delete entry.second;
3979 LogPrintf(
"Initializing databases...\n");
3990 return error(
"%s: FindBlockPos failed", __func__);
3992 return error(
"%s: writing genesis block to disk failed", __func__);
3995 return error(
"%s: genesis block not accepted", __func__);
3997 return error(
"%s: genesis block cannot be activated", __func__);
4000 }
catch (
const std::runtime_error& e) {
4001 return error(
"%s: failed to initialize block database: %s", __func__, e.what());
4011 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4019 uint64_t nRewind = blkdat.
GetPos();
4020 while (!blkdat.
eof()) {
4021 boost::this_thread::interruption_point();
4026 unsigned int nSize = 0;
4031 nRewind = blkdat.
GetPos()+1;
4037 if (nSize < 80 || nSize > nMaxBlockSize)
4039 }
catch (
const std::exception&) {
4045 uint64_t nBlockPos = blkdat.
GetPos();
4047 dbp->
nPos = nBlockPos;
4048 blkdat.
SetLimit(nBlockPos + nSize);
4049 blkdat.
SetPos(nBlockPos);
4052 nRewind = blkdat.
GetPos();
4057 LogPrint(
"reindex",
"%s: Out of order block %s, parent %s not known\n", __func__, hash.
ToString(),
4058 block.hashPrevBlock.ToString());
4060 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4068 if (
AcceptBlock(block, state, chainparams, NULL,
true, dbp, NULL))
4087 deque<uint256> queue;
4088 queue.push_back(hash);
4089 while (!queue.empty()) {
4092 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4093 while (range.first != range.second) {
4094 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4097 LogPrint(
"reindex",
"%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4101 if (
AcceptBlock(block, dummy, chainparams, NULL,
true, &it->second, NULL))
4104 queue.push_back(block.GetHash());
4108 mapBlocksUnknownParent.erase(it);
4112 }
catch (
const std::exception& e) {
4113 LogPrintf(
"%s: Deserialize or I/O error - %s\n", __func__, e.what());
4116 }
catch (
const std::runtime_error& e) {
4117 AbortNode(std::string(
"System error: ") + e.what());
4141 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4143 forward.insert(std::make_pair(it->second->pprev, it->second));
4148 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4150 rangeGenesis.first++;
4151 assert(rangeGenesis.first == rangeGenesis.second);
4162 CBlockIndex* pindexFirstNotTransactionsValid = NULL;
4165 while (pindex != NULL) {
4169 if (pindexFirstNeverProcessed == NULL && pindex->
nTx == 0) pindexFirstNeverProcessed = pindex;
4176 if (pindex->
pprev == NULL) {
4187 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4195 assert((pindexFirstNeverProcessed != NULL) == (pindex->
nChainTx == 0));
4196 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->
nChainTx == 0));
4197 assert(pindex->
nHeight == nHeight);
4200 assert(pindexFirstNotTreeValid == NULL);
4204 if (pindexFirstInvalid == NULL) {
4208 if (!CBlockIndexWorkComparator()(pindex,
chainActive.
Tip()) && pindexFirstNeverProcessed == NULL) {
4209 if (pindexFirstInvalid == NULL) {
4215 assert(setBlockIndexCandidates.count(pindex));
4222 assert(setBlockIndexCandidates.count(pindex) == 0);
4225 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->
pprev);
4226 bool foundInUnlinked =
false;
4227 while (rangeUnlinked.first != rangeUnlinked.second) {
4228 assert(rangeUnlinked.first->first == pindex->
pprev);
4229 if (rangeUnlinked.first->second == pindex) {
4230 foundInUnlinked =
true;
4233 rangeUnlinked.first++;
4237 assert(foundInUnlinked);
4240 if (pindexFirstMissing == NULL) assert(!foundInUnlinked);
4252 if (!CBlockIndexWorkComparator()(pindex,
chainActive.
Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4253 if (pindexFirstInvalid == NULL) {
4254 assert(foundInUnlinked);
4262 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4263 if (range.first != range.second) {
4265 pindex = range.first->second;
4274 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4275 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4276 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4277 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4278 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4279 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4280 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4284 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4285 while (rangePar.first->second != pindex) {
4286 assert(rangePar.first != rangePar.second);
4291 if (rangePar.first != rangePar.second) {
4293 pindex = rangePar.first->second;
4305 assert(nNodes == forward.size());
4316 string strStatusBar;
4321 strStatusBar =
"This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
4322 strGUI =
_(
"This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4326 strStatusBar = strRPC = strGUI =
"testsafemode enabled";
4338 strStatusBar = strRPC =
"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
4339 strGUI =
_(
"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4344 strStatusBar = strRPC =
"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
4345 strGUI =
_(
"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
4353 const CAlert& alert = item.second;
4362 if (strFor ==
"gui")
4364 else if (strFor ==
"statusbar")
4365 return strStatusBar;
4366 else if (strFor ==
"rpc")
4368 assert(!
"GetWarnings(): invalid parameter");
4372 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));
4389 delete (*it1).second;
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
static const unsigned int MAX_STANDARD_TX_SIGOPS
void TrimToSize(size_t sizelimit, std::vector< uint256 > *pvNoSpendsRemaining=NULL)
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, const CBlock *pblock)
unsigned int GetSigOpCount(bool fAccurate) const
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
bool GetBlockHash(uint256 &hashRet, int nBlockHeight)
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
boost::signals2::signal< void(const CTransaction &, const CBlock *)> SyncTransaction
full block available in blk*.dat
static void UpdateTip(CBlockIndex *pindexNew)
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, bool fAssumeMasternodeIsUpgraded)
int Threshold(const Consensus::Params ¶ms) const
static const unsigned int MAX_BLOCKFILE_SIZE
bool IsPayToPublicKeyHash() const
static const unsigned int DEFAULT_DESCENDANT_LIMIT
static void PruneBlockIndexCandidates()
static bool IsSuperMajority(int minVersion, const CBlockIndex *pstart, unsigned nRequired, const Consensus::Params &consensusParams)
void Add(std::vector< T > &vChecks)
boost::condition_variable CConditionVariable
void remove(const CTransaction &tx, std::list< CTransaction > &removed, bool fRecursive=false)
CAmount GetMasternodePayment(int nHeight, CAmount blockValue)
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
static const bool DEFAULT_PERMIT_BAREMULTISIG
uint64_t nTimeLast
earliest time of block in file
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
void SetTip(CBlockIndex *pindex)
uint64_t nTimeFirst
highest height of block in file
static const unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS
bool GetLockedOutPointTxHash(const COutPoint &outpoint, uint256 &hashRet)
CTxMemPool mempool(::minRelayTxFee)
int GetUTXOHeight(const COutPoint &outpoint)
std::string GetRejectReason() const
static int64_t nTimeConnectTotal
void FileCommit(FILE *fileout)
int64_t MaxTipAge() const
#define MESSAGE_START_SIZE
bool GetAddressUnspent(uint160 addressHash, int type, std::vector< std::pair< CAddressUnspentKey, CAddressUnspentValue > > &unspentOutputs)
static void InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state)
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, CBlockIndex *const pindexPrev)
static const int SPORK_3_INSTANTSEND_BLOCK_FILTERING
CBlockIndex * pindexBestForkBase
static const unsigned char REJECT_INSUFFICIENTFEE
bool Error(const std::string &strRejectReasonIn)
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
unsigned int MaxBlockSize(bool fDIP0001Active)
static const CAmount MAX_MONEY
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector< CScriptCheck > *pvChecks)
bool RaiseValidity(enum BlockStatus nUpTo)
uint64_t GetHash(const uint256 &salt) const
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params ¶ms)
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data)
Returns last CBlockIndex* in mapBlockIndex that is a checkpoint.
descends from failed block
static const int32_t VERSIONBITS_TOP_MASK
static const unsigned int REJECT_ALREADY_KNOWN
bool GetUTXOCoins(const COutPoint &outpoint, CCoins &coins)
CWaitableCriticalSection csBestBlock
static void FlushBlockFile(bool fFinalize=false)
const Consensus::Params & GetConsensus() const
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight)
static const CAmount COIN
bool ReadAddressUnspentIndex(uint160 addressHash, int type, std::vector< std::pair< CAddressUnspentKey, CAddressUnspentValue > > &vect)
static bool ConnectTip(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindexNew, const CBlock *pblock)
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
static const unsigned int MIN_BLOCKS_TO_KEEP
static const unsigned int DEFAULT_ANCESTOR_LIMIT
std::vector< CTxInUndo > vprevout
int Period(const Consensus::Params ¶ms) const
static int64_t nTimeForks
static bool AcceptBlock(const CBlock &block, CValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex, bool fRequested, const CDiskBlockPos *dbp, bool *fNewBlock)
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
static const unsigned int REJECT_CONFLICT
bool IsBlockPayeeValid(const CTransaction &txNew, int nBlockHeight, CAmount blockReward)
static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS]
bool MoneyRange(const CAmount &nValue)
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
std::string ToString() const
unsigned int GetSizeOfCompactSize(uint64_t nSize)
boost::signals2::signal< void(const CBlockIndex *, bool fInitialDownload)> NotifyHeaderTip
bool IsAvailable(unsigned int nPos) const
check whether a particular output is still available
static const uint32_t SEQUENCE_FINAL
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
static const int COINBASE_MATURITY
bool ReadAddressIndex(uint160 addressHash, int type, std::vector< std::pair< CAddressIndexKey, CAmount > > &addressIndex, int start=0, int end=0)
std::map< COutPoint, CInPoint > mapNextTx
bool fCoinBase
whether transaction is a coinbase
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
static const unsigned int DEFAULT_LIMITFREERELAY
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
int nSubsidyHalvingInterval
map< uint256, int64_t > mapRejectedBlocks GUARDED_BY(cs_main)
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee, bool fDryRun)
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
uint32_t VersionBitsMask(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
bool HaveCoins(const uint256 &txid) const
CAmount GetFee(size_t size) const
bool CheckTxInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight)
static const uint64_t nMinDiskSpace
CAmount GetValueOut() const
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyHeaderTip
void AddTransactionsUpdated(unsigned int n)
CDiskBlockPos GetBlockPos() const
const CTxOut & GetOutputFor(const CTxIn &input) const
indexed_transaction_set mapTx
void UnlinkPrunedFiles(std::set< int > &setFilesToPrune)
void UpdateTransactionsFromBlock(const std::vector< uint256 > &hashesToUpdate)
bool WriteFlag(const std::string &name, bool fValue)
static const unsigned char REJECT_INVALID
CBlockIndex * pindexBestForkTip
static const unsigned char REJECT_OBSOLETE
void RenameThread(const char *name)
std::string ToString() const
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)
static CBlockIndex * FindMostWorkChain()
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
boost::signals2::signal< bool(const uint256 &)> UpdatedTransaction
static const bool DEFAULT_ADDRESSINDEX
double ConvertBitsToDouble(unsigned int nBits)
uint32_t nRuleChangeActivationThreshold
ThresholdState VersionBitsTipState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
arith_uint256 UintToArith256(const uint256 &a)
std::vector< CTransaction > vtx
bool lookup(uint256 hash, CTransaction &result) const
const CBlock & GenesisBlock() const
static const uint32_t SEQUENCE_LOCKTIME_MASK
unsigned int nSize
number of blocks stored in file
static bool AcceptBlockHeader(const CBlockHeader &block, CValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex)
bool ProcessNewBlock(const CChainParams &chainparams, const CBlock *pblock, bool fForceProcessing, const CDiskBlockPos *dbp, bool *fNewBlock)
const char * ScriptErrorString(const ScriptError serror)
bool Contains(const CBlockIndex *pindex) const
void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const
bool getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
static bool ActivateBestChainStep(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindexMostWork, const CBlock *pblock, bool &fInvalidFound)
bool exists(uint256 hash) const
uint32_t nMinerConfirmationWindow
#define CLIENT_VERSION_IS_RELEASE
Set to true for release, false for prerelease or test build.
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
WarningBitsConditionChecker(int bitIn)
#define AssertLockHeld(cs)
bool CheckDiskSpace(uint64_t nAdditionalBytes)
CCoinsViewCache * pcoinsTip
bool DisconnectBlocks(int blocks)
std::atomic< bool > fDIP0001WasLockedIn
std::vector< CTxOut > vout
unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are d...
bool HasNoInputsOf(const CTransaction &tx) const
bool fLargeWorkInvalidChainFound
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
CDiskBlockPos GetUndoPos() const
void LimitMempoolSize(CTxMemPool &pool, size_t limit, unsigned long age)
uint64_t PruneAfterHeight() const
static const bool DEFAULT_ALERTS
bool TruncateFile(FILE *file, unsigned int length)
bool GetBoolArg(const std::string &strArg, bool fDefault)
bool CheckFinalTx(const CTransaction &tx, int flags)
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
void PruneOneBlockFile(const int fileNumber)
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
static void NotifyHeaderTip()
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
boost::signals2::signal< void(const CBlockLocator &)> SetBestChain
int GetSpendHeight(const CCoinsViewCache &inputs)
static const unsigned int BLOCKFILE_CHUNK_SIZE
void CalculateDescendants(txiter it, setEntries &setDescendants)
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
static int64_t nTimeChainState
unsigned int GetSerializeSize(char a, int, int=0)
CBlockIndex * AddToBlockIndex(const CBlockHeader &block)
static int64_t nTimeTotal
CMasternodePayments mnpayments
unsigned int nHeightLast
lowest height of block in file
bool Spend(uint32_t nPos)
mark a vout spent
static int LogPrint(const char *category, const char *format)
CBlockIndex * pindexBestHeader
boost::signals2::signal< void(const CBlockIndex *)> AcceptedBlockHeader
static bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
void removeForBlock(const std::vector< CTransaction > &vtx, unsigned int nBlockHeight, std::list< CTransaction > &conflicts, bool fCurrentEstimate=true)
std::vector< CTxUndo > vtxundo
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
int nMasternodePaymentsIncreaseBlock
static const unsigned int MAX_LEGACY_BLOCK_SIZE
static CCheckQueue< CScriptCheck > scriptcheckqueue(128)
std::string ToString() const
static const unsigned int DEFAULT_BYTES_PER_SIGOP
unsigned int MaxBlockSigOps(bool fDIP0001Active)
bool ReadSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
stage after last reached validness failed
bool GetMasternodeInfo(const COutPoint &outpoint, masternode_info_t &mnInfoRet)
uint256 uint256S(const char *str)
static const unsigned char REJECT_NONSTANDARD
void swap(CScriptCheck &check)
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
static const unsigned int UNDOFILE_CHUNK_SIZE
CClientUIInterface uiInterface
static bool error(const char *format)
static int64_t nTimeIndex
uint32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
void check(const CCoinsViewCache *pcoins) const
bool IsInitialBlockDownload()
CBlockIndex * maxInputBlock
CBlockIndex * Genesis() const
int nMajorityRejectBlockOutdated
map< uint256, CAlert > mapAlerts
std::atomic< bool > fDIP0001ActiveAtTip
void SetBackend(CCoinsView &viewIn)
CMainSignals & GetMainSignals()
bool AllowFree(double dPriority)
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view...
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
CCriticalSection cs_mapAlerts
arith_uint256 GetBlockProof(const CBlockIndex &block)
bool TestLockPointValidity(const LockPoints *lp)
int nFile
Which # file this block is stored in (blk?????.dat)
void SetBestBlock(const uint256 &hashBlock)
bool IsPayToScriptHash() const
std::string ToString() const
CCoinsModifier ModifyCoins(const uint256 &txid)
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo *> > &fileInfo, int nLastFile, const std::vector< const CBlockIndex *> &blockinfo)
class CMainCleanup instance_of_cmaincleanup
bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params ¶ms)
static const unsigned char REJECT_DUPLICATE
static void CheckBlockIndex(const Consensus::Params &consensusParams)
std::string ToString() const
std::string FormatMoney(const CAmount &n)
unsigned int GetRejectCode() const
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
void addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
int nMajorityEnforceBlockUpgrade
double GuessVerificationProgress(const CCheckpointData &data, CBlockIndex *pindex, bool fSigchecks)
Guess how far we are in the verification process at the given block index.
static const int SEQUENCE_LOCKTIME_GRANULARITY
VersionBitsCache versionbitscache
static int64_t nTimeCallbacks
static int64_t nTimeCheck
static const unsigned int DATABASE_WRITE_INTERVAL
const CMessageHeader::MessageStartChars & MessageStart() const
std::set< txiter, CompareIteratorByHash > setEntries
static int64_t nTimeConnect
const CCheckpointData & Checkpoints() const
bool CheckBlockHeader(const CBlockHeader &block, CValidationState &state, bool fCheckPOW)
unsigned int GetLegacySigOpCount(const CTransaction &tx)
std::map< const CBlockIndex *, ThresholdState > ThresholdConditionCache
static int64_t nTimeReadFromDisk
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
void Uncache(const uint256 &txid)
bool CorruptionPossible() const
static bool FlushStateToDisk(CValidationState &state, FlushStateMode mode)
CSporkManager sporkManager
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
bool IsBlockValueValid(const CBlock &block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet)
TODO: all 4 functions do not belong here really, they should be refactored/moved somewhere (main...
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
bool WriteTimestampIndex(const CTimestampIndexKey ×tampIndex)
const std::vector< CTxIn > vin
boost::signals2::signal< void(const CBlock &, const CValidationState &)> BlockChecked
static const bool DEFAULT_CHECKPOINTS_ENABLED
bool UpdateAddressUnspentIndex(const std::vector< std::pair< CAddressUnspentKey, CAddressUnspentValue > > &vect)
std::string FormatStateMessage(const CValidationState &state)
static const unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
static const bool DEFAULT_ENABLE_REPLACEMENT
std::map< uint256, int64_t > mapRejectedBlocks
bool ReceivedBlockTransactions(const CBlock &block, CValidationState &state, CBlockIndex *pindexNew, const CDiskBlockPos &pos)
uint256 nMinimumChainWork
static const bool DEFAULT_TESTSAFEMODE
bool ReadTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector< uint256 > &vect)
std::string GetWarnings(const std::string &strFor)
bool ConnectBlock(const CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck)
bool EraseAddressIndex(const std::vector< std::pair< CAddressIndexKey, CAmount > > &vect)
static bool ApplyTxInUndo(const CTxInUndo &undo, CCoinsViewCache &view, const COutPoint &out)
int nMasternodePaymentsIncreasePeriod
bool InvalidateBlock(CValidationState &state, const Consensus::Params &consensusParams, CBlockIndex *pindex)
CBlockIndex * Next(const CBlockIndex *pindex) const
bool LoadBlockIndexGuts()
const CChainParams & Params()
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
int GetUTXOConfirmations(const COutPoint &outpoint)
boost::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
static const int PROTOCOL_VERSION
bool HaveCoinsInCache(const uint256 &txid) const
const uint256 & GetHash() const
static const int32_t VERSIONBITS_TOP_BITS
static void Notify(const std::string &strMessage, bool fThread)
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
double GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const
int64_t GetAdjustedTime()
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
uint256 GetBlockHash() const
void CheckForkWarningConditions()
static const bool DEFAULT_TIMESTAMPINDEX
boost::signals2::signal< void(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transactions)
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &headers, CValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex)
bool ReadReindexing(bool &fReindex)
static bool LoadBlockIndexDB()
bool ReadLastBlockFile(int &nFile)
static int64_t nTimeVerify
void addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
static int64_t nTimePostConnect
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
CFeeRate GetMinFee(size_t sizelimit) const
const std::vector< CTxOut > vout
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
static std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
CBlockIndex * Tip() const
static bool CheckIndexAgainstCheckpoint(const CBlockIndex *pindexPrev, CValidationState &state, const CChainParams &chainparams, const uint256 &hash)
CBlockTreeDB * pblocktree
bool CheckTransaction(const CTransaction &tx, CValidationState &state)
bool GetAddressIndex(uint160 addressHash, int type, std::vector< std::pair< CAddressIndexKey, CAmount > > &addressIndex, int start, int end)
bool WriteBlockToDisk(const CBlock &block, CDiskBlockPos &pos, const CMessageHeader::MessageStartChars &messageStart)
bool IsStandardTx(const CTransaction &tx, std::string &reason)
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
int64_t GetMedianTimePast() const
bool ReadFlag(const std::string &name, bool &fValue)
static const std::string MAIN
bool ReconsiderBlock(CValidationState &state, CBlockIndex *pindex)
bool DoS(int level, bool ret=false, unsigned int chRejectCodeIn=0, const std::string &strRejectReasonIn="", bool corruptionIn=false, const std::string &strDebugMessageIn="")
bool HasTxLockRequest(const uint256 &txHash)
std::string GetDebugMessage() const
int64_t GetBlockTime() const
std::string GetArg(const std::string &strArg, const std::string &strDefault)
bool ContextualCheckTransaction(const CTransaction &tx, CValidationState &state, CBlockIndex *const pindexPrev)
static const int DIP0001_PROTOCOL_VERSION
ScriptError GetScriptError() const
static const bool DEFAULT_SPENTINDEX
bool Condition(const CBlockIndex *pindex, const Consensus::Params ¶ms) const
CBlockIndex * pprev
pointer to the index of the predecessor of this block
bool DisconnectBlock(const CBlock &block, CValidationState &state, const CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
bool IsSporkActive(int nSporkID)
static const unsigned int MEMPOOL_HEIGHT
int64_t GetTime()
For unit testing.
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
static const unsigned int LOCKTIME_THRESHOLD
bool GetTransaction(const uint256 &hash, CTransaction &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow)
unsigned int nBytesPerSigOp
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
bool WriteAddressIndex(const std::vector< std::pair< CAddressIndexKey, CAmount > > &vect)
static const unsigned int DEFAULT_LEGACY_MIN_RELAY_TX_FEE
unsigned int nHeightFirst
number of used bytes in the undo file
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
static const unsigned int DATABASE_FLUSH_INTERVAL
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS
CAmount GetBlockSubsidy(int nPrevBits, int nPrevHeight, const Consensus::Params &consensusParams, bool fSuperblockPartOnly)
CBlockIndex * InsertBlockIndex(uint256 hash)
static bool DisconnectTip(CValidationState &state, const Consensus::Params &consensusParams)
uint64_t CalculateCurrentUsage()
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
const string strMessageMagic
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
bool AcceptToMemoryPoolWorker(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee, std::vector< uint256 > &vHashTxnToUncache, bool fDryRun)
void RemoveStaged(setEntries &stage)
void BuildSkip()
Build the skiplist pointer for this entry.
static const bool DEFAULT_RELAYPRIORITY
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos, VersionBitsCache &cache)
static const int32_t VERSIONBITS_NUM_BITS
int nHeight
height of the entry in the chain. The genesis block has height 0
static const int CLIENT_VERSION
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
int nBudgetPaymentsStartBlock
CCoinsModifier ModifyNewCoins(const uint256 &txid)
bool ContextualCheckBlock(const CBlock &block, CValidationState &state, CBlockIndex *const pindexPrev)
int64_t EndTime(const Consensus::Params ¶ms) const
bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector< uint256 > &hashes)
static int64_t nTimeFlush
static const bool DEFAULT_TXINDEX
bool SetPos(uint64_t nPos)
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate=true)
bool GetBlockPayee(int nBlockHeight, CScript &payee)
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot)
bool UpdateSpentIndex(const std::vector< std::pair< CSpentIndexKey, CSpentIndexValue > > &vect)
CAmount GetValueIn(const CTransaction &tx) const
std::string _(const char *psz)
ThresholdState GetStateFor(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, ThresholdConditionCache &cache) const
const struct BIP9DeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
int nHeight
at which height this transaction was included in the active block chain
void ReprocessBlocks(int nBlocks)
CConditionVariable cvBlockChange
static const unsigned int REJECT_HIGHFEE
int64_t BeginTime(const Consensus::Params ¶ms) const
bool InitBlockIndex(const CChainParams &chainparams)
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
static void InvalidChainFound(CBlockIndex *pindexNew)
const CCoins * AccessCoins(const uint256 &txid) const
std::vector< uint256 > vHave
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
static const unsigned int MAX_STANDARD_TX_SIZE
static const unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS