41 #include <boost/algorithm/string/replace.hpp>
42 #include <boost/foreach.hpp>
43 #include <boost/thread.hpp>
47 #error "PRCY cannot be compiled without assertions."
114 static void CheckBlockIndex();
124 struct CBlockIndexWorkComparator {
137 if (pa < pb)
return false;
138 if (pa > pb)
return true;
151 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
153 int nSyncStarted = 0;
155 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
158 std::vector<CBlockFileInfo> vinfoBlockFile;
159 int nLastBlockFile = 0;
167 uint32_t nBlockSequenceId = 1;
173 std::map<uint256, NodeId> mapBlockSource;
195 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
196 uint256 hashRecentRejectsChainTip;
203 int nValidatedQueuedBefore;
204 bool fValidatedHeaders;
206 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
209 int nQueuedValidatedHeaders = 0;
212 int nPreferredDownload = 0;
215 std::set<CBlockIndex*> setDirtyBlockIndex;
218 std::set<int> setDirtyFileInfo;
229 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
242 sharedSec.
Set(tx.
vin[i].encryptionKey.begin(), tx.
vin[i].encryptionKey.begin() + 33);
245 std::vector<unsigned char> commitment;
248 throw std::runtime_error(
"Commitment for coinstake not correct");
263 double dResult = 0.0;
285 if (kiHex.empty())
return false;
286 std::vector<uint256> bhs;
294 for (
int i = 0; i < bhs.size(); i++) {
296 if (againsHash.
IsNull()) {
307 if (bh == againsHash && !againsHash.
IsNull())
return false;
314 if (ancestor == bhIndex)
return true;
323 if (kiHex.empty())
return false;
324 std::vector<uint256> bhs;
332 for (
int i = 0; i < bhs.size(); i++) {
380 if (tx.
vout.size() >= 5)
return false;
382 if (len == 0)
return false;
383 const size_t MAX_VOUT = 5;
386 for (i = 0; i < tx.
vout.size(); i++) {
388 throw std::runtime_error(
"Failed to parse pedersen commitment");
390 return secp256k1_bulletproof_rangeproof_verify(
GetContext(),
GetScratch(),
GetGenerator(), &(tx.
bulletproofs[0]), len, NULL, commitments, tx.
vout.size(), 64, &
secp256k1_generator_const_h, NULL, 0);
395 if (tx.
nTxFee < 0)
return false;
400 const size_t MAX_VOUT = 5;
402 if (tx.
vin.size() > MAX_VIN) {
406 for (
size_t i = 1; i < tx.
vin.size(); i++) {
407 if (tx.
vin[i].decoys.size() != tx.
vin[0].decoys.size()) {
408 LogPrintf(
"The number of decoys not equal for all inputs, input %d has %d decoys but input 0 has only %d\n", i, tx.
vin[i].decoys.size(), tx.
vin[0].decoys.size());
412 if (tx.
vin.size() == 0) {
422 unsigned char allInPubKeys[MAX_VIN + 1][MAX_DECOYS + 1][33];
423 unsigned char allKeyImages[MAX_VIN + 1][33];
424 unsigned char allInCommitments[MAX_VIN][MAX_DECOYS + 1][33];
425 unsigned char allOutCommitments[MAX_VOUT][33];
427 unsigned char SIJ[MAX_VIN + 1][MAX_DECOYS + 1][32];
428 unsigned char LIJ[MAX_VIN + 1][MAX_DECOYS + 1][33];
429 unsigned char RIJ[MAX_VIN + 1][MAX_DECOYS + 1][33];
434 for (
size_t j = 0; j < tx.
vin.size(); j++) {
435 memcpy(allKeyImages[j], tx.
vin[j].keyImage.begin(), 33);
439 for (
size_t i = 0; i < tx.
vin.size(); i++) {
440 std::vector<COutPoint> decoysForIn;
441 decoysForIn.push_back(tx.
vin[i].prevout);
442 for (
size_t j = 0; j < tx.
vin[i].decoys.size(); j++) {
443 decoysForIn.push_back(tx.
vin[i].decoys[j]);
445 for (
size_t j = 0; j < tx.
vin[0].decoys.size() + 1; j++) {
449 LogPrintf(
"Failed to find transaction %s\n", decoysForIn[j].hash.GetHex());
453 if (!pindex) tip = pindex;
459 LogPrintf(
"%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, decoysForIn[j].hash.GetHex(), tip->
nHeight, tip->
GetBlockHash().
GetHex());
463 if (ancestor != atTheblock) {
464 LogPrintf(
"%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, decoysForIn[j].hash.GetHex(), tip->
nHeight, tip->
GetBlockHash().
GetHex());
474 memcpy(allInPubKeys[i][j], extractedPub.
begin(), 33);
475 memcpy(allInCommitments[i][j], &(txPrev.
vout[decoysForIn[j].n].commitment[0]), 33);
480 for (
size_t i = 0; i < tx.
vin[0].decoys.size() + 1; i++) {
481 std::vector<uint256> S_column = tx.
S[i];
482 for (
size_t j = 0; j < tx.
vin.size() + 1; j++) {
483 memcpy(SIJ[j][i], S_column[j].begin(), 32);
491 for (
size_t i = 0; i < tx.
vout.size(); i++) {
492 if (tx.
vout[i].commitment.empty()) {
493 LogPrintf(
"Commitment can not be null\n");
496 memcpy(allOutCommitments[i], &(tx.
vout[i].commitment[0]), 33);
498 LogPrintf(
"Failed to parse commitment\n");
504 unsigned char txFeeBlind[32];
505 memset(txFeeBlind, 0, 32);
507 throw std::runtime_error(
"Failed to computed commitment");
512 for (
size_t i = 0; i < tx.
vout.size() + 1; i++) {
513 outCptr[i] = &allOutCommitmentsPacked[i];
517 for (
size_t i = 0; i < tx.
vin.size(); i++) {
518 for (
size_t j = 0; j < tx.
vin[0].decoys.size() + 1; j++) {
523 for (
size_t j = 0; j < tx.
vin[0].decoys.size() + 1; j++) {
525 for (
size_t k = 0; k < tx.
vin.size(); k++) {
527 LogPrintf(
"Failed to parse commitment\n");
530 inCptr[k] = &allInCommitmentsPacked[k][j];
533 for (
size_t k = tx.
vin.size(); k < 2 * tx.
vin.size(); k++) {
534 inCptr[k] = &inPubKeysToCommitments[k - tx.
vin.size()][j];
539 LogPrintf(
"Failed to secp256k1_pedersen_commitment_sum\n");
543 LogPrintf(
"Failed to serialized pubkey\n");
552 for (
size_t j = 0; j < tx.
vin[0].decoys.size() + 1; j++) {
553 for (
size_t i = 0; i < tx.
vin.size() + 1; i++) {
556 memcpy(P, allInPubKeys[i][j], 33);
570 unsigned char sh[33];
572 pkij.
Set(allInPubKeys[i][j], allInPubKeys[i][j] + 33);
575 unsigned char ci[33];
576 memcpy(ci, allKeyImages[i], 33);
591 twoElements[0] = &SHP_commitment;
592 twoElements[1] = &cii_commitment;
596 throw std::runtime_error(
"failed to compute secp256k1_pedersen_commitment_sum_pos");
599 throw std::runtime_error(
"failed to serialize pedersen commitment");
603 unsigned char tempForHash[2 * (MAX_VIN + 1) * 33 + 32];
604 unsigned char* tempForHashPtr = tempForHash;
605 for (
size_t i = 0; i < tx.
vin.size() + 1; i++) {
606 memcpy(tempForHashPtr, &(LIJ[i][j][0]), 33);
607 tempForHashPtr += 33;
608 memcpy(tempForHashPtr, &(RIJ[i][j][0]), 33);
609 tempForHashPtr += 33;
614 uint256 temppi1 =
Hash(tempForHash, tempForHash + 2 * (tx.
vin.size() + 1) * 33 + 32);
625 if (!pindex)
return false;
632 for (
unsigned int i = 0; i < block.
vtx.size(); i++) {
650 size_t numUTXO = coinstake.
vout.size();
656 const CTxOut& mnOut = coinstake.
vout[numUTXO - 1];
659 LogPrintf(
"%s: Incorrect derived address for masternode rewards\n", __func__);
665 pindex->
nMoneySupply = nMoneySupplyPrev + nValueOut - nValueIn - nFees;
671 nExpectedMint += nFees;
700 struct CBlockReject {
701 unsigned char chRejectCode;
702 std::string strRejectReason;
714 maxSize =
GetArg(
"-blockspamfiltermaxsize", DEFAULT_BLOCK_SPAM_FILTER_MAX_SIZE);
715 maxAvg =
GetArg(
"-blockspamfiltermaxavg", DEFAULT_BLOCK_SPAM_FILTER_MAX_AVG);
718 bool onBlockReceived(
int nHeight) {
719 if(nHeight > 0 && maxSize && maxAvg) {
729 size_t size = points.size();
735 for(
auto point : points)
737 nBlocks += point.second;
741 double nAvgValue = (double)nBlocks / size;
744 bool banNode = (nAvgValue >= 1.5 * maxAvg && size >= maxAvg) ||
745 (nAvgValue >= maxAvg && nBlocks >= maxSize) ||
746 (nBlocks >= maxSize * 3);
751 return state.
DoS(100,
error(
"block-spam ban node for sending spam"));
758 void addPoint(
int height)
761 if(points.size() == maxSize)
763 points.erase(points.begin());
768 auto mi = points.find(height);
769 if (mi != points.end())
770 occurrence = (*mi).second;
772 points[height] = occurrence;
776 std::map<int,int> points;
793 bool fCurrentlyConnected;
801 std::vector<CBlockReject> rejects;
811 int64_t nStallingSince;
812 std::list<QueuedBlock> vBlocksInFlight;
815 bool fPreferredDownload;
817 CNodeBlocks nodeBlocks;
821 fCurrentlyConnected =
false;
824 pindexBestKnownBlock = NULL;
825 hashLastUnknownBlock.
SetNull();
826 pindexLastCommonBlock = NULL;
827 fSyncStarted =
false;
830 fPreferredDownload =
false;
835 std::map<NodeId, CNodeState> mapNodeState;
838 CNodeState* State(
NodeId pnode)
840 std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
841 if (it == mapNodeState.end())
858 void UpdatePreferredDownload(
CNode* node, CNodeState* state)
860 nPreferredDownload -= state->fPreferredDownload;
865 nPreferredDownload += state->fPreferredDownload;
868 void InitializeNode(
NodeId nodeid,
const CNode* pnode)
871 CNodeState& state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
873 state.address = pnode->
addr;
876 void FinalizeNode(
NodeId nodeid)
879 CNodeState* state = State(nodeid);
884 if (state->fSyncStarted)
887 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
891 for (
const QueuedBlock& entry : state->vBlocksInFlight)
892 mapBlocksInFlight.erase(entry.hash);
894 nPreferredDownload -= state->fPreferredDownload;
896 mapNodeState.erase(nodeid);
900 void MarkBlockAsReceived(
const uint256& hash)
902 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
903 if (itInFlight != mapBlocksInFlight.end()) {
904 CNodeState* state = State(itInFlight->second.first);
905 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
906 state->vBlocksInFlight.erase(itInFlight->second.second);
907 state->nBlocksInFlight--;
908 state->nStallingSince = 0;
909 mapBlocksInFlight.erase(itInFlight);
916 CNodeState* state = State(nodeid);
917 assert(state != NULL);
920 MarkBlockAsReceived(hash);
922 QueuedBlock newentry = {hash, pindex,
GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
923 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
924 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
925 state->nBlocksInFlight++;
926 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
930 void ProcessBlockAvailability(
NodeId nodeid)
932 CNodeState* state = State(nodeid);
933 assert(state != NULL);
935 if (!state->hashLastUnknownBlock.IsNull()) {
936 BlockMap::iterator itOld =
mapBlockIndex.find(state->hashLastUnknownBlock);
942 if (itOld !=
mapBlockIndex.end() && itOld->second->nChainWork > 0) {
943 if (state->pindexBestKnownBlock == NULL ||
944 itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
945 state->pindexBestKnownBlock = itOld->second;
946 state->hashLastUnknownBlock.SetNull();
952 void UpdateBlockAvailability(
NodeId nodeid,
const uint256& hash)
954 CNodeState* state = State(nodeid);
955 assert(state != NULL);
956 ProcessBlockAvailability(nodeid);
962 if (it !=
mapBlockIndex.end() && it->second->nChainWork > 0) {
964 if (state->pindexBestKnownBlock == NULL ||
965 it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
966 state->pindexBestKnownBlock = it->second;
969 state->hashLastUnknownBlock = hash;
983 while (pa != pb && pa && pb) {
995 void FindNextBlocksToDownload(
NodeId nodeid,
unsigned int count, std::vector<CBlockIndex*>& vBlocks,
NodeId& nodeStaller)
1000 vBlocks.reserve(vBlocks.size() + count);
1001 CNodeState* state = State(nodeid);
1002 assert(state != NULL);
1005 ProcessBlockAvailability(nodeid);
1007 if (state->pindexBestKnownBlock == NULL ||
1013 if (state->pindexLastCommonBlock == NULL) {
1016 state->pindexLastCommonBlock =
chainActive[std::min(state->pindexBestKnownBlock->nHeight,
1022 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
1023 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
1026 std::vector<CBlockIndex*> vToFetch;
1027 CBlockIndex* pindexWalk = state->pindexLastCommonBlock;
1031 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1032 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1034 while (pindexWalk->
nHeight < nMaxHeight) {
1038 int nToFetch = std::min(nMaxHeight - pindexWalk->
nHeight, std::max<int>(count - vBlocks.size(), 128));
1039 vToFetch.resize(nToFetch);
1040 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->
nHeight + nToFetch);
1041 vToFetch[nToFetch - 1] = pindexWalk;
1042 for (
unsigned int i = nToFetch - 1; i > 0; i--) {
1043 vToFetch[i - 1] = vToFetch[i]->
pprev;
1056 state->pindexLastCommonBlock = pindex;
1057 }
else if (mapBlocksInFlight.count(pindex->
GetBlockHash()) == 0) {
1059 if (pindex->
nHeight > nWindowEnd) {
1061 if (vBlocks.size() == 0 && waitingfor != nodeid) {
1063 nodeStaller = waitingfor;
1067 vBlocks.push_back(pindex);
1068 if (vBlocks.size() == count) {
1071 }
else if (waitingfor == -1) {
1073 waitingfor = mapBlocksInFlight[pindex->
GetBlockHash()].first;
1084 CNodeState* state = State(nodeid);
1088 stats.
nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
1089 stats.
nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
1090 for (
const QueuedBlock& queue : state->vBlocksInFlight) {
1099 nodeSignals.
GetHeight.connect(&GetHeight);
1108 nodeSignals.
GetHeight.disconnect(&GetHeight);
1122 if (pindex && chain.
Contains(pindex)) {
1167 void static EraseOrphanTx(
uint256 hash)
1172 for (
const CTxIn& txin : it->second.tx.vin) {
1176 itPrev->second.erase(hash);
1177 if (itPrev->second.empty())
1188 std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
1189 if (maybeErase->second.fromPeer == peer) {
1190 EraseOrphanTx(maybeErase->second.tx.GetHash());
1200 unsigned int nEvicted = 0;
1207 EraseOrphanTx(it->first);
1239 reason =
"non-final";
1248 unsigned int nMaxSize = MAX_STANDARD_TX_SIZE;
1249 if (sz >= nMaxSize) {
1263 reason =
"scriptsig-size";
1267 reason =
"scriptsig-not-pushonly";
1272 unsigned int nDataOut = 0;
1276 reason =
"scriptpubkey";
1283 reason =
"bare-multisig";
1293 reason =
"multi-op-return";
1314 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
1323 std::vector<std::vector<unsigned char> > vSolutions;
1327 if (!
Solver(prevScript, whichType, vSolutions))
1330 if (nArgsExpected < 0)
1333 if (tx.
vin[i].decoys.size() > 0) {
1343 std::vector<std::vector<unsigned char> > stack;
1350 CScript subscript(stack.back().begin(), stack.back().end());
1351 std::vector<std::vector<unsigned char> > vSolutions2;
1353 if (
Solver(subscript, whichType2, vSolutions2)) {
1355 if (tmpExpected < 0)
1357 nArgsExpected += tmpExpected;
1362 return (sigops <= MAX_P2SH_SIGOPS);
1366 if (stack.size() != (
unsigned int)nArgsExpected)
1385 if (coins->
nHeight < 0)
return 0;
1396 std::map<uint256, CTransactionLock>::iterator i =
mapTxLocks.find(nTXHash);
1398 sigs = (*i).second.CountSignatures();
1416 unsigned char S[33];
1423 unsigned char buff[33 + 32];
1427 unsigned char eI[33];
1439 twoElements[0] = &R_commitment;
1440 twoElements[1] = &eI_commitment;
1443 throw std::runtime_error(
"failed to compute secp256k1_pedersen_commitment_sum_pos");
1445 unsigned char recomputed[33];
1447 throw std::runtime_error(
"failed to serialize pedersen commitment");
1449 for (
int i = 0; i < 33; i++)
1450 if (
S[i] != recomputed[i])
return false;
1492 return IsFinalTx(tx, nBlockHeight, nBlockTime);
1500 double dPriorityDelta = 0;
1503 if (dPriorityDelta > 0 || nFeeDelta > 0)
1514 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1524 int nSpendHeight = pindexPrev->
nHeight + 1;
1526 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
1528 std::vector<COutPoint> alldecoys = tx.
vin[i].decoys;
1530 alldecoys.push_back(tx.
vin[i].prevout);
1531 for (
size_t j = 0; j < alldecoys.size(); j++) {
1540 if (nSpendHeight -
mapBlockIndex[bh]->nHeight <
Params().COINBASE_MATURITY())
return false;
1544 if (!pindexPrev) tip = pindexPrev;
1550 LogPrintf(
"%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, alldecoys[j].hash.GetHex(), tip->
nHeight, tip->
GetBlockHash().
GetHex());
1554 if (ancestor != atTheblock) {
1555 LogPrintf(
"%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, alldecoys[j].hash.GetHex(), tip->
nHeight, tip->
GetBlockHash().
GetHex());
1561 if (tx.
vin[i].decoys.size() != tx.
vin[0].decoys.size()) {
1562 LogPrintf(
"%s: Transaction does not have the same ring size for inputs\n", __func__);
1570 LogPrintf(
"%s: Failed to verify correctness of key image of staking transaction\n", __func__);
1582 if (pfMissingInputs)
1583 *pfMissingInputs =
false;
1587 return state.
DoS(100,
error(
"%s : CheckTransaction failed", __func__), REJECT_INVALID,
"bad-tx");
1591 return state.
DoS(100,
error(
"%s : coinbase as individual tx",
1592 __func__), REJECT_INVALID,
"coinbase");
1596 return state.
DoS(100,
error(
"%s : coinstake as individual tx (id=%s): %s",
1603 return state.
DoS(0,
false, REJECT_NONSTANDARD,
"non-final");
1609 error(
"AcceptToMemoryPool : nonstandard transaction: %s", reason),
1610 REJECT_NONSTANDARD, reason);
1614 return error(
"%s tx already in mempool", __func__);
1640 return state.
DoS(banscore,
error(
"AcceptToMemoryPool() : Ring Signature check for transaction %s failed", tx.
GetHash().
ToString()),
1641 REJECT_INVALID,
"bad-ring-signature");
1644 return state.
DoS(100,
error(
"AcceptToMemoryPool() : Bulletproof check for transaction %s failed", tx.
GetHash().
ToString()),
1645 REJECT_INVALID,
"bad-bulletproof");
1653 return state.
Invalid(
error(
"AcceptToMemoryPool : key image already spent %s", keyImage.
GetHex()),
1654 REJECT_DUPLICATE,
"bad-txns-inputs-spent");
1659 tx.
GetHash().
GetHex()), REJECT_INVALID,
"bad-txns-invalid-inputs");
1663 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
1666 std::vector<COutPoint> alldecoys = tx.
vin[i].decoys;
1668 alldecoys.push_back(tx.
vin[i].prevout);
1669 for (
size_t j = 0; j < alldecoys.size(); j++) {
1677 return state.
DoS(100,
error(
"%s : tried to spend invalid decoy %s in tx %s", __func__, alldecoys[j].ToString(),
1678 tx.
GetHash().
GetHex()), REJECT_INVALID,
"bad-txns-invalid-inputs");
1693 return error(
"AcceptToMemoryPool: nonstandard transaction input");
1701 unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
1702 if (nSigOps > nMaxSigOps)
1704 error(
"AcceptToMemoryPool : too many sigops %s, %d > %d",
1705 hash.
ToString(), nSigOps, nMaxSigOps),
1706 REJECT_NONSTANDARD,
"bad-txns-too-many-sigops");
1718 if (fLimitFree && nFees < txMinFee)
1719 return state.
DoS(0,
error(
"AcceptToMemoryPool : not enough fees %s, %d < %d", hash.
ToString(), nFees, txMinFee),
1720 REJECT_INSUFFICIENTFEE,
"insufficient fee");
1727 static double dFreeCount;
1728 static int64_t nLastTime;
1731 LOCK(csFreeLimiter);
1734 dFreeCount *= pow(1.0 - 1.0 / 600.0, (
double)(nNow - nLastTime));
1738 if (dFreeCount >=
GetArg(
"-limitfreerelay", 30) * 10 * 1000)
1739 return state.
DoS(0,
error(
"AcceptToMemoryPool : free transaction rejected by rate limiter"),
1740 REJECT_INSUFFICIENTFEE,
"rate limited free transaction");
1742 dFreeCount += nSize;
1750 int flags = STANDARD_SCRIPT_VERIFY_FLAGS;
1751 if (fCLTVIsActivated)
1754 return error(
"AcceptToMemoryPool: ConnectInputs failed %s", hash.
ToString());
1766 flags = MANDATORY_SCRIPT_VERIFY_FLAGS;
1767 if (fCLTVIsActivated)
1771 "AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s",
1782 for (
size_t i = 0; i < tx.
vin.size(); i++) {
1783 std::string outpoint = tx.
vin[i].prevout.hash.GetHex() + std::to_string(tx.
vin[i].prevout.n);
1789 for (
size_t j = 0; j < tx.
vin[i].decoys.size(); j++) {
1790 std::string outpoint = tx.
vin[i].decoys[j].hash.GetHex() + std::to_string(tx.
vin[i].decoys[j].n);
1806 if (pfMissingInputs)
1807 *pfMissingInputs =
false;
1812 return error(
"AcceptableInputs: CheckTransaction failed");
1816 return state.
DoS(100,
error(
"AcceptableInputs: coinbase as individual tx"),
1817 REJECT_INVALID,
"coinbase");
1833 error(
"AcceptableInputs : conflicts with existing transaction lock: %s", reason),
1834 REJECT_INVALID,
"tx-lock-conflict");
1842 for (
const auto &in : tx.
vin) {
1871 if (pfMissingInputs)
1872 *pfMissingInputs =
true;
1878 tx.
GetHash().
GetHex()), REJECT_INVALID,
"bad-txns-invalid-inputs");
1883 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
1886 std::vector<COutPoint> alldecoys = tx.
vin[i].decoys;
1888 alldecoys.push_back(tx.
vin[i].prevout);
1889 for (
size_t j = 0; j < alldecoys.size(); j++) {
1897 return state.
DoS(100,
error(
"%s : tried to spend invalid decoy %s in tx %s", __func__, alldecoys[j].ToString(),
1898 tx.
GetHash().
GetHex()), REJECT_INVALID,
"bad-txns-invalid-inputs");
1905 return state.
Invalid(
error(
"AcceptableInputs : inputs already spent"),
1906 REJECT_DUPLICATE,
"bad-txns-inputs-spent");
1923 unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
1924 if (nSigOps > nMaxSigOps)
1926 error(
"AcceptableInputs : too many sigops %s, %d > %d",
1927 hash.
ToString(), nSigOps, nMaxSigOps),
1928 REJECT_NONSTANDARD,
"bad-txns-too-many-sigops");
1943 if (fLimitFree && nFees < txMinFee)
1944 return state.
DoS(0,
error(
"AcceptableInputs : not enough fees %s, %d < %d", hash.
ToString(), nFees, txMinFee),
1945 REJECT_INSUFFICIENTFEE,
"insufficient fee");
1959 static double dFreeCount;
1960 static int64_t nLastTime;
1963 LOCK(csFreeLimiter);
1966 dFreeCount *= pow(1.0 - 1.0 / 600.0, (
double)(nNow - nLastTime));
1970 if (dFreeCount >=
GetArg(
"-limitfreerelay", 30) * 10 * 1000)
1971 return state.
DoS(0,
error(
"AcceptableInputs : free transaction rejected by rate limiter"),
1972 REJECT_INSUFFICIENTFEE,
"rate limited free transaction");
1974 dFreeCount += nSize;
1979 return error(
"AcceptableInputs: insane fees %s, %d > %d",
1987 int flags = STANDARD_SCRIPT_VERIFY_FLAGS;
1988 if (fCLTVIsActivated)
1991 return error(
"AcceptableInputs: ConnectInputs failed %s", hash.
ToString());
2026 return error(
"%s: OpenBlockFile failed", __func__);
2032 }
catch (
const std::exception& e) {
2033 return error(
"%s : Deserialize or I/O error - %s", __func__, e.what());
2085 return error(
"WriteBlockToDisk : OpenBlockFile failed");
2092 long fileOutPos = ftell(fileout.
Get());
2094 return error(
"WriteBlockToDisk : ftell failed");
2095 pos.
nPos = (
unsigned int)fileOutPos;
2108 return error(
"ReadBlockFromDisk : OpenBlockFile failed");
2113 }
catch (
const std::exception& e) {
2114 return error(
"%s : Deserialize or I/O error - %s", __func__, e.what());
2120 return error(
"ReadBlockFromDisk : Errors in block header");
2133 return error(
"ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
2141 int nShift = (nBits >> 24) & 0xff;
2144 (double)0x0000ffff / (
double)(nBits & 0x00ffffff);
2146 while (nShift < 29) {
2150 while (nShift > 29) {
2162 if (
Params().IsRegTestNet()) {
2167 int64_t nSubsidy = 0;
2170 if (nMoneySupply >=
Params().TOTAL_SUPPLY) {
2174 if (nHeight <
Params().LAST_POW_BLOCK()) {
2175 nSubsidy = 120000 * COIN;
2177 nSubsidy = 1 * COIN;
2180 if (nMoneySupply + nSubsidy >=
Params().TOTAL_SUPPLY) {
2190 if (nMasternodeCount < 1) {
2198 LogPrintf(
"Adjusting seesaw at height %d with %d masternodes (without drift: %d) at %ld\n", nHeight,nMasternodeCount, nMasternodeCount -
Params().MasternodeCountDrift(),
GetTime());
2202 if (mNodeCoins == 0) {
2204 }
else if (nHeight <=
Params().SoftFork()) {
2205 if (mNodeCoins <= (nMoneySupply * .05) && mNodeCoins > 0) {
2206 ret = blockValue * .6;
2207 }
else if (mNodeCoins <= (nMoneySupply * .1) && mNodeCoins > (nMoneySupply * .05)) {
2208 ret = blockValue * .59;
2209 }
else if (mNodeCoins <= (nMoneySupply * .15) && mNodeCoins > (nMoneySupply * .1)) {
2210 ret = blockValue * .58;
2211 }
else if (mNodeCoins <= (nMoneySupply * .2) && mNodeCoins > (nMoneySupply * .15)) {
2212 ret = blockValue * .57;
2213 }
else if (mNodeCoins <= (nMoneySupply * .25) && mNodeCoins > (nMoneySupply * .2)) {
2214 ret = blockValue * .56;
2215 }
else if (mNodeCoins <= (nMoneySupply * .3) && mNodeCoins > (nMoneySupply * .25)) {
2216 ret = blockValue * .55;
2217 }
else if (mNodeCoins <= (nMoneySupply * .35) && mNodeCoins > (nMoneySupply * .3)) {
2218 ret = blockValue * .54;
2219 }
else if (mNodeCoins <= (nMoneySupply * .4) && mNodeCoins > (nMoneySupply * .35)) {
2220 ret = blockValue * .53;
2221 }
else if (mNodeCoins <= (nMoneySupply * .45) && mNodeCoins > (nMoneySupply * .4)) {
2222 ret = blockValue * .52;
2223 }
else if (mNodeCoins <= (nMoneySupply * .5) && mNodeCoins > (nMoneySupply * .45)) {
2224 ret = blockValue * .51;
2225 }
else if (mNodeCoins <= (nMoneySupply * .525) && mNodeCoins > (nMoneySupply * .5)) {
2226 ret = blockValue * .50;
2227 }
else if (mNodeCoins <= (nMoneySupply * .55) && mNodeCoins > (nMoneySupply * .525)) {
2228 ret = blockValue * .49;
2229 }
else if (mNodeCoins <= (nMoneySupply * .6) && mNodeCoins > (nMoneySupply * .55)) {
2230 ret = blockValue * .48;
2231 }
else if (mNodeCoins <= (nMoneySupply * .65) && mNodeCoins > (nMoneySupply * .6)) {
2232 ret = blockValue * .47;
2233 }
else if (mNodeCoins <= (nMoneySupply * .7) && mNodeCoins > (nMoneySupply * .65)) {
2234 ret = blockValue * .46;
2235 }
else if (mNodeCoins <= (nMoneySupply * .75) && mNodeCoins > (nMoneySupply * .7)) {
2236 ret = blockValue * .45;
2237 }
else if (mNodeCoins <= (nMoneySupply * .8) && mNodeCoins > (nMoneySupply * .75)) {
2238 ret = blockValue * .44;
2239 }
else if (mNodeCoins <= (nMoneySupply * .85) && mNodeCoins > (nMoneySupply * .8)) {
2240 ret = blockValue * .43;
2241 }
else if (mNodeCoins <= (nMoneySupply * .9) && mNodeCoins > (nMoneySupply * .85)) {
2242 ret = blockValue * .42;
2243 }
else if (mNodeCoins <= (nMoneySupply * .95) && mNodeCoins > (nMoneySupply * .9)) {
2244 ret = blockValue * .41;
2246 ret = blockValue * .40;
2248 }
else if (nHeight >
Params().SoftFork()) {
2249 if (mNodeCoins <= (nMoneySupply * .01) && mNodeCoins > 0) {
2250 ret = blockValue * .6;
2251 }
else if (mNodeCoins <= (nMoneySupply * .02) && mNodeCoins > (nMoneySupply * .01)) {
2252 ret = blockValue * .598;
2253 }
else if (mNodeCoins <= (nMoneySupply * .03) && mNodeCoins > (nMoneySupply * .02)) {
2254 ret = blockValue * .596;
2255 }
else if (mNodeCoins <= (nMoneySupply * .04) && mNodeCoins > (nMoneySupply * .03)) {
2256 ret = blockValue * .594;
2257 }
else if (mNodeCoins <= (nMoneySupply * .05) && mNodeCoins > (nMoneySupply * .04)) {
2258 ret = blockValue * .592;
2259 }
else if (mNodeCoins <= (nMoneySupply * .06) && mNodeCoins > (nMoneySupply * .05)) {
2260 ret = blockValue * .59;
2261 }
else if (mNodeCoins <= (nMoneySupply * .07) && mNodeCoins > (nMoneySupply * .06)) {
2262 ret = blockValue * .588;
2263 }
else if (mNodeCoins <= (nMoneySupply * .08) && mNodeCoins > (nMoneySupply * .07)) {
2264 ret = blockValue * .586;
2265 }
else if (mNodeCoins <= (nMoneySupply * .09) && mNodeCoins > (nMoneySupply * .08)) {
2266 ret = blockValue * .584;
2267 }
else if (mNodeCoins <= (nMoneySupply * .1) && mNodeCoins > (nMoneySupply * .09)) {
2268 ret = blockValue * .582;
2269 }
else if (mNodeCoins <= (nMoneySupply * .11) && mNodeCoins > (nMoneySupply * .1)) {
2270 ret = blockValue * .58;
2271 }
else if (mNodeCoins <= (nMoneySupply * .12) && mNodeCoins > (nMoneySupply * .11)) {
2272 ret = blockValue * .578;
2273 }
else if (mNodeCoins <= (nMoneySupply * .13) && mNodeCoins > (nMoneySupply * .12)) {
2274 ret = blockValue * .576;
2275 }
else if (mNodeCoins <= (nMoneySupply * .14) && mNodeCoins > (nMoneySupply * .13)) {
2276 ret = blockValue * .574;
2277 }
else if (mNodeCoins <= (nMoneySupply * .15) && mNodeCoins > (nMoneySupply * .14)) {
2278 ret = blockValue * .572;
2279 }
else if (mNodeCoins <= (nMoneySupply * .16) && mNodeCoins > (nMoneySupply * .15)) {
2280 ret = blockValue * .57;
2281 }
else if (mNodeCoins <= (nMoneySupply * .17) && mNodeCoins > (nMoneySupply * .16)) {
2282 ret = blockValue * .568;
2283 }
else if (mNodeCoins <= (nMoneySupply * .18) && mNodeCoins > (nMoneySupply * .17)) {
2284 ret = blockValue * .566;
2285 }
else if (mNodeCoins <= (nMoneySupply * .19) && mNodeCoins > (nMoneySupply * .18)) {
2286 ret = blockValue * .564;
2287 }
else if (mNodeCoins <= (nMoneySupply * .20) && mNodeCoins > (nMoneySupply * .19)) {
2288 ret = blockValue * .562;
2289 }
else if (mNodeCoins <= (nMoneySupply * .21) && mNodeCoins > (nMoneySupply * .20)) {
2290 ret = blockValue * .56;
2291 }
else if (mNodeCoins <= (nMoneySupply * .22) && mNodeCoins > (nMoneySupply * .21)) {
2292 ret = blockValue * .558;
2293 }
else if (mNodeCoins <= (nMoneySupply * .23) && mNodeCoins > (nMoneySupply * .22)) {
2294 ret = blockValue * .556;
2295 }
else if (mNodeCoins <= (nMoneySupply * .24) && mNodeCoins > (nMoneySupply * .23)) {
2296 ret = blockValue * .554;
2297 }
else if (mNodeCoins <= (nMoneySupply * .25) && mNodeCoins > (nMoneySupply * .24)) {
2298 ret = blockValue * .552;
2299 }
else if (mNodeCoins <= (nMoneySupply * .26) && mNodeCoins > (nMoneySupply * .25)) {
2300 ret = blockValue * .55;
2301 }
else if (mNodeCoins <= (nMoneySupply * .27) && mNodeCoins > (nMoneySupply * .26)) {
2302 ret = blockValue * .548;
2303 }
else if (mNodeCoins <= (nMoneySupply * .28) && mNodeCoins > (nMoneySupply * .27)) {
2304 ret = blockValue * .546;
2305 }
else if (mNodeCoins <= (nMoneySupply * .29) && mNodeCoins > (nMoneySupply * .28)) {
2306 ret = blockValue * .544;
2307 }
else if (mNodeCoins <= (nMoneySupply * .30) && mNodeCoins > (nMoneySupply * .29)) {
2308 ret = blockValue * .542;
2309 }
else if (mNodeCoins <= (nMoneySupply * .31) && mNodeCoins > (nMoneySupply * .30)) {
2310 ret = blockValue * .54;
2311 }
else if (mNodeCoins <= (nMoneySupply * .32) && mNodeCoins > (nMoneySupply * .31)) {
2312 ret = blockValue * .538;
2313 }
else if (mNodeCoins <= (nMoneySupply * .33) && mNodeCoins > (nMoneySupply * .32)) {
2314 ret = blockValue * .536;
2315 }
else if (mNodeCoins <= (nMoneySupply * .34) && mNodeCoins > (nMoneySupply * .33)) {
2316 ret = blockValue * .534;
2317 }
else if (mNodeCoins <= (nMoneySupply * .35) && mNodeCoins > (nMoneySupply * .34)) {
2318 ret = blockValue * .532;
2319 }
else if (mNodeCoins <= (nMoneySupply * .36) && mNodeCoins > (nMoneySupply * .35)) {
2320 ret = blockValue * .53;
2321 }
else if (mNodeCoins <= (nMoneySupply * .37) && mNodeCoins > (nMoneySupply * .36)) {
2322 ret = blockValue * .528;
2323 }
else if (mNodeCoins <= (nMoneySupply * .38) && mNodeCoins > (nMoneySupply * .37)) {
2324 ret = blockValue * .526;
2325 }
else if (mNodeCoins <= (nMoneySupply * .39) && mNodeCoins > (nMoneySupply * .38)) {
2326 ret = blockValue * .524;
2327 }
else if (mNodeCoins <= (nMoneySupply * .40) && mNodeCoins > (nMoneySupply * .39)) {
2328 ret = blockValue * .522;
2329 }
else if (mNodeCoins <= (nMoneySupply * .41) && mNodeCoins > (nMoneySupply * .40)) {
2330 ret = blockValue * .52;
2331 }
else if (mNodeCoins <= (nMoneySupply * .42) && mNodeCoins > (nMoneySupply * .41)) {
2332 ret = blockValue * .518;
2333 }
else if (mNodeCoins <= (nMoneySupply * .43) && mNodeCoins > (nMoneySupply * .42)) {
2334 ret = blockValue * .516;
2335 }
else if (mNodeCoins <= (nMoneySupply * .44) && mNodeCoins > (nMoneySupply * .43)) {
2336 ret = blockValue * .514;
2337 }
else if (mNodeCoins <= (nMoneySupply * .45) && mNodeCoins > (nMoneySupply * .44)) {
2338 ret = blockValue * .512;
2339 }
else if (mNodeCoins <= (nMoneySupply * .46) && mNodeCoins > (nMoneySupply * .45)) {
2340 ret = blockValue * .51;
2341 }
else if (mNodeCoins <= (nMoneySupply * .47) && mNodeCoins > (nMoneySupply * .46)) {
2342 ret = blockValue * .508;
2343 }
else if (mNodeCoins <= (nMoneySupply * .48) && mNodeCoins > (nMoneySupply * .47)) {
2344 ret = blockValue * .506;
2345 }
else if (mNodeCoins <= (nMoneySupply * .49) && mNodeCoins > (nMoneySupply * .48)) {
2346 ret = blockValue * .504;
2347 }
else if (mNodeCoins <= (nMoneySupply * .50) && mNodeCoins > (nMoneySupply * .49)) {
2348 ret = blockValue * .502;
2349 }
else if (mNodeCoins <= (nMoneySupply * .51) && mNodeCoins > (nMoneySupply * .5)) {
2350 ret = blockValue * .50;
2351 }
else if (mNodeCoins <= (nMoneySupply * .52) && mNodeCoins > (nMoneySupply * .51)) {
2352 ret = blockValue * .498;
2353 }
else if (mNodeCoins <= (nMoneySupply * .53) && mNodeCoins > (nMoneySupply * .52)) {
2354 ret = blockValue * .496;
2355 }
else if (mNodeCoins <= (nMoneySupply * .54) && mNodeCoins > (nMoneySupply * .53)) {
2356 ret = blockValue * .494;
2357 }
else if (mNodeCoins <= (nMoneySupply * .55) && mNodeCoins > (nMoneySupply * .54)) {
2358 ret = blockValue * .492;
2359 }
else if (mNodeCoins <= (nMoneySupply * .56) && mNodeCoins > (nMoneySupply * .55)) {
2360 ret = blockValue * .49;
2361 }
else if (mNodeCoins <= (nMoneySupply * .57) && mNodeCoins > (nMoneySupply * .56)) {
2362 ret = blockValue * .488;
2363 }
else if (mNodeCoins <= (nMoneySupply * .58) && mNodeCoins > (nMoneySupply * .57)) {
2364 ret = blockValue * .486;
2365 }
else if (mNodeCoins <= (nMoneySupply * .59) && mNodeCoins > (nMoneySupply * .58)) {
2366 ret = blockValue * .484;
2367 }
else if (mNodeCoins <= (nMoneySupply * .60) && mNodeCoins > (nMoneySupply * .59)) {
2368 ret = blockValue * .482;
2369 }
else if (mNodeCoins <= (nMoneySupply * .61) && mNodeCoins > (nMoneySupply * .60)) {
2370 ret = blockValue * .48;
2371 }
else if (mNodeCoins <= (nMoneySupply * .62) && mNodeCoins > (nMoneySupply * .61)) {
2372 ret = blockValue * .478;
2373 }
else if (mNodeCoins <= (nMoneySupply * .63) && mNodeCoins > (nMoneySupply * .62)) {
2374 ret = blockValue * .476;
2375 }
else if (mNodeCoins <= (nMoneySupply * .64) && mNodeCoins > (nMoneySupply * .63)) {
2376 ret = blockValue * .474;
2377 }
else if (mNodeCoins <= (nMoneySupply * .65) && mNodeCoins > (nMoneySupply * .64)) {
2378 ret = blockValue * .472;
2379 }
else if (mNodeCoins <= (nMoneySupply * .66) && mNodeCoins > (nMoneySupply * .65)) {
2380 ret = blockValue * .47;
2381 }
else if (mNodeCoins <= (nMoneySupply * .67) && mNodeCoins > (nMoneySupply * .66)) {
2382 ret = blockValue * .468;
2383 }
else if (mNodeCoins <= (nMoneySupply * .68) && mNodeCoins > (nMoneySupply * .67)) {
2384 ret = blockValue * .466;
2385 }
else if (mNodeCoins <= (nMoneySupply * .69) && mNodeCoins > (nMoneySupply * .68)) {
2386 ret = blockValue * .464;
2387 }
else if (mNodeCoins <= (nMoneySupply * .70) && mNodeCoins > (nMoneySupply * .69)) {
2388 ret = blockValue * .462;
2389 }
else if (mNodeCoins <= (nMoneySupply * .71) && mNodeCoins > (nMoneySupply * .7)) {
2390 ret = blockValue * .46;
2391 }
else if (mNodeCoins <= (nMoneySupply * .72) && mNodeCoins > (nMoneySupply * .71)) {
2392 ret = blockValue * .458;
2393 }
else if (mNodeCoins <= (nMoneySupply * .73) && mNodeCoins > (nMoneySupply * .72)) {
2394 ret = blockValue * .456;
2395 }
else if (mNodeCoins <= (nMoneySupply * .74) && mNodeCoins > (nMoneySupply * .73)) {
2396 ret = blockValue * .454;
2397 }
else if (mNodeCoins <= (nMoneySupply * .75) && mNodeCoins > (nMoneySupply * .74)) {
2398 ret = blockValue * .452;
2399 }
else if (mNodeCoins <= (nMoneySupply * .76) && mNodeCoins > (nMoneySupply * .75)) {
2400 ret = blockValue * .45;
2401 }
else if (mNodeCoins <= (nMoneySupply * .77) && mNodeCoins > (nMoneySupply * .76)) {
2402 ret = blockValue * .448;
2403 }
else if (mNodeCoins <= (nMoneySupply * .78) && mNodeCoins > (nMoneySupply * .77)) {
2404 ret = blockValue * .446;
2405 }
else if (mNodeCoins <= (nMoneySupply * .79) && mNodeCoins > (nMoneySupply * .78)) {
2406 ret = blockValue * .444;
2407 }
else if (mNodeCoins <= (nMoneySupply * .80) && mNodeCoins > (nMoneySupply * .79)) {
2408 ret = blockValue * .442;
2409 }
else if (mNodeCoins <= (nMoneySupply * .81) && mNodeCoins > (nMoneySupply * .8)) {
2410 ret = blockValue * .44;
2411 }
else if (mNodeCoins <= (nMoneySupply * .82) && mNodeCoins > (nMoneySupply * .81)) {
2412 ret = blockValue * .438;
2413 }
else if (mNodeCoins <= (nMoneySupply * .83) && mNodeCoins > (nMoneySupply * .82)) {
2414 ret = blockValue * .436;
2415 }
else if (mNodeCoins <= (nMoneySupply * .84) && mNodeCoins > (nMoneySupply * .83)) {
2416 ret = blockValue * .434;
2417 }
else if (mNodeCoins <= (nMoneySupply * .85) && mNodeCoins > (nMoneySupply * .84)) {
2418 ret = blockValue * .432;
2419 }
else if (mNodeCoins <= (nMoneySupply * .86) && mNodeCoins > (nMoneySupply * .85)) {
2420 ret = blockValue * .43;
2421 }
else if (mNodeCoins <= (nMoneySupply * .87) && mNodeCoins > (nMoneySupply * .86)) {
2422 ret = blockValue * .428;
2423 }
else if (mNodeCoins <= (nMoneySupply * .88) && mNodeCoins > (nMoneySupply * .87)) {
2424 ret = blockValue * .426;
2425 }
else if (mNodeCoins <= (nMoneySupply * .89) && mNodeCoins > (nMoneySupply * .88)) {
2426 ret = blockValue * .424;
2427 }
else if (mNodeCoins <= (nMoneySupply * .90) && mNodeCoins > (nMoneySupply * .89)) {
2428 ret = blockValue * .422;
2429 }
else if (mNodeCoins <= (nMoneySupply * .91) && mNodeCoins > (nMoneySupply * .90)) {
2430 ret = blockValue * .42;
2431 }
else if (mNodeCoins <= (nMoneySupply * .92) && mNodeCoins > (nMoneySupply * .91)) {
2432 ret = blockValue * .418;
2433 }
else if (mNodeCoins <= (nMoneySupply * .93) && mNodeCoins > (nMoneySupply * .92)) {
2434 ret = blockValue * .416;
2435 }
else if (mNodeCoins <= (nMoneySupply * .94) && mNodeCoins > (nMoneySupply * .93)) {
2436 ret = blockValue * .414;
2437 }
else if (mNodeCoins <= (nMoneySupply * .95) && mNodeCoins > (nMoneySupply * .94)) {
2438 ret = blockValue * .412;
2439 }
else if (mNodeCoins <= (nMoneySupply * .96) && mNodeCoins > (nMoneySupply * .95)) {
2440 ret = blockValue * .41;
2441 }
else if (mNodeCoins <= (nMoneySupply * .97) && mNodeCoins > (nMoneySupply * .96)) {
2442 ret = blockValue * .408;
2443 }
else if (mNodeCoins <= (nMoneySupply * .98) && mNodeCoins > (nMoneySupply * .97)) {
2444 ret = blockValue * .404;
2445 }
else if (mNodeCoins <= (nMoneySupply * .99) && mNodeCoins > (nMoneySupply * .98)) {
2446 ret = blockValue * .402;
2448 ret = blockValue * .40;
2457 int64_t blockValueForSeeSaw = blockValue;
2459 if (nHeight >=
Params().LAST_POW_BLOCK()) {
2460 return GetSeeSaw(blockValueForSeeSaw, nMasternodeCount, nHeight);
2479 if (nHeight >=
Params().HardForkRingSize()) {
2486 if (nHeight >=
Params().HardForkRingSize()) {
2490 if (nHeight >=
Params().HardForkRingSize2()) {
2506 static bool lockIBDState =
false;
2512 lockIBDState =
true;
2520 static void AlertNotify(
const std::string& strMessage,
bool fThread)
2523 std::string strCmd =
GetArg(
"-alertnotify",
"");
2524 if (strCmd.empty())
return;
2529 std::string singleQuote(
"'");
2531 safeStatus = singleQuote+safeStatus+singleQuote;
2532 boost::replace_all(strCmd,
"%s", safeStatus);
2542 if (out.
nValue == 0)
return true;
2543 unsigned char zeroBlind[32];
2544 std::vector<unsigned char> commitment;
2551 CPubKey addressGenPub, pubView, pubSpend;
2555 LogPrintf(
"%s: Cannot decode foundational address\n", __func__);
2564 if (foundationTxPub != origin)
return false;
2588 std::string warning = std::string(
"'Warning: Large-work fork detected, forking after block ") +
2590 AlertNotify(warning,
true);
2596 "CheckForkWarningConditions: 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",
2603 "CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
2618 while (pfork && pfork != plonger) {
2620 plonger = plonger->
pprev;
2621 if (pfork == plonger)
2623 pfork = pfork->
pprev;
2650 CNodeState* state = State(pnode);
2657 state->nMisbehavior += howmuch;
2658 int banscore =
GetArg(
"-banscore", 100);
2659 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) {
2660 LogPrintf(
"Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior - howmuch,
2661 state->nMisbehavior);
2662 state->fShouldBan =
true;
2664 LogPrintf(
"Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior);
2667 void static InvalidChainFound(
CBlockIndex* pindexNew)
2669 if (!pindexBestInvalid || pindexNew->
nChainWork > pindexBestInvalid->nChainWork)
2670 pindexBestInvalid = pindexNew;
2672 LogPrintf(
"InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
2677 LogPrintf(
"InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
2687 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->
GetBlockHash());
2688 if (it != mapBlockSource.end() && State(it->second)) {
2691 State(it->second)->rejects.push_back(reject);
2700 setDirtyBlockIndex.insert(pindex);
2701 setBlockIndexCandidates.erase(pindex);
2702 InvalidChainFound(pindex);
2753 bool fSpent =
false;
2760 nValue += coins->
vout[out.
n].nValue;
2770 pvChecks->reserve(tx.
vin.size());
2780 int nSpendHeight = pindexPrev->
nHeight + 1;
2782 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
2788 error(
"CheckInputs() : Inputs not available"),
2789 REJECT_INVALID,
"bad-txns");
2796 error(
"CheckInputs() : tried to spend coinbase at depth %d, coinstake=%d",
2798 REJECT_INVALID,
"bad-txns-premature-spend-of-coinbase");
2812 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
2818 error(
"CheckInputs() : Inputs not available"),
2819 REJECT_INVALID,
"bad-txns");
2827 check.
swap(pvChecks->back());
2828 }
else if (!check()) {
2829 if (
flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
2837 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
2839 return state.
Invalid(
false, REJECT_NONSTANDARD,
2840 strprintf(
"non-mandatory-script-verify-flag (%s)",
2860 static bool AbortNode(
const std::string& strMessage,
const std::string& userMessage=
"")
2865 userMessage.empty() ?
_(
"Error: A fatal internal error occured, see debug.log for details") : userMessage,
2871 static bool AbortNode(
CValidationState& state,
const std::string& strMessage,
const std::string& userMessage=
"")
2873 AbortNode(strMessage, userMessage);
2874 return state.
Error(strMessage);
2891 return error(
"DisconnectBlock() : no undo data available");
2893 return error(
"DisconnectBlock() : failure reading undo data");
2895 if (blockUndo.
vtxundo.size() + 1 != block.
vtx.size())
2896 return error(
"DisconnectBlock() : block and undo data inconsistent");
2899 for (
int i = block.
vtx.size() - 1; i >= 0; i--) {
2919 if (*outs != outsBlock)
2920 fClean = fClean &&
error(
"DisconnectBlock() : added transaction mismatch? database corrupted");
2931 "DisconnectBlock() : transaction and undo data inconsistent - txundo.vprevout.siz=%d tx.vin.siz=%d",
2933 for (
unsigned int j = tx.
vin.size(); j-- > 0;) {
2940 fClean = fClean &&
error(
"DisconnectBlock() : undo data overwriting existing transaction");
2947 fClean = fClean &&
error(
"DisconnectBlock() : undo data adding output to missing transaction");
2950 fClean = fClean &&
error(
"DisconnectBlock() : undo data overwriting existing output");
2951 if (coins->
vout.size() < out.
n + 1)
2952 coins->
vout.resize(out.
n + 1);
2969 void static FlushBlockFile(
bool fFinalize =
false)
2971 LOCK(cs_LastBlockFile);
2978 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2986 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2999 scriptcheckqueue.Thread();
3005 if (nHeightStart > chainHeight)
3013 if (pindex->
nHeight % 1000 == 0) {
3015 int percent = std::max(1, std::min(99, (
int)((
double)((pindex->
nHeight - nHeightStart) * 100) / (chainHeight - nHeightStart))));
3027 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
3036 throw std::runtime_error(
"Commitment for coinstake not correct: failed to verify blind commitment");
3044 sharedSec.
Set(tx.
vin[i].encryptionKey.begin(), tx.
vin[i].encryptionKey.begin() + 33);
3047 std::vector<unsigned char> commitment;
3050 throw std::runtime_error(
"Commitment for coinstake not correct");
3057 for (
unsigned int i = 0; i < tx.
vout.size(); i++) {
3061 nValueOut += tx.
vout[i].nValue;
3066 pindex->
nMoneySupply = nSupplyPrev + nValueOut - nValueIn - nFees;
3071 if (pindex->
nHeight < chainHeight)
3079 static int64_t nTimeVerify = 0;
3080 static int64_t nTimeConnect = 0;
3081 static int64_t nTimeIndex = 0;
3082 static int64_t nTimeCallbacks = 0;
3083 static int64_t nTimeTotal = 0;
3089 if (!fAlreadyChecked && !
CheckBlock(block, state, !fJustCheck, !fJustCheck))
3094 return state.
Invalid(
error(
"ConnectBlock(): Time elapsed between two PoA blocks is too short"),
3095 REJECT_INVALID,
"time-too-new");
3099 return state.
Invalid(
error(
"ConnectBlock(): PoA block auditing PoS blocks previously audited by its parent"),
3100 REJECT_INVALID,
"overlap-audit");
3109 return state.
DoS(100,
error(
"ConnectBlock(): PoA block should contain only non-audited recent PoS blocks"),
3110 REJECT_INVALID,
"blocks-already-audited");
3114 return state.
DoS(100,
error(
"ConnectBlock(): A PoA block should audit at least 59 PoS blocks and no more than 120 PoS blocks (65 max after block 169869)"),
3115 REJECT_INVALID,
"incorrect-number-audited-blocks");
3119 return state.
DoS(100,
error(
"ConnectBlock(): A PoA block should not audit any existing PoA blocks"),
3120 REJECT_INVALID,
"auditing-poa-block");
3124 return state.
DoS(100,
error(
"ConnectBlock(): This PoA block reward does not match the value it should"),
3125 REJECT_INVALID,
"incorrect-reward");
3129 return state.
DoS(100,
error(
"ConnectBlock(): This PoA block does not have the correct padding"),
3130 REJECT_INVALID,
"incorrect-padding");
3134 return state.
DoS(100,
error(
"ConnectBlock(): A PoA block should not be in the future"),
3135 REJECT_INVALID,
"time-in-future");
3142 LogPrintf(
"%s: hashPrev=%s view=%s\n", __func__, hashPrevBlock.
ToString().c_str(),
3151 int nHeight = pindex->
nHeight;
3153 return state.
DoS(100,
error(
"ConnectBlock() : PoS period not active"),
3154 REJECT_INVALID,
"PoS-early");
3157 return state.
DoS(100,
error(
"ConnectBlock() : PoW period ended"),
3158 REJECT_INVALID,
"PoW-ended");
3163 bool fCLTVIsActivated =
false;
3164 if (fScriptChecks && pindex->
pprev) {
3173 unsigned int nSigOps = 0;
3175 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
3176 vPos.reserve(block.
vtx.size());
3178 blockundo.
vtxundo.reserve(block.
vtx.size() - 1);
3181 unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_CURRENT;
3182 for (
unsigned int i = 0; i < block.
vtx.size(); i++) {
3184 nInputs += tx.
vin.size();
3187 return state.
DoS(100,
error(
"ConnectBlock() : too many sigops"),
3188 REJECT_INVALID,
"bad-blk-sigops");
3194 return state.
DoS(100,
error(
"ConnectBlock() : Ring Signature check for transaction %s failed", tx.
GetHash().
ToString()),
3195 REJECT_INVALID,
"bad-ring-signature");
3197 return state.
DoS(100,
error(
"ConnectBlock() : Bulletproof check for transaction %s failed", tx.
GetHash().
ToString()),
3198 REJECT_INVALID,
"bad-bulletproof");
3206 std::string kh = keyImage.
GetHex();
3209 return state.
Invalid(
error(
"ConnectBlock() : key image already spent"),
3210 REJECT_DUPLICATE,
"bad-txns-inputs-spent");
3221 tx.
GetHash().
GetHex()), REJECT_INVALID,
"bad-txns-invalid-inputs");
3225 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
3228 std::vector<COutPoint> alldecoys = tx.
vin[i].decoys;
3230 alldecoys.push_back(tx.
vin[i].prevout);
3231 for (
size_t j = 0; j < alldecoys.size(); j++) {
3239 return state.
DoS(100,
error(
"%s : tried to spend invalid decoy %s in tx %s", __func__, alldecoys[j].ToString(),
3240 tx.
GetHash().
GetHex()), REJECT_INVALID,
"bad-txns-invalid-inputs");
3246 return state.
Invalid(
error(
"ConnectBlock() : Fee below Minimum. Network spam detected."),
3247 REJECT_INVALID,
"bad-txns-low-fee");
3251 nValueIn += valTemp;
3253 std::vector<CScriptCheck> vChecks;
3255 if (fCLTVIsActivated)
3258 bool fCacheResults = fJustCheck;
3261 control.
Add(vChecks);
3267 blockundo.
vtxundo.emplace_back();
3271 vPos.emplace_back(tx.
GetHash(), pos);
3278 size_t numUTXO = coinstake.
vout.size();
3283 const CTxOut& mnOut = coinstake.
vout[numUTXO - 1];
3286 return state.
DoS(100,
error(
"ConnectBlock() : Incorrect derived address for masternode rewards"));
3288 if (nHeight >=
Params().HardFork() && nValueIn < minStakingAmount)
3289 return state.
DoS(100,
error(
"ConnectBlock() : amount (%d) not allowed for staking. Min amount: %d",
3290 __func__, nValueIn, minStakingAmount), REJECT_INVALID,
"bad-txns-stake");
3292 if (coinstake.
vin.size() > 1 && nHeight >
Params().FixChecks())
3293 return state.
DoS(100,
error(
"%s : multiple stake inputs not allowed", __func__), REJECT_INVALID,
"bad-txns-stake");
3298 pindex->
nMoneySupply = nMoneySupplyPrev + nValueOut - nValueIn - nFees;
3303 nTimeConnect += nTime1 - nTimeStart;
3304 LogPrint(
BCLog::BENCH,
" - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n",
3305 (
unsigned)block.
vtx.size(), 0.001 * (nTime1 - nTimeStart),
3306 0.001 * (nTime1 - nTimeStart) / block.
vtx.size(),
3307 nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs - 1), nTimeConnect * 0.000001);
3311 nExpectedMint += nFees;
3315 return state.
DoS(100,
error(
"ConnectBlock() : reward pays too much (actual=%s vs limit=%s)",
3319 if (!control.
Wait())
3320 return state.
DoS(100,
error(
"%s: CheckQueue failed", __func__), REJECT_INVALID,
"block-validation-failed");
3322 nTimeVerify += nTime2 - nTimeStart;
3324 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs - 1),
3325 nTimeVerify * 0.000001);
3336 return error(
"ConnectBlock() : FindUndoPos failed");
3338 return AbortNode(state,
"Failed to write undo data");
3346 setDirtyBlockIndex.insert(pindex);
3351 return AbortNode(state,
"Failed to write transaction index");
3357 nTimeIndex += nTime3 - nTime2;
3358 LogPrint(
BCLog::BENCH,
" - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
3361 static uint256 hashPrevBestCoinBase;
3363 hashPrevBestCoinBase = block.
vtx[0].GetHash();
3366 nTimeCallbacks += nTime4 - nTime3;
3367 LogPrint(
BCLog::BENCH,
" - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
3386 static int64_t nLastWrite = 0;
3387 static int64_t nLastFlush = 0;
3388 static int64_t nLastSetChain = 0;
3392 if (nLastWrite == 0) {
3395 if (nLastFlush == 0) {
3398 if (nLastSetChain == 0) {
3399 nLastSetChain = nNow;
3407 bool fPeriodicWrite = mode ==
FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
3409 bool fPeriodicFlush = mode ==
FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
3411 bool fDoFullFlush = (mode ==
FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush;
3413 if (fDoFullFlush || fPeriodicWrite) {
3416 return state.
Error(
"out of disk space");
3421 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
3422 vFiles.reserve(setDirtyFileInfo.size());
3423 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
3424 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
3425 setDirtyFileInfo.erase(it++);
3427 std::vector<const CBlockIndex*> vBlocks;
3428 vBlocks.reserve(setDirtyBlockIndex.size());
3429 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
3430 vBlocks.push_back(*it);
3431 setDirtyBlockIndex.erase(it++);
3435 return AbortNode(state,
"Files to write to block index database");
3449 return state.
Error(
"out of disk space");
3452 return AbortNode(state,
"Failed to write to coin database");
3458 nLastSetChain = nNow;
3461 }
catch (
const std::runtime_error& e) {
3462 return AbortNode(state, std::string(
"System error while flushing: ") + e.what());
3489 LogPrintf(
"UpdateTip: new best=%s height=%d version=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n",
3495 static bool fWarned =
false;
3499 for (
int i = 0; i < 100 && pindex != NULL; i++) {
3502 pindex = pindex->
pprev;
3506 if (nUpgraded > 100 / 2) {
3508 strMiscWarning =
_(
"Warning: This version is obsolete, upgrade required!");
3519 assert(pindexDelete);
3524 return AbortNode(state,
"Failed to read block");
3531 assert(view.Flush());
3540 std::list<CTransaction> removed;
3548 UpdateTip(pindexDelete->
pprev);
3558 static int64_t nTimeReadFromDisk = 0;
3559 static int64_t nTimeConnectTotal = 0;
3560 static int64_t nTimeFlush = 0;
3561 static int64_t nTimeChainState = 0;
3562 static int64_t nTimePostConnect = 0;
3575 fAlreadyChecked =
false;
3582 return AbortNode(state,
"Failed to read block");
3587 nTimeReadFromDisk += nTime2 - nTime1;
3590 nTimeReadFromDisk * 0.000001);
3593 bool rv =
ConnectBlock(*pblock, state, pindexNew, view,
false, fAlreadyChecked);
3597 InvalidBlockFound(pindexNew, state);
3600 mapBlockSource.erase(inv.
hash);
3602 nTimeConnectTotal += nTime3 - nTime2;
3604 nTimeConnectTotal * 0.000001);
3605 assert(view.Flush());
3608 nTimeFlush += nTime4 - nTime3;
3609 LogPrint(
BCLog::BENCH,
" - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
3618 nTimeChainState += nTime5 - nTime4;
3620 nTimeChainState * 0.000001);
3623 std::list<CTransaction> txConflicted;
3627 UpdateTip(pindexNew);
3639 nTimePostConnect += nTime6 - nTime5;
3640 nTimeTotal += nTime6 - nTime1;
3642 nTimePostConnect * 0.000001);
3643 LogPrint(
BCLog::BENCH,
"- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
3653 LogPrintf(
"%s: Got command to replay %d blocks\n", __func__, nBlocks);
3654 for (
int i = 0; i <= nBlocks; i++)
3655 DisconnectTip(state);
3665 if ((*it).second >
GetTime() - (nBlocks *
Params().TargetSpacing() * 2)) {
3671 LogPrintf(
"%s - %s\n", __func__, (*it).first.ToString());
3695 std::vector<CTransaction> tobeRemoveds;
3696 for (std::map<uint256, CTxMemPoolEntry>::const_iterator it =
mempool.
mapTx.begin(); it !=
mempool.
mapTx.end(); ++it) {
3698 for(
size_t i = 0; i < tx.
vin.size(); i++) {
3699 std::string kiHex = tx.
vin[i].keyImage.GetHex();
3702 if (confirm >
Params().MaxReorganizationDepth()) {
3703 tobeRemoveds.push_back(tx);
3707 bool needsBreak =
false;
3708 std::vector<COutPoint> decoys = tx.
vin[i].decoys;
3709 decoys.push_back(tx.
vin[i].prevout);
3710 for (
size_t j = 0; j < decoys.size(); j++) {
3714 tobeRemoveds.push_back(tx);
3721 tobeRemoveds.push_back(tx);
3727 tobeRemoveds.push_back(tx);
3733 if (needsBreak)
break;
3736 std::list<CTransaction> removed;
3737 for(
size_t i = 0; i < tobeRemoveds.size(); i++) {
3753 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
3754 if (it == setBlockIndexCandidates.rend())
3762 bool fInvalidAncestor =
false;
3772 if (fFailedChain || fMissingData) {
3775 (pindexBestInvalid == NULL || pindexNew->
nChainWork > pindexBestInvalid->nChainWork))
3776 pindexBestInvalid = pindexNew;
3779 while (pindexTest != pindexFailed) {
3782 }
else if (fMissingData) {
3786 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->
pprev, pindexFailed));
3788 setBlockIndexCandidates.erase(pindexFailed);
3789 pindexFailed = pindexFailed->
pprev;
3791 setBlockIndexCandidates.erase(pindexTest);
3792 fInvalidAncestor =
true;
3795 pindexTest = pindexTest->
pprev;
3797 if (!fInvalidAncestor)
3803 static void PruneBlockIndexCandidates()
3807 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3808 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it,
chainActive.
Tip())) {
3809 setBlockIndexCandidates.erase(it++);
3812 assert(!setBlockIndexCandidates.empty());
3824 fAlreadyChecked =
false;
3825 bool fInvalidFound =
false;
3831 if (!DisconnectTip(state))
3836 std::vector<CBlockIndex*> vpindexToConnect;
3837 bool fContinue =
true;
3838 int nHeight = pindexFork ? pindexFork->
nHeight : -1;
3839 while (fContinue && nHeight != pindexMostWork->
nHeight) {
3842 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->
nHeight);
3843 vpindexToConnect.clear();
3844 vpindexToConnect.reserve(nTargetHeight - nHeight);
3846 while (pindexIter && pindexIter->
nHeight != nHeight) {
3847 vpindexToConnect.push_back(pindexIter);
3848 pindexIter = pindexIter->
pprev;
3850 nHeight = nTargetHeight;
3853 BOOST_REVERSE_FOREACH (
CBlockIndex* pindexConnect, vpindexToConnect) {
3854 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL, fAlreadyChecked)) {
3858 InvalidChainFound(vpindexToConnect.back());
3860 fInvalidFound =
true;
3868 PruneBlockIndexCandidates();
3903 boost::this_thread::interruption_point();
3906 bool fInitialDownload;
3914 pindexMostWork = FindMostWorkChain();
3916 if (pindexMostWork == NULL || pindexMostWork ==
chainActive.
Tip())
3918 if (!ActivateBestChainStep(state, pindexMostWork,
3931 if (pindexFork != pindexNewTip) {
3937 if (!fInitialDownload) {
3978 setDirtyBlockIndex.insert(pindex);
3979 setBlockIndexCandidates.erase(pindex);
3984 setDirtyBlockIndex.insert(pindexWalk);
3985 setBlockIndexCandidates.erase(pindexWalk);
3988 if (!DisconnectTip(state)) {
3998 !setBlockIndexCandidates.value_comp()(it->second,
chainActive.
Tip())) {
3999 setBlockIndexCandidates.insert(it->second);
4004 InvalidChainFound(pindex);
4012 int nHeight = pindex->
nHeight;
4017 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
4019 setDirtyBlockIndex.insert(it->second);
4021 setBlockIndexCandidates.value_comp()(
chainActive.
Tip(), it->second)) {
4022 setBlockIndexCandidates.insert(it->second);
4024 if (it->second == pindexBestInvalid) {
4026 pindexBestInvalid = NULL;
4033 while (pindex != NULL) {
4036 setDirtyBlockIndex.insert(pindex);
4038 pindex = pindex->
pprev;
4058 BlockMap::iterator mi =
mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
4063 pindexNew->
pprev = (*miPrev).second;
4075 LogPrintf(
"AddToBlockIndex() : SetStakeEntropyBit() failed \n");
4080 LogPrintf(
"AddToBlockIndex() : hashProofOfStake not found in map \n");
4085 uint64_t nStakeModifier = 0;
4086 bool fGeneratedStakeModifier =
false;
4088 LogPrintf(
"AddToBlockIndex() : ComputeNextStakeModifier() failed \n");
4092 LogPrintf(
"AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=%s \n",
4093 pindexNew->
nHeight, std::to_string(nStakeModifier));
4104 setDirtyBlockIndex.insert(pindexNew);
4114 pindexNew->
nTx = block.
vtx.size();
4121 setDirtyBlockIndex.insert(pindexNew);
4125 std::deque<CBlockIndex*> queue;
4126 queue.push_back(pindexNew);
4129 while (!queue.empty()) {
4134 LOCK(cs_nBlockSequenceId);
4138 setBlockIndexCandidates.insert(pindex);
4140 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(
4142 while (range.first != range.second) {
4143 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
4144 queue.push_back(it->second);
4146 mapBlocksUnlinked.erase(it);
4151 mapBlocksUnlinked.insert(std::make_pair(pindexNew->
pprev, pindexNew));
4160 LOCK(cs_LastBlockFile);
4162 unsigned int nFile = fKnown ? pos.
nFile : nLastBlockFile;
4163 if (vinfoBlockFile.size() <= nFile) {
4164 vinfoBlockFile.resize(nFile + 1);
4168 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
4169 LogPrintf(
"Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
4170 FlushBlockFile(
true);
4172 if (vinfoBlockFile.size() <= nFile) {
4173 vinfoBlockFile.resize(nFile + 1);
4177 pos.
nPos = vinfoBlockFile[nFile].nSize;
4180 nLastBlockFile = nFile;
4181 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
4183 vinfoBlockFile[nFile].nSize = std::max(pos.
nPos + nAddSize, vinfoBlockFile[nFile].nSize);
4185 vinfoBlockFile[nFile].nSize += nAddSize;
4188 unsigned int nOldChunks = (pos.
nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
4189 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
4190 if (nNewChunks > nOldChunks) {
4194 LogPrintf(
"Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE,
4200 return state.
Error(
"out of disk space");
4204 setDirtyFileInfo.insert(nFile);
4212 LOCK(cs_LastBlockFile);
4214 unsigned int nNewSize;
4215 pos.
nPos = vinfoBlockFile[nFile].nUndoSize;
4216 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
4217 setDirtyFileInfo.insert(nFile);
4219 unsigned int nOldChunks = (pos.
nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
4220 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
4221 if (nNewChunks > nOldChunks) {
4225 LogPrintf(
"Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE,
4231 return state.
Error(
"out of disk space");
4241 return state.
DoS(50,
error(
"CheckBlockHeader() : proof of work failed"),
4242 REJECT_INVALID,
"high-hash");
4244 if (
Params().IsRegTestNet())
return true;
4249 return state.
DoS(50,
error(
"CheckBlockHeader() : proof of work PoA failed"),
4250 REJECT_INVALID,
"high-hash");
4255 return state.
DoS(50,
error(
"CheckBlockHeader() : Previous PoA block hash is not matched => failed"),
4256 REJECT_INVALID,
"high-hash");
4271 return state.
DoS(100,
error(
"CheckBlock() : CheckBlockHeader failed"),
4272 REJECT_INVALID,
"bad-header",
true);
4278 return state.
Invalid(
error(
"CheckBlock() : block timestamp too far in the future"),
4279 REJECT_INVALID,
"time-too-new");
4282 std::set<CKeyImage> keyimages;
4283 for(
size_t i = 0; i < block.
vtx.size(); i++) {
4284 for (
const CTxIn& txin : block.
vtx[i].vin) {
4286 if (keyimages.count(txin.
keyImage)) {
4287 return state.
DoS(100,
error(
"CheckBlock() : duplicate inputs"),
4288 REJECT_INVALID,
"bad-txns-inputs-duplicate");
4295 if (fCheckMerkleRoot) {
4299 return state.
DoS(100,
error(
"CheckBlock() : hashMerkleRoot mismatch"),
4300 REJECT_INVALID,
"bad-txnmrklroot",
true);
4306 return state.
DoS(100,
error(
"CheckBlock() : duplicate transaction"),
4307 REJECT_INVALID,
"bad-txns-duplicate",
true);
4314 return state.
DoS(100,
error(
"CheckBlock() : hashPoAMerkleRoot mismatch"),
4315 REJECT_INVALID,
"bad-txnmrklroot",
true);
4321 return state.
DoS(100,
error(
"CheckBlock() : duplicate PoS block info"),
4322 REJECT_INVALID,
"bad-txns-duplicate",
true);
4330 unsigned int nMaxBlockSize = MAX_BLOCK_SIZE_CURRENT;
4331 if (block.
vtx.empty() || block.
vtx.size() > nMaxBlockSize ||
4333 return state.
DoS(100,
error(
"CheckBlock() : size limits failed"),
4334 REJECT_INVALID,
"bad-blk-length");
4338 return state.
DoS(100,
error(
"CheckBlock() : first tx is not coinbase"),
4339 REJECT_INVALID,
"bad-cb-missing");
4340 for (
unsigned int i = 1; i < block.
vtx.size(); i++)
4341 if (block.
vtx[i].IsCoinBase())
4342 return state.
DoS(100,
error(
"CheckBlock() : more than one coinbase"),
4343 REJECT_INVALID,
"bad-cb-multiple");
4347 if (block.
vtx[0].vout.size() != 1 || !block.
vtx[0].vout[0].IsEmpty())
4348 return state.
DoS(100,
error(
"CheckBlock() : coinbase output not empty for proof-of-stake block"));
4350 if (block.
vtx.empty() || !block.
vtx[1].IsCoinStake())
4351 return state.
DoS(100,
error(
"CheckBlock() : second tx is not coinstake"));
4352 for (
unsigned int i = 2; i < block.
vtx.size(); i++)
4353 if (block.
vtx[i].IsCoinStake())
4354 return state.
DoS(100,
error(
"CheckBlock() : more than one coinstake"));
4357 int numUTXO = coinstake.
vout.size();
4361 return state.
DoS(100,
error(
"CheckBlock() : Failed to verify shnorr signature"));
4365 for (
int i = 1; i < numUTXO; i++) {
4367 return state.
DoS(100,
error(
"CheckBlock() : PoS rewards commitment not correct"));
4370 std::set<COutPoint> vInOutPoints;
4371 for (
const CTxIn& txin : block.
vtx[1].vin) {
4373 return state.
DoS(100,
error(
"CheckBlock() : duplicate inputs"),
4374 REJECT_INVALID,
"bad-txns-inputs-duplicate");
4375 vInOutPoints.insert(txin.
prevout);
4379 return state.
DoS(100,
error(
"%s : multiple stake inputs not allowed", __func__), REJECT_INVALID,
"bad-txns-stake");
4385 return state.
DoS(100,
error(
"CheckBlock() : PoS rewards commitment not correct"));
4393 return state.
DoS(100,
error(
"CheckBlock() : PoA block should only start at block height=%d",
Params().START_POA_BLOCK()));
4400 if (pindexPrev != NULL) {
4402 nHeight = pindexPrev->
nHeight + 1;
4406 nHeight = (*mi).second->nHeight + 1;
4418 return state.
DoS(0,
error(
"CheckBlock() : Couldn't find masternode/budget payment"),
4419 REJECT_INVALID,
"bad-cb-payee");
4426 unsigned int nSigOps = 0;
4430 unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_LEGACY;
4431 if (nSigOps > nMaxBlockSigOps)
4432 return state.
DoS(100,
error(
"ConnectBlock() : too many sigops"), REJECT_INVALID,
"bad-blk-sigops");
4439 if (pindexPrev == NULL)
4440 return error(
"%s : null pindexPrev for block %s", __func__, block.
GetHash().
ToString().c_str());
4446 if (std::abs(n1 - n2) > n1 * 0.5)
4447 return error(
"%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, std::abs(n1 - n2), n1, n2, pindexPrev->
nHeight + 1);
4452 if (block.
nBits != nBitsRequired)
4453 return error(
"%s : incorrect proof of work at %d", __func__, pindexPrev->
nHeight + 1);
4462 if (hash ==
Params().HashGenesisBlock())
4467 const int nHeight = pindexPrev->
nHeight + 1;
4471 return state.
DoS(100,
error(
"%s : incorrect proof of work", __func__),
4472 REJECT_INVALID,
"bad-diffbits");
4476 int nMaxReorgDepth =
GetArg(
"-maxreorg",
Params().MaxReorganizationDepth());
4477 if (chainHeight - nHeight >= nMaxReorgDepth)
4478 return state.
DoS(1,
error(
"%s: forked chain older than max reorganization depth (height %d)", __func__, chainHeight - nHeight));
4483 return state.
Invalid(
error(
"%s : block's timestamp is too early", __func__),
4484 REJECT_INVALID,
"time-too-old");
4489 return state.
DoS(100,
error(
"%s : rejected by checkpoint lock-in at %d", __func__, nHeight),
4490 REJECT_CHECKPOINT,
"checkpoint mismatch");
4494 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
4495 return state.
DoS(0,
error(
"%s : forked chain older than last checkpoint (height %d)", __func__, nHeight));
4500 return state.
Invalid(
error(
"%s : rejected nVersion=1 block", __func__),
4501 REJECT_OBSOLETE,
"bad-version");
4506 return state.
Invalid(
error(
"%s : rejected nVersion=2 block", __func__),
4507 REJECT_OBSOLETE,
"bad-version");
4512 return state.
Invalid(
error(
"%s : rejected nVersion=4 block", __func__),
4513 REJECT_OBSOLETE,
"bad-version");
4547 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->
nHeight + 1;
4552 return state.
DoS(10,
error(
"%s : contains a non-final transaction", __func__), REJECT_INVALID,
4553 "bad-txns-nonfinal");
4561 if (block.
vtx[0].vin[0].scriptSig.size() <
expect.size() ||
4562 !std::equal(
expect.begin(),
expect.end(), block.
vtx[0].vin[0].scriptSig.begin())) {
4563 return state.
DoS(100,
error(
"%s : block height mismatch in coinbase", __func__), REJECT_INVALID,
4581 pindex = miSelf->second;
4586 return state.
Invalid(
error(
"%s : block is not found", __func__), 0,
"not-found");
4589 return state.
Invalid(
error(
"%s : block is marked invalid", __func__), 0,
"duplicate");
4593 LogPrintf(
"AcceptBlockHeader(): CheckBlockHeader failed \n");
4598 if (hash !=
Params().HashGenesisBlock()) {
4603 pindexPrev = (*mi).second;
4617 return state.
DoS(100,
4618 error(
"%s : prev block height=%d hash=%s is invalid, unable to add block %s", __func__,
4620 REJECT_INVALID,
"bad-prevblk");
4650 pindexPrev = (*mi).second;
4664 REJECT_INVALID,
"bad-prevblk");
4675 std::unique_ptr<CStakeInput> stake;
4678 return state.
DoS(100,
error(
"%s: proof of stake check failed", __func__));
4681 return error(
"%s: null stake ptr", __func__);
4700 setDirtyBlockIndex.insert(pindex);
4705 int nHeight = pindex->
nHeight;
4706 int splitHeight = -1;
4713 bool isBlockFromFork = pindexPrev !=
nullptr &&
chainActive.
Tip() != pindexPrev;
4719 if (stakeTxIn.
vin.size() > 1 && nHeight >
Params().FixChecks())
4720 return state.
DoS(100,
error(
"%s : multiple stake inputs not allowed", __func__), REJECT_INVALID,
"bad-txns-stake");
4723 std::vector<CTxIn> prcyInputs;
4725 for (
const CTxIn& stakeIn : stakeTxIn.
vin) {
4726 prcyInputs.push_back(stakeIn);
4728 const bool hasPRCYInputs = !prcyInputs.empty();
4735 for (
const CTxIn& prcyIn : prcyInputs){
4738 return error(
"%s: double spent coinstake input: %s, KeyImage: %s inside block: %s", __func__, prcyIn.prevout.hash.GetHex(), prcyIn.keyImage.GetHex(), block.
GetHash().
GetHex());
4745 if (isBlockFromFork) {
4755 if(readBlock ==
Params().MaxReorganizationDepth()){
4757 return error(
"%s: forked chain longer than maximum reorg limit", __func__);
4769 for (
const CTxIn& stakeIn : prcyInputs) {
4790 for (
const CTxIn& in: stakeTxIn.
vin) {
4793 if(!coin && !isBlockFromFork){
4795 return error(
"%s: coin stake inputs not available on main chain, received height %d vs current %d", __func__, nHeight,
chainActive.
Height());
4800 if(!(isBlockFromFork && coin->
nHeight > splitHeight)){
4802 return error(
"%s: coin stake inputs already spent in main chain", __func__);
4816 return error(
"AcceptBlock() : FindBlockPos failed");
4819 return AbortNode(state,
"Failed to write block");
4821 return error(
"AcceptBlock() : ReceivedBlockTransactions failed");
4822 }
catch (
const std::runtime_error& e) {
4823 return AbortNode(state, std::string(
"System error: ") + e.what());
4832 unsigned int nFound = 0;
4833 for (
unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) {
4834 if (pstart->
nVersion >= minVersion)
4836 pstart = pstart->
pprev;
4838 return (nFound >= nRequired);
4842 int static inline InvertLowestOne(
int n) {
return n & (n - 1); }
4845 int static inline GetSkipHeight(
int height)
4853 return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
4858 if (height >
nHeight || height < 0)
4863 while (heightWalk > height) {
4864 int heightSkip = GetSkipHeight(heightWalk);
4865 int heightSkipPrev = GetSkipHeight(heightWalk - 1);
4866 if (heightSkip == height ||
4867 (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) {
4869 pindexWalk = pindexWalk->
pskip;
4870 heightWalk = heightSkip;
4872 pindexWalk = pindexWalk->
pprev;
4899 return error(
"ProcessNewBlock() : bad proof-of-stake block signature");
4901 if (pblock->
GetHash() !=
Params().HashGenesisBlock() && pfrom != NULL) {
4919 MarkBlockAsReceived(pblock->
GetHash());
4921 return error(
"%s : CheckBlock FAILED for block %s", __func__, pblock->
GetHash().
GetHex());
4926 bool ret =
AcceptBlock(*pblock, state, &pindex, dbp, checked);
4927 if (pindex && pfrom) {
4944 if (!initialDownloadCheck &&
4955 if(pindex && pfrom &&
GetBoolArg(
"-blockspamfilter", DEFAULT_BLOCK_SPAM_FILTER)) {
4956 CNodeState *nodestate = State(pfrom->
GetId());
4957 if(nodestate !=
nullptr) {
4958 nodestate->nodeBlocks.onBlockReceived(pindex->
nHeight);
4959 bool nodeStatus =
true;
4961 nodeStatus = nodestate->nodeBlocks.updateState(state, nodeStatus);
4969 return error(
"%s : AcceptBlock FAILED - block spam protection", __func__);
4972 return error(
"%s : AcceptBlock FAILED", __func__);
4977 return error(
"%s : ActivateBestChain failed", __func__);
5003 int userTxStartIdx = 1;
5004 int coinbaseIdx = 0;
5023 if ((
int)pblock->
vtx.size() > userTxStartIdx) {
5024 for (
int i = userTxStartIdx; i < (int)pblock->
vtx.size(); i++) {
5025 for (
int j = 0; j < (int)pblock->
vtx[i].vout.size(); j++) {
5055 if (
b.posBlocksAudited.size() == 0) {
5056 for (
int i = 0; i < (int)coinbase.
vout.size(); i++) {
5057 if (!coinbase.
vout[i].IsNull() && !coinbase.
vout[i].commitment.empty() && coinbase.
vout[i].nValue > 0 && !coinbase.
vout[i].IsEmpty()) {
5082 LogPrintf(
"%s: ACCEPTED in %ld milliseconds with size=%d, height=%d\n", __func__,
GetTimeMillis() - nStartTime,
5093 LogPrintf(
"%s : No longer working on chain tip\n", __func__);
5099 indexDummy.
pprev = pindexPrev;
5105 if (!
CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
5109 if (!
ConnectBlock(block, state, &indexDummy, viewNew,
true))
5118 uint64_t nFreeBytesAvailable = fs::space(
GetDataDir()).available;
5121 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
5122 return AbortNode(
"Disk space is low!",
_(
"Error: Disk space is low!"));
5132 fs::create_directories(path.parent_path());
5134 if (!file && !fReadOnly)
5137 LogPrintf(
"Unable to open file %s\n", path.string());
5141 if (fseek(file, pos.
nPos, SEEK_SET)) {
5142 LogPrintf(
"Unable to seek to position %u of %s\n", pos.
nPos, path.string());
5173 return (*mi).second;
5178 throw std::runtime_error(
"LoadBlockIndex() : new CBlockIndex failed");
5179 mi =
mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
5186 bool static LoadBlockIndexDB(std::string& strError)
5191 boost::this_thread::interruption_point();
5194 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
5196 for (
const std::pair<const uint256, CBlockIndex*>& item :
mapBlockIndex) {
5198 vSortedByHeight.push_back(std::make_pair(pindex->
nHeight, pindex));
5200 std::sort(vSortedByHeight.begin(), vSortedByHeight.end());
5208 if (pindex->
pprev) {
5213 mapBlocksUnlinked.insert(std::make_pair(pindex->
pprev, pindex));
5220 setBlockIndexCandidates.insert(pindex);
5222 (!pindexBestInvalid || pindex->
nChainWork > pindexBestInvalid->nChainWork))
5223 pindexBestInvalid = pindex;
5233 vinfoBlockFile.resize(nLastBlockFile + 1);
5234 LogPrintf(
"%s: last block file = %i\n", __func__, nLastBlockFile);
5235 for (
int nFile = 0; nFile <= nLastBlockFile; nFile++) {
5238 LogPrintf(
"%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
5239 for (
int nFile = nLastBlockFile + 1;
true; nFile++) {
5242 vinfoBlockFile.push_back(info);
5249 LogPrintf(
"Checking all blk files are present...\n");
5250 std::set<int> setBlkDataFiles;
5251 for (
const std::pair<const uint256, CBlockIndex*>& item :
mapBlockIndex) {
5254 setBlkDataFiles.insert(pindex->
nFile);
5257 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
5265 bool fLastShutdownWasPrepared =
true;
5267 LogPrintf(
"%s: Last shutdown was prepared: %s\n", __func__, fLastShutdownWasPrepared);
5270 bool fReindexing =
false;
5276 LogPrintf(
"LoadBlockIndexDB(): transaction index %s\n",
fTxIndex ?
"enabled" :
"disabled");
5287 PruneBlockIndexCandidates();
5290 LogPrintf(
"LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
5316 if (nCheckDepth <= 0)
5317 nCheckDepth = 1000000000;
5318 if (nCheckDepth > chainHeight)
5319 nCheckDepth = chainHeight;
5320 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
5321 LogPrintf(
"Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
5325 int nGoodTransactions = 0;
5328 boost::this_thread::interruption_point();
5329 uiInterface.
ShowProgress(
_(
"Verifying blocks..."), std::max(1, std::min(99, (
int)(((
double)(chainHeight - pindex->
nHeight)) / (
double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
5330 if (pindex->
nHeight < chainHeight - nCheckDepth)
5337 if (nCheckLevel >= 1 && !
CheckBlock(block, state))
5340 if (nCheckLevel >= 2 && pindex) {
5353 pindexState = pindex->
pprev;
5355 nGoodTransactions = 0;
5356 pindexFailure = pindex;
5358 nGoodTransactions += block.
vtx.size();
5364 return error(
"VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainHeight - pindexFailure->
nHeight + 1, nGoodTransactions);
5367 if (nCheckLevel >= 4) {
5370 boost::this_thread::interruption_point();
5371 uiInterface.
ShowProgress(
_(
"Verifying blocks..."), std::max(1, std::min(99, 100 - (
int)(((
double)(chainHeight - pindex->
nHeight)) / (
double)nCheckDepth * 50))));
5381 LogPrintf(
"No coin database inconsistencies in last %i blocks (%i transactions)\n", chainHeight - pindexState->
nHeight, nGoodTransactions);
5389 setBlockIndexCandidates.clear();
5391 pindexBestInvalid = NULL;
5397 mapBlocksUnlinked.clear();
5398 vinfoBlockFile.clear();
5400 nBlockSequenceId = 1;
5401 mapBlockSource.clear();
5402 mapBlocksInFlight.clear();
5403 nQueuedValidatedHeaders = 0;
5404 nPreferredDownload = 0;
5405 setDirtyBlockIndex.clear();
5406 setDirtyFileInfo.clear();
5407 mapNodeState.clear();
5408 recentRejects.reset(
nullptr);
5411 delete entry.second;
5419 if (!
fReindex && !LoadBlockIndexDB(strError))
5439 LogPrintf(
"Initializing databases...\n");
5450 return error(
"LoadBlockIndex() : FindBlockPos failed");
5452 return error(
"LoadBlockIndex() : writing genesis block to disk failed");
5455 return error(
"LoadBlockIndex() : genesis block not accepted");
5458 }
catch (
const std::runtime_error& e) {
5459 return error(
"LoadBlockIndex() : failed to initialize block database: %s", e.what());
5470 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
5476 CBufferedFile blkdat(fileIn, 2 * MAX_BLOCK_SIZE_CURRENT, MAX_BLOCK_SIZE_CURRENT + 8,
SER_DISK, CLIENT_VERSION);
5477 uint64_t nRewind = blkdat.
GetPos();
5478 while (!blkdat.
eof()) {
5479 boost::this_thread::interruption_point();
5484 unsigned int nSize = 0;
5489 nRewind = blkdat.
GetPos() + 1;
5495 if (nSize < 80 || nSize > MAX_BLOCK_SIZE_CURRENT)
5497 }
catch (
const std::exception&) {
5503 uint64_t nBlockPos = blkdat.
GetPos();
5505 dbp->
nPos = nBlockPos;
5506 blkdat.
SetLimit(nBlockPos + nSize);
5507 blkdat.
SetPos(nBlockPos);
5510 nRewind = blkdat.
GetPos();
5514 if (hash !=
Params().HashGenesisBlock() &&
5517 hash.
GetHex(), block.hashPrevBlock.GetHex());
5519 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
5530 }
else if (hash !=
Params().HashGenesisBlock() &&
mapBlockIndex[hash]->nHeight % 1000 == 0) {
5536 std::deque<uint256> queue;
5537 queue.push_back(hash);
5538 while (!queue.empty()) {
5541 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(
5543 while (range.first != range.second) {
5544 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
5546 LogPrintf(
"%s: Processing out of order child %s of %s\n", __func__,
5547 block.GetHash().ToString(),
5552 queue.push_back(block.GetHash());
5556 mapBlocksUnknownParent.erase(it);
5559 }
catch (
const std::exception& e) {
5560 LogPrintf(
"%s : Deserialize or I/O error - %s\n", __func__, e.what());
5563 }
catch (
const std::runtime_error& e) {
5564 AbortNode(std::string(
"System error: ") + e.what());
5571 void static CheckBlockIndex()
5588 std::multimap<CBlockIndex*, CBlockIndex*> forward;
5590 forward.insert(std::make_pair(it->second->pprev, it->second));
5595 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(
5598 rangeGenesis.first++;
5599 assert(rangeGenesis.first == rangeGenesis.second);
5611 while (pindex != NULL) {
5615 if (pindex->
pprev != NULL && pindexFirstNotTreeValid == NULL &&
5617 pindexFirstNotTreeValid = pindex;
5618 if (pindex->
pprev != NULL && pindexFirstNotChainValid == NULL &&
5620 pindexFirstNotChainValid = pindex;
5621 if (pindex->
pprev != NULL && pindexFirstNotScriptsValid == NULL &&
5623 pindexFirstNotScriptsValid = pindex;
5626 if (pindex->
pprev == NULL) {
5638 assert((pindexFirstMissing != NULL) == (pindex->
nChainTx ==
5646 assert(pindexFirstNotTreeValid ==
5649 assert(pindexFirstNotTreeValid == NULL);
5651 assert(pindexFirstNotChainValid == NULL);
5653 assert(pindexFirstNotScriptsValid == NULL);
5654 if (pindexFirstInvalid == NULL) {
5659 if (!CBlockIndexWorkComparator()(pindex,
chainActive.
Tip()) && pindexFirstMissing == NULL) {
5660 if (pindexFirstInvalid ==
5662 assert(setBlockIndexCandidates.count(pindex));
5665 assert(setBlockIndexCandidates.count(pindex) == 0);
5668 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(
5670 bool foundInUnlinked =
false;
5671 while (rangeUnlinked.first != rangeUnlinked.second) {
5672 assert(rangeUnlinked.first->first == pindex->
pprev);
5673 if (rangeUnlinked.first->second == pindex) {
5674 foundInUnlinked =
true;
5677 rangeUnlinked.first++;
5680 if (pindexFirstInvalid ==
5682 assert(foundInUnlinked);
5685 assert(!foundInUnlinked);
5691 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = forward.equal_range(
5693 if (range.first != range.second) {
5695 pindex = range.first->second;
5704 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
5705 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
5706 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
5707 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
5708 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
5712 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangePar = forward.equal_range(
5714 while (rangePar.first->second != pindex) {
5715 assert(rangePar.first !=
5721 if (rangePar.first != rangePar.second) {
5723 pindex = rangePar.first->second;
5735 assert(nNodes == forward.size());
5741 std::string strStatusBar;
5746 "This is a pre-release test build - use at your own risk - do not use for staking or merchant applications!");
5749 strStatusBar = strRPC =
"testsafemode enabled";
5757 strStatusBar = strRPC =
_(
5758 "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
5760 strStatusBar = strRPC =
_(
5761 "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
5764 if (strFor ==
"statusbar")
5765 return strStatusBar;
5766 else if (strFor ==
"rpc")
5768 assert(!
"GetWarnings() : invalid parameter");
5779 bool static AlreadyHave(
const CInv& inv)
5783 assert(recentRejects);
5790 recentRejects->reset();
5793 return recentRejects->contains(inv.
hash) ||
5848 void static ProcessGetData(
CNode* pfrom)
5852 std::deque<CInv>::iterator it = pfrom->
vRecvGetData.begin();
5853 std::vector<CInv> vNotFound;
5862 const CInv& inv = *it;
5864 boost::this_thread::interruption_point();
5880 std::string remoteAddr;
5885 "ProcessGetData(): ignoring request from peer=%i%s for old block that is not in the main chain\n",
5886 pfrom->
GetId(), remoteAddr);
5895 assert(!
"cannot load block from disk");
5910 typedef std::pair<unsigned int, uint256> PairType;
5911 for (PairType& pair : merkleBlock.vMatchedTxn)
5923 std::vector<CInv> vInv;
5931 bool pushed =
false;
5934 std::map<CInv, CDataStream>::iterator mi =
mapRelay.find(inv);
6039 vNotFound.push_back(inv);
6053 if (!vNotFound.empty()) {
6065 bool static ProcessMessage(
CNode* pfrom, std::string strCommand,
CDataStream& vRecv, int64_t nTimeReceived)
6069 LogPrintf(
"dropmessagestest DROPPING RECV MESSAGE\n");
6090 uint64_t nNonce = 1;
6091 uint64_t nServiceInt;
6092 vRecv >> pfrom->
nVersion >> nServiceInt >> nTime >> addrMe;
6114 vRecv >> addrFrom >> nNonce;
6115 if (!vRecv.
empty()) {
6134 if (pfrom->
fInbound && addrMe.IsRoutable()) {
6147 UpdatePreferredDownload(pfrom, State(pfrom->
GetId()));
6176 std::string remoteAddr;
6180 LogPrintf(
"receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
6185 int64_t nTimeOffset = nTime -
GetTime();
6199 State(pfrom->
GetId())->fCurrentlyConnected =
true;
6202 std::vector<CAddress> vAddr;
6208 if (vAddr.size() > 1000) {
6211 return error(
"message addr size() = %u", vAddr.size());
6215 std::vector<CAddress> vAddrOk;
6217 int64_t nSince = nNow - 10 * 60;
6219 boost::this_thread::interruption_point();
6221 if ((addr.
nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
6224 if (addr.
nTime <= 100000000 || addr.
nTime > nNow + 10 * 60)
6225 addr.
nTime = nNow - 5 * 24 * 60 * 60;
6237 uint64_t hashAddr = addr.
GetHash();
6238 uint256 hashRand = hashSalt ^ (hashAddr << 32) ^ ((
GetTime() + hashAddr) / (24 * 60 * 60));
6240 std::multimap<uint256, CNode*> mapMix;
6242 if (pnode->
nVersion < CADDR_TIME_VERSION)
6244 unsigned int nPointer;
6245 memcpy(&nPointer, &pnode,
sizeof(nPointer));
6246 uint256 hashKey = hashRand ^ nPointer;
6248 mapMix.insert(std::make_pair(hashKey, pnode));
6250 int nRelayNodes = fReachable ? 2 : 1;
6252 for (std::multimap<uint256, CNode*>::iterator mi = mapMix.begin();
6253 mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
6254 ((*mi).second)->PushAddress(addr, insecure_rand);
6259 vAddrOk.push_back(addr);
6262 if (vAddr.size() < 1000)
6267 std::vector<CInv> vInv;
6269 if (vInv.size() > MAX_INV_SZ) {
6272 return error(
"message inv size() = %u", vInv.size());
6276 unsigned int nLastBlock = (
unsigned int)(-1);
6277 for (
unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
6278 if (vInv[vInv.size() - 1 - nInv].type ==
MSG_BLOCK) {
6279 nLastBlock = vInv.size() - 1 - nInv;
6286 std::vector<CInv> vToFetch;
6287 for (
unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
6288 const CInv& inv = vInv[nInv];
6290 boost::this_thread::interruption_point();
6293 bool fAlreadyHave = AlreadyHave(inv);
6294 LogPrint(
BCLog::NET,
"got inv: %s %s peer=%d, inv.type=%d, mapBlocksInFlight.count(inv.hash)=%d\n", inv.
ToString(), fAlreadyHave ?
"have" :
"new", pfrom->
id, inv.
type, mapBlocksInFlight.count(inv.
hash));
6296 if (!fAlreadyHave && pfrom)
6299 UpdateBlockAvailability(pfrom->
GetId(), inv.
hash);
6302 vToFetch.push_back(inv);
6306 }
else if (nInv == nLastBlock) {
6310 std::vector<CInv> vGetData(1,inv);
6326 if (!vToFetch.empty())
6329 std::vector<CInv> vInv;
6331 if (vInv.size() > MAX_INV_SZ) {
6334 return error(
"message getdata size() = %u", vInv.size());
6337 if ((vInv.size() != 1))
6340 if (vInv.size() > 0)
6344 ProcessGetData(pfrom);
6348 vRecv >> locator >> hashStop;
6350 if (locator.
vHave.size() > MAX_LOCATOR_SZ) {
6366 hashStop.IsNull() ?
"end" : hashStop.ToString(), nLimit, pfrom->
id);
6373 if (--nLimit <= 0) {
6385 vRecv >> locator >> hashStop;
6387 if (locator.
vHave.size() > MAX_LOCATOR_SZ) {
6404 pindex = (*mi).second;
6413 std::vector<CBlock> vHeaders;
6414 int nLimit = MAX_HEADERS_RESULTS;
6415 LogPrintf(
"getheaders %d to %s from peer=%d\n", (pindex ? pindex->
nHeight : -1), hashStop.ToString(), pfrom->
id);
6418 if (--nLimit <= 0 || pindex->
GetBlockHash() == hashStop)
6423 std::vector<uint256> vWorkQueue;
6424 std::vector<uint256> vEraseQueue;
6428 bool ignoreFees =
false;
6430 std::vector<unsigned char> vchSig;
6439 bool fMissingInputs =
false;
6447 vWorkQueue.push_back(inv.
hash);
6451 tx.GetHash().ToString(),
6455 std::set<NodeId> setMisbehaving;
6456 for (
unsigned int i = 0; i < vWorkQueue.size(); i++) {
6460 for(std::set<uint256>::iterator mi = itByPrev->second.begin();
6461 mi != itByPrev->second.end();
6463 const uint256& orphanHash = *mi;
6466 bool fMissingInputs2 =
false;
6473 if (setMisbehaving.count(fromPeer))
6478 vWorkQueue.push_back(orphanHash);
6479 vEraseQueue.push_back(orphanHash);
6480 }
else if (!fMissingInputs2) {
6482 if (stateDummy.
IsInvalid(nDos) && nDos > 0) {
6485 setMisbehaving.insert(fromPeer);
6491 vEraseQueue.push_back(orphanHash);
6492 assert(recentRejects);
6493 recentRejects->insert(orphanHash);
6499 for (
uint256 hash : vEraseQueue)
6500 EraseOrphanTx(hash);
6501 }
else if (fMissingInputs) {
6505 unsigned int nMaxOrphanTx = (
unsigned int)std::max((int64_t)0,
GetArg(
"-maxorphantx",
6506 DEFAULT_MAX_ORPHAN_TRANSACTIONS));
6515 assert(recentRejects);
6516 recentRejects->insert(tx.GetHash());
6533 tx.GetHash().ToString(),
6544 std::vector<CBlockHeader> headers;
6548 if (nCount > MAX_HEADERS_RESULTS) {
6551 return error(
"headers message size = %u", nCount);
6553 headers.resize(nCount);
6554 for (
unsigned int n = 0; n < nCount; n++) {
6555 vRecv >> headers[n];
6570 return error(
"non-continuous headers sequence");
6581 std::string strError =
"invalid header received " + header.
GetHash().
ToString();
6582 return error(strError.c_str());
6590 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
6594 LogPrintf(
"more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->
nHeight, pfrom->
id,
6637 LogPrint(
BCLog::NET,
"Added block %s to block index map\n", block.GetHash().GetHex());
6640 LogPrint(
BCLog::NET,
"%s : Already processed block %s, skipping ProcessNewBlock()\n", __func__,
6641 block.GetHash().GetHex());
6661 std::vector<uint256> vtxid;
6663 std::vector<CInv> vInv;
6668 if (!fInMemPool)
continue;
6671 vInv.push_back(inv);
6672 if (vInv.size() == MAX_INV_SZ) {
6677 if (vInv.size() > 0)
6680 if (pfrom->
nVersion > BIP0031_VERSION) {
6697 int64_t pingUsecEnd = nTimeReceived;
6700 bool bPingFinished =
false;
6701 std::string sProblem;
6703 if (nAvail >=
sizeof(nonce)) {
6710 bPingFinished =
true;
6712 if (pingUsecTime > 0) {
6718 sProblem =
"Timing mishap";
6722 sProblem =
"Nonce mismatch";
6725 bPingFinished =
true;
6726 sProblem =
"Nonce zero";
6730 sProblem =
"Unsolicited pong without ping";
6734 bPingFinished =
true;
6735 sProblem =
"Short payload";
6738 if (!(sProblem.empty())) {
6747 if (bPingFinished) {
6754 LogPrintf(
"bloom message=%s\n", strCommand);
6761 if (!filter.IsWithinSizeConstraints()) {
6773 std::vector<unsigned char> vData;
6778 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
6798 unsigned char ccode;
6799 std::string strReason;
6802 std::ostringstream ss;
6803 ss << strMsg <<
" code " <<
itostr(ccode) <<
": " << strReason;
6808 ss <<
": hash " << hash.
ToString();
6811 }
catch (
const std::ios_base::failure& e) {
6818 for (
const std::string msg : allMessages) {
6819 if(msg == strCommand) {
6846 return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT;
6861 ProcessGetData(pfrom);
6866 std::deque<CNetMessage>::iterator it = pfrom->
vRecvMsg.begin();
6903 unsigned int nChecksum = ReadLE32((
unsigned char*)&hash);
6905 LogPrintf(
"ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
6913 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.
nTime);
6914 boost::this_thread::interruption_point();
6915 }
catch (
const std::ios_base::failure& e) {
6917 if (strstr(e.what(),
"end of data")) {
6919 LogPrintf(
"ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n",
SanitizeString(strCommand), nMessageSize, e.what());
6920 }
else if (strstr(e.what(),
"size too large")) {
6922 LogPrintf(
"ProcessMessages(%s, %u bytes): Exception '%s' caught\n",
SanitizeString(strCommand), nMessageSize, e.what());
6926 }
catch (
const boost::thread_interrupted&) {
6928 }
catch (
const std::exception& e) {
6958 bool pingSend =
false;
6969 while (nonce == 0) {
6974 if (pto->
nVersion > BIP0031_VERSION) {
7000 std::vector<CAddress> vAddr;
7005 vAddr.push_back(addr);
7007 if (vAddr.size() >= 1000) {
7018 CNodeState& state = *State(pto->
GetId());
7019 if (state.fShouldBan) {
7030 state.fShouldBan =
false;
7033 for (
const CBlockReject& reject : state.rejects)
7035 state.rejects.clear();
7040 bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->
fClient &&
7046 state.fSyncStarted =
true;
7063 std::vector<CInv> vInv;
7064 std::vector<CInv> vInvWait;
7068 fSendTrickle =
true;
7086 bool fTrickleWait = ((hashRand & 3) != 0);
7089 vInvWait.push_back(inv);
7096 vInv.push_back(inv);
7097 if (vInv.size() >= 1000) {
7110 state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
7114 LogPrintf(
"Peer=%d is stalling block download, disconnecting\n", pto->
id);
7122 if (!pto->
fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 *
Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
7123 LogPrintf(
"Timeout downloading block %s from peer=%d, disconnecting\n",
7124 state.vBlocksInFlight.front().hash.ToString(), pto->
id);
7131 std::vector<CInv> vGetData;
7132 if (!pto->
fDisconnect && !pto->
fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
7133 std::vector<CBlockIndex*> vToDownload;
7135 FindNextBlocksToDownload(pto->
GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload,
7143 if (state.nBlocksInFlight == 0 && staller != -1) {
7144 if (State(staller)->nStallingSince == 0) {
7145 State(staller)->nStallingSince = nNow;
7156 if (!AlreadyHave(inv)) {
7158 vGetData.push_back(inv);
7159 if (vGetData.size() >= 1000) {
7166 if (!vGetData.empty())
7178 return error(
"CBlockUndo::WriteToDisk : OpenUndoFile failed");
7185 long fileOutPos = ftell(fileout.
Get());
7187 return error(
"CBlockUndo::WriteToDisk : ftell failed");
7188 pos.
nPos = (
unsigned int)fileOutPos;
7193 hasher << hashBlock;
7205 return error(
"CBlockUndo::ReadFromDisk : OpenBlockFile failed");
7211 filein >> hashChecksum;
7212 }
catch (
const std::exception& e) {
7213 return error(
"%s : Deserialize or I/O error - %s", __func__, e.what());
7218 hasher << hashBlock;
7220 if (hashChecksum != hasher.
GetHash())
7221 return error(
"CBlockUndo::ReadFromDisk : Checksum mismatch");
7243 delete (*it1).second;