22 #include <boost/algorithm/string/replace.hpp>
23 #include <boost/filesystem.hpp>
24 #include <boost/filesystem/fstream.hpp>
27 using namespace boost;
36 # error "Bitcoin cannot be compiled without assertions."
86 struct CBlockIndexWorkComparator
99 if (pa < pb)
return false;
100 if (pa > pb)
return true;
109 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
113 int nLastBlockFile = 0;
119 uint32_t nBlockSequenceId = 1;
123 map<uint256, NodeId> mapBlockSource;
132 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
133 map<uint256, pair<NodeId, list<uint256>::iterator> > mapBlocksToDownload;
144 struct CMainSignals {
146 boost::signals2::signal<void (const uint256 &, const CTransaction &, const CBlock *)> SyncTransaction;
148 boost::signals2::signal<void (const uint256 &)> EraseTransaction;
150 boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
152 boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
154 boost::signals2::signal<void (const uint256 &)> Inventory;
156 boost::signals2::signal<void ()> Broadcast;
179 g_signals.Broadcast.disconnect_all_slots();
180 g_signals.Inventory.disconnect_all_slots();
181 g_signals.SetBestChain.disconnect_all_slots();
182 g_signals.UpdatedTransaction.disconnect_all_slots();
183 g_signals.EraseTransaction.disconnect_all_slots();
184 g_signals.SyncTransaction.disconnect_all_slots();
188 g_signals.SyncTransaction(hash, tx, pblock);
198 struct CBlockReject {
199 unsigned char chRejectCode;
200 string strRejectReason;
216 std::vector<CBlockReject> rejects;
217 list<QueuedBlock> vBlocksInFlight;
219 list<uint256> vBlocksToDownload;
220 int nBlocksToDownload;
221 int64_t nLastBlockReceive;
222 int64_t nLastBlockProcess;
227 nBlocksToDownload = 0;
229 nLastBlockReceive = 0;
230 nLastBlockProcess = 0;
235 map<NodeId, CNodeState> mapNodeState;
238 CNodeState *State(
NodeId pnode) {
239 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
240 if (it == mapNodeState.end())
248 return chainActive.
Height();
251 void InitializeNode(
NodeId nodeid,
const CNode *pnode) {
253 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
257 void FinalizeNode(
NodeId nodeid) {
259 CNodeState *state = State(nodeid);
261 BOOST_FOREACH(
const QueuedBlock& entry, state->vBlocksInFlight)
262 mapBlocksInFlight.erase(entry.hash);
263 BOOST_FOREACH(const
uint256& hash, state->vBlocksToDownload)
264 mapBlocksToDownload.erase(hash);
267 mapNodeState.erase(nodeid);
271 void MarkBlockAsReceived(const
uint256 &hash,
NodeId nodeFrom = -1) {
272 map<uint256, pair<NodeId, list<uint256>::iterator> >::iterator itToDownload = mapBlocksToDownload.find(hash);
273 if (itToDownload != mapBlocksToDownload.end()) {
274 CNodeState *state = State(itToDownload->second.first);
275 state->vBlocksToDownload.erase(itToDownload->second.second);
276 state->nBlocksToDownload--;
277 mapBlocksToDownload.erase(itToDownload);
280 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
281 if (itInFlight != mapBlocksInFlight.end()) {
282 CNodeState *state = State(itInFlight->second.first);
283 state->vBlocksInFlight.erase(itInFlight->second.second);
284 state->nBlocksInFlight--;
285 if (itInFlight->second.first == nodeFrom)
287 mapBlocksInFlight.erase(itInFlight);
294 if (mapBlocksToDownload.count(hash) || mapBlocksInFlight.count(hash))
297 CNodeState *state = State(nodeid);
301 list<uint256>::iterator it = state->vBlocksToDownload.insert(state->vBlocksToDownload.end(), hash);
302 state->nBlocksToDownload++;
303 if (state->nBlocksToDownload > 5000)
305 mapBlocksToDownload[hash] = std::make_pair(nodeid, it);
310 void MarkBlockAsInFlight(
NodeId nodeid,
const uint256 &hash) {
311 CNodeState *state = State(nodeid);
312 assert(state != NULL);
315 MarkBlockAsReceived(hash);
317 QueuedBlock newentry = {hash,
GetTimeMicros(), state->nBlocksInFlight};
318 if (state->nBlocksInFlight == 0)
319 state->nLastBlockReceive = newentry.nTime;
320 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
321 state->nBlocksInFlight++;
322 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
329 CNodeState *state = State(nodeid);
360 if (pindex == NULL) {
364 vChain.resize(pindex->
nHeight + 1);
365 while (pindex && vChain[pindex->
nHeight] != pindex) {
366 vChain[pindex->
nHeight] = pindex;
367 pindex = pindex->
pprev;
374 std::vector<uint256> vHave;
385 int nHeight = std::max(pindex->
nHeight - nStep, 0);
387 while (pindex->
nHeight > nHeight && !Contains(pindex))
388 pindex = pindex->
pprev;
391 pindex = (*this)[nHeight];
392 if (vHave.size() > 10)
402 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
403 if (mi != mapBlockIndex.end())
406 if (Contains(pindex))
424 if (mapOrphanTransactions.count(hash))
437 LogPrint(
"mempool",
"ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.
ToString());
441 mapOrphanTransactions[hash].tx = tx;
442 mapOrphanTransactions[hash].fromPeer = peer;
443 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
444 mapOrphanTransactionsByPrev[txin.
prevout.
hash].insert(hash);
446 LogPrint(
"mempool",
"stored orphan tx %s (mapsz %u prevsz %u)\n", hash.
ToString(),
447 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
453 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
454 if (it == mapOrphanTransactions.end())
456 BOOST_FOREACH(
const CTxIn& txin, it->second.tx.vin)
458 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.
prevout.
hash);
459 if (itPrev == mapOrphanTransactionsByPrev.end())
461 itPrev->second.erase(hash);
462 if (itPrev->second.empty())
463 mapOrphanTransactionsByPrev.erase(itPrev);
465 mapOrphanTransactions.erase(it);
471 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
472 while (iter != mapOrphanTransactions.end())
474 map<uint256, COrphanTx>::iterator maybeErase = iter++;
475 if (maybeErase->second.fromPeer == peer)
481 if (nErased > 0)
LogPrint(
"mempool",
"Erased %d orphan tx from peer %d\n", nErased, peer);
487 unsigned int nEvicted = 0;
488 while (mapOrphanTransactions.size() > nMaxOrphans)
492 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
493 if (it == mapOrphanTransactions.end())
494 it = mapOrphanTransactions.begin();
533 reason =
"non-final";
547 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
557 reason =
"scriptsig-size";
561 reason =
"scriptsig-not-pushonly";
565 reason =
"scriptsig-non-canonical-push";
570 unsigned int nDataOut = 0;
574 reason =
"scriptpubkey";
587 reason =
"multi-op-return";
600 if (nBlockHeight == 0)
601 nBlockHeight = chainActive.
Height();
606 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
628 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
632 vector<vector<unsigned char> > vSolutions;
636 if (!
Solver(prevScript, whichType, vSolutions))
639 if (nArgsExpected < 0)
647 vector<vector<unsigned char> > stack;
648 if (!
EvalScript(stack, tx.
vin[i].scriptSig, tx, i,
false, 0))
655 CScript subscript(stack.back().begin(), stack.back().end());
656 vector<vector<unsigned char> > vSolutions2;
658 if (!
Solver(subscript, whichType2, vSolutions2))
667 nArgsExpected += tmpExpected;
670 if (stack.size() != (
unsigned int)nArgsExpected)
679 unsigned int nSigOps = 0;
680 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
696 unsigned int nSigOps = 0;
697 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
706 int CMerkleTx::SetMerkleBranch(
const CBlock* pblock)
711 if (pblock == NULL) {
713 if (pcoinsTip->
GetCoins(GetHash(), coins)) {
728 for (nIndex = 0; nIndex < (
int)pblock->
vtx.size(); nIndex++)
731 if (nIndex == (
int)pblock->
vtx.size())
733 vMerkleBranch.clear();
735 LogPrintf(
"ERROR: SetMerkleBranch() : couldn't find tx in block\n");
744 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
745 if (mi == mapBlockIndex.end())
748 if (!pindex || !chainActive.
Contains(pindex))
764 return state.
DoS(10,
error(
"CheckTransaction() : vin empty"),
767 return state.
DoS(10,
error(
"CheckTransaction() : vout empty"),
771 return state.
DoS(100,
error(
"CheckTransaction() : size limits failed"),
775 int64_t nValueOut = 0;
779 return state.
DoS(100,
error(
"CheckTransaction() : txout.nValue negative"),
782 return state.
DoS(100,
error(
"CheckTransaction() : txout.nValue too high"),
784 nValueOut += txout.
nValue;
786 return state.
DoS(100,
error(
"CheckTransaction() : txout total out of range"),
791 set<COutPoint> vInOutPoints;
792 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
794 if (vInOutPoints.count(txin.
prevout))
795 return state.
DoS(100,
error(
"CheckTransaction() : duplicate inputs"),
797 vInOutPoints.insert(txin.
prevout);
802 if (tx.
vin[0].scriptSig.size() < 2 || tx.
vin[0].scriptSig.size() > 100)
803 return state.
DoS(100,
error(
"CheckTransaction() : coinbase script size"),
808 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
810 return state.
DoS(10,
error(
"CheckTransaction() : prevout is null"),
822 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
839 if (nMinFee < nBaseFee && mode ==
GMF_SEND)
853 bool* pfMissingInputs,
bool fRejectInsaneFee)
857 *pfMissingInputs =
false;
860 return error(
"AcceptToMemoryPool: : CheckTransaction failed");
864 return state.
DoS(100,
error(
"AcceptToMemoryPool: : coinbase as individual tx"),
871 error(
"AcceptToMemoryPool : nonstandard transaction: %s", reason),
882 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
909 BOOST_FOREACH(
const CTxIn txin, tx.
vin) {
912 *pfMissingInputs =
true;
919 return state.
Invalid(
error(
"AcceptToMemoryPool : inputs already spent"),
931 return error(
"AcceptToMemoryPool: : nonstandard transaction input");
939 int64_t nFees = nValueIn-nValueOut;
943 unsigned int nSize = entry.GetTxSize();
947 if (fLimitFree && nFees < txMinFee)
948 return state.
DoS(0,
error(
"AcceptToMemoryPool : not enough fees %s, %d < %d",
958 static double dFreeCount;
959 static int64_t nLastTime;
965 dFreeCount *= pow(1.0 - 1.0/600.0, (
double)(nNow - nLastTime));
969 if (dFreeCount >=
GetArg(
"-limitfreerelay", 15)*10*1000)
970 return state.
DoS(0,
error(
"AcceptToMemoryPool : free transaction rejected by rate limiter"),
972 LogPrint(
"mempool",
"Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
977 return error(
"AcceptToMemoryPool: : insane fees %s, %d > %d",
985 return error(
"AcceptToMemoryPool: : ConnectInputs failed %s", hash.
ToString());
991 g_signals.SyncTransaction(hash, tx, NULL);
999 if (hashBlock == 0 || nIndex == -1)
1004 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1005 if (mi == mapBlockIndex.end())
1008 if (!pindex || !chainActive.
Contains(pindex))
1012 if (!fMerkleVerified)
1016 fMerkleVerified =
true;
1026 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
1027 if (nResult == 0 && !mempool.
exists(GetHash()))
1055 if (mempool.
lookup(hash, txOut))
1070 }
catch (std::exception &e) {
1071 return error(
"%s : Deserialize or I/O error - %s", __func__, e.what());
1075 return error(
"%s : txid mismatch", __func__);
1089 pindexSlow = chainActive[nHeight];
1124 return error(
"WriteBlockToDisk : OpenBlockFile failed");
1131 long fileOutPos = ftell(fileout);
1133 return error(
"WriteBlockToDisk : ftell failed");
1134 pos.
nPos = (
unsigned int)fileOutPos;
1152 return error(
"ReadBlockFromDisk : OpenBlockFile failed");
1158 catch (std::exception &e) {
1159 return error(
"%s : Deserialize or I/O error - %s", __func__, e.what());
1164 return error(
"ReadBlockFromDisk : Errors in block header");
1174 return error(
"ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
1180 map<uint256, COrphanBlock*>::iterator it = mapOrphanBlocks.find(hash);
1181 if (it == mapOrphanBlocks.end())
1186 map<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocks.find(it->second->hashPrev);
1187 if (it2 == mapOrphanBlocks.end())
1201 std::multimap<uint256, COrphanBlock*>::iterator it = mapOrphanBlocksByPrev.begin();
1206 std::multimap<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocksByPrev.find(it->second->hashBlock);
1207 if (it2 == mapOrphanBlocksByPrev.end())
1212 uint256 hash = it->second->hashBlock;
1214 mapOrphanBlocksByPrev.erase(it);
1215 mapOrphanBlocks.erase(hash);
1220 int64_t nSubsidy = 50 *
COIN;
1228 nSubsidy >>= halvings;
1230 return nSubsidy + nFees;
1246 if (
TestNet() && nTime > nTargetSpacing*2)
1251 while (nTime > 0 && bnResult < bnLimit)
1256 nTime -= nTargetTimespan*4;
1258 if (bnResult > bnLimit)
1268 if (pindexLast == NULL)
1269 return nProofOfWorkLimit;
1272 if ((pindexLast->
nHeight+1) % nInterval != 0)
1279 if (pblock->
nTime > pindexLast->
nTime + nTargetSpacing*2)
1280 return nProofOfWorkLimit;
1285 while (pindex->
pprev && pindex->
nHeight % nInterval != 0 && pindex->
nBits == nProofOfWorkLimit)
1286 pindex = pindex->
pprev;
1287 return pindex->
nBits;
1290 return pindexLast->
nBits;
1295 for (
int i = 0; pindexFirst && i < nInterval-1; i++)
1296 pindexFirst = pindexFirst->
pprev;
1297 assert(pindexFirst);
1301 LogPrintf(
" nActualTimespan = %d before bounds\n", nActualTimespan);
1302 if (nActualTimespan < nTargetTimespan/4)
1303 nActualTimespan = nTargetTimespan/4;
1304 if (nActualTimespan > nTargetTimespan*4)
1305 nActualTimespan = nTargetTimespan*4;
1310 bnNew *= nActualTimespan;
1313 if (bnNew >
Params().ProofOfWorkLimit())
1317 LogPrintf(
"GetNextWorkRequired RETARGET\n");
1318 LogPrintf(
"nTargetTimespan = %d nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);
1331 if (bnTarget <= 0 || bnTarget >
Params().ProofOfWorkLimit())
1332 return error(
"CheckProofOfWork() : nBits below minimum work");
1336 return error(
"CheckProofOfWork() : hash doesn't match nBits");
1346 static int64_t nLastUpdate;
1348 if (chainActive.
Tip() != pindexLastBest)
1350 pindexLastBest = chainActive.
Tip();
1353 return (
GetTime() - nLastUpdate < 10 &&
1371 if (pindexBestForkTip && chainActive.
Height() - pindexBestForkTip->
nHeight >= 72)
1372 pindexBestForkTip = NULL;
1374 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.
Tip()->
nChainWork + (chainActive.
Tip()->
GetBlockWork() * 6).getuint256()))
1376 if (!fLargeWorkForkFound)
1378 std::string strCmd =
GetArg(
"-alertnotify",
"");
1379 if (!strCmd.empty())
1381 std::string warning = std::string(
"'Warning: Large-work fork detected, forking after block ") +
1382 pindexBestForkBase->phashBlock->ToString() + std::string(
"'");
1383 boost::replace_all(strCmd,
"%s", warning);
1387 if (pindexBestForkTip)
1389 LogPrintf(
"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",
1390 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1392 fLargeWorkForkFound =
true;
1396 LogPrintf(
"CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1397 fLargeWorkInvalidChainFound =
true;
1402 fLargeWorkForkFound =
false;
1403 fLargeWorkInvalidChainFound =
false;
1413 while (pfork && pfork != plonger)
1416 plonger = plonger->
pprev;
1417 if (pfork == plonger)
1419 pfork = pfork->
pprev;
1429 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->
nHeight > pindexBestForkTip->
nHeight)) &&
1433 pindexBestForkTip = pindexNewForkTip;
1434 pindexBestForkBase = pfork;
1446 CNodeState *state = State(pnode);
1450 state->nMisbehavior += howmuch;
1451 if (state->nMisbehavior >=
GetArg(
"-banscore", 100))
1453 LogPrintf(
"Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1454 state->fShouldBan =
true;
1456 LogPrintf(
"Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1461 if (!pindexBestInvalid || pindexNew->
nChainWork > pindexBestInvalid->nChainWork)
1463 pindexBestInvalid = pindexNew;
1470 LogPrintf(
"InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1474 LogPrintf(
"InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1483 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->
GetBlockHash());
1484 if (it != mapBlockSource.end() && State(it->second)) {
1486 State(it->second)->rejects.push_back(reject);
1494 setBlockIndexValid.erase(pindex);
1523 BOOST_FOREACH(
const CTxIn &txin, tx.
vin) {
1538 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1539 if (!
VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1540 return error(
"CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString());
1546 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1554 pvChecks->reserve(tx.
vin.size());
1564 int nSpendHeight = pindexPrev->
nHeight + 1;
1565 int64_t nValueIn = 0;
1567 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
1576 error(
"CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.
nHeight),
1581 nValueIn += coins.
vout[prevout.
n].nValue;
1583 return state.
DoS(100,
error(
"CheckInputs() : txin values out of range"),
1599 return state.
DoS(100,
error(
"CheckInputs() : nFees out of range"),
1609 if (fScriptChecks) {
1610 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
1618 check.
swap(pvChecks->back());
1619 }
else if (!check()) {
1623 CScriptCheck check(coins, tx, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
1650 return error(
"DisconnectBlock() : no undo data available");
1652 return error(
"DisconnectBlock() : failure reading undo data");
1654 if (blockUndo.
vtxundo.size() + 1 != block.
vtx.size())
1655 return error(
"DisconnectBlock() : block and undo data inconsistent");
1658 for (
int i = block.
vtx.size() - 1; i >= 0; i--) {
1676 if (outs != outsBlock)
1677 fClean = fClean &&
error(
"DisconnectBlock() : added transaction mismatch? database corrupted");
1686 return error(
"DisconnectBlock() : transaction and undo data inconsistent");
1687 for (
unsigned int j = tx.
vin.size(); j-- > 0;) {
1695 fClean = fClean &&
error(
"DisconnectBlock() : undo data overwriting existing transaction");
1702 fClean = fClean &&
error(
"DisconnectBlock() : undo data adding output to missing transaction");
1705 fClean = fClean &&
error(
"DisconnectBlock() : undo data overwriting existing output");
1706 if (coins.
vout.size() < out.
n+1)
1707 coins.
vout.resize(out.
n+1);
1710 return error(
"DisconnectBlock() : cannot restore coin inputs");
1728 LOCK(cs_LastBlockFile);
1762 if (!
CheckBlock(block, state, !fJustCheck, !fJustCheck))
1790 bool fEnforceBIP30 = (!pindex->
phashBlock) ||
1791 !((pindex->
nHeight==91842 && pindex->
GetBlockHash() == uint256(
"0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1792 (pindex->
nHeight==91880 && pindex->
GetBlockHash() == uint256(
"0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1793 if (fEnforceBIP30) {
1794 for (
unsigned int i = 0; i < block.
vtx.size(); i++) {
1797 return state.
DoS(100,
error(
"ConnectBlock() : tried to overwrite transaction"),
1803 int64_t nBIP16SwitchTime = 1333238400;
1804 bool fStrictPayToScriptHash = (pindex->
nTime >= nBIP16SwitchTime);
1816 unsigned int nSigOps = 0;
1818 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1819 vPos.reserve(block.
vtx.size());
1820 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
1824 nInputs += tx.
vin.size();
1827 return state.
DoS(100,
error(
"ConnectBlock() : too many sigops"),
1833 return state.
DoS(100,
error(
"ConnectBlock() : inputs missing/spent"),
1836 if (fStrictPayToScriptHash)
1843 return state.
DoS(100,
error(
"ConnectBlock() : too many sigops"),
1849 std::vector<CScriptCheck> vChecks;
1850 if (!
CheckInputs(tx, state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1852 control.
Add(vChecks);
1858 blockundo.
vtxundo.push_back(txundo);
1860 vPos.push_back(std::make_pair(block.
GetTxHash(i), pos));
1865 LogPrintf(
"- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (
unsigned)block.
vtx.size(), 0.001 * nTime, 0.001 * nTime / block.
vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
1868 return state.
DoS(100,
1869 error(
"ConnectBlock() : coinbase pays too much (actual=%d vs limit=%d)",
1873 if (!control.
Wait())
1874 return state.
DoS(100,
false);
1877 LogPrintf(
"- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1888 return error(
"ConnectBlock() : FindUndoPos failed");
1890 return state.
Abort(
_(
"Failed to write undo data"));
1901 return state.
Abort(
_(
"Failed to write block index"));
1906 return state.
Abort(
_(
"Failed to write transaction index"));
1914 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
1922 static int64_t nLastWrite = 0;
1930 return state.
Error(
"out of disk space");
1933 if (!pcoinsTip->
Flush())
1934 return state.
Abort(
_(
"Failed to write to coin database"));
1942 chainActive.
SetTip(pindexNew);
1946 if ((chainActive.
Height() % 20160) == 0 || (!fIsInitialDownload && (chainActive.
Height() % 144) == 0))
1952 LogPrintf(
"UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
1958 if (!fIsInitialDownload)
1962 for (
int i = 0; i < 100 && pindex != NULL; i++)
1966 pindex = pindex->
pprev;
1970 if (nUpgraded > 100/2)
1972 strMiscWarning =
_(
"Warning: This version is obsolete, upgrade required!");
1979 assert(pindexDelete);
1980 mempool.
check(pcoinsTip);
1984 return state.
Abort(
_(
"Failed to read block"));
1991 assert(view.
Flush());
2001 list<CTransaction> removed;
2005 mempool.
remove(tx, removed,
true);
2007 mempool.
check(pcoinsTip);
2028 assert(pindexNew->
pprev == chainActive.
Tip());
2032 mempool.
check(pcoinsTip);
2036 return state.
Abort(
_(
"Failed to read block"));
2047 mapBlockSource.erase(inv.hash);
2048 assert(view.
Flush());
2056 list<CTransaction> txConflicted;
2058 list<CTransaction> unused;
2059 mempool.
remove(tx, unused);
2062 mempool.
check(pcoinsTip);
2071 unsigned int tx_idx = 0, countMP = 0;
2091 setBlockIndexValid.erase(chainMostWork.
Tip());
2098 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
2099 if (it == setBlockIndexValid.rend())
2107 bool fInvalidAncestor =
false;
2108 while (pindexTest && !chainActive.
Contains(pindexTest)) {
2111 if (pindexBestInvalid == NULL || pindexNew->
nChainWork > pindexBestInvalid->nChainWork)
2112 pindexBestInvalid = pindexNew;
CBlockIndex *pindexFailed = pindexNew;
2113 while (pindexTest != pindexFailed) {
2115 setBlockIndexValid.erase(pindexFailed);
2116 pindexFailed = pindexFailed->
pprev;
2118 fInvalidAncestor =
true;
2121 pindexTest = pindexTest->
pprev;
2123 if (fInvalidAncestor)
2130 if (chainMostWork.
Tip() && !CBlockIndexWorkComparator()(chainMostWork.
Tip(), pindexNew))
2134 chainMostWork.
SetTip(pindexNew);
2141 bool fComplete =
false;
2142 while (!fComplete) {
2147 if (chainMostWork.
Tip() == NULL)
break;
2150 while (chainActive.
Tip() && !chainMostWork.
Contains(chainActive.
Tip())) {
2156 while (!chainActive.
Contains(chainMostWork.
Tip())) {
2174 if (chainActive.
Tip() != pindexOldTip) {
2175 std::string strCmd =
GetArg(
"-blocknotify",
"");
2190 if (mapBlockIndex.count(hash))
2191 return state.
Invalid(
error(
"AddToBlockIndex() : %s already exists", hash.
ToString()), 0,
"duplicate");
2197 LOCK(cs_nBlockSequenceId);
2200 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2202 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(block.
hashPrevBlock);
2203 if (miPrev != mapBlockIndex.end())
2205 pindexNew->
pprev = (*miPrev).second;
2208 pindexNew->
nTx = block.
vtx.size();
2215 setBlockIndexValid.insert(pindexNew);
2218 return state.
Abort(
_(
"Failed to write block index"));
2225 if (pindexNew == chainActive.
Tip())
2230 static uint256 hashPrevBestCoinBase;
2231 g_signals.UpdatedTransaction(hashPrevBestCoinBase);
2232 hashPrevBestCoinBase = block.
GetTxHash(0);
2236 if (!pblocktree->
Flush())
2237 return state.
Abort(
_(
"Failed to sync block index"));
2246 bool fUpdatedLast =
false;
2248 LOCK(cs_LastBlockFile);
2251 if (nLastBlockFile != pos.
nFile) {
2252 nLastBlockFile = pos.
nFile;
2253 infoLastBlockFile.SetNull();
2255 fUpdatedLast =
true;
2259 LogPrintf(
"Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString());
2262 infoLastBlockFile.SetNull();
2264 fUpdatedLast =
true;
2266 pos.
nFile = nLastBlockFile;
2267 pos.
nPos = infoLastBlockFile.nSize;
2270 infoLastBlockFile.nSize += nAddSize;
2271 infoLastBlockFile.AddBlock(nHeight, nTime);
2276 if (nNewChunks > nOldChunks) {
2286 return state.
Error(
"out of disk space");
2291 return state.
Abort(
_(
"Failed to write file info"));
2302 LOCK(cs_LastBlockFile);
2304 unsigned int nNewSize;
2305 if (nFile == nLastBlockFile) {
2306 pos.
nPos = infoLastBlockFile.nUndoSize;
2307 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2309 return state.
Abort(
_(
"Failed to write block info"));
2313 return state.
Abort(
_(
"Failed to read block info"));
2315 nNewSize = (info.
nUndoSize += nAddSize);
2317 return state.
Abort(
_(
"Failed to write block info"));
2322 if (nNewChunks > nOldChunks) {
2332 return state.
Error(
"out of disk space");
2346 return state.
DoS(100,
error(
"CheckBlock() : size limits failed"),
2351 return state.
DoS(50,
error(
"CheckBlock() : proof of work failed"),
2356 return state.
Invalid(
error(
"CheckBlock() : block timestamp too far in the future"),
2360 if (block.
vtx.empty() || !block.
vtx[0].IsCoinBase())
2361 return state.
DoS(100,
error(
"CheckBlock() : first tx is not coinbase"),
2363 for (
unsigned int i = 1; i < block.
vtx.size(); i++)
2364 if (block.
vtx[i].IsCoinBase())
2365 return state.
DoS(100,
error(
"CheckBlock() : more than one coinbase"),
2371 return error(
"CheckBlock() : CheckTransaction failed");
2380 set<uint256> uniqueTx;
2381 for (
unsigned int i = 0; i < block.
vtx.size(); i++) {
2384 if (uniqueTx.size() != block.
vtx.size())
2385 return state.
DoS(100,
error(
"CheckBlock() : duplicate transaction"),
2388 unsigned int nSigOps = 0;
2394 return state.
DoS(100,
error(
"CheckBlock() : out-of-bounds SigOpCount"),
2399 return state.
DoS(100,
error(
"CheckBlock() : hashMerkleRoot mismatch"),
2410 if (mapBlockIndex.count(hash))
2411 return state.
Invalid(
error(
"AcceptBlock() : block already in mapBlockIndex"), 0,
"duplicate");
2416 if (hash !=
Params().HashGenesisBlock()) {
2417 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.
hashPrevBlock);
2418 if (mi == mapBlockIndex.end())
2419 return state.
DoS(10,
error(
"AcceptBlock() : prev block not found"), 0,
"bad-prevblk");
2420 pindexPrev = (*mi).second;
2421 nHeight = pindexPrev->
nHeight+1;
2425 return state.
DoS(100,
error(
"AcceptBlock() : incorrect proof of work"),
2430 return state.
Invalid(
error(
"AcceptBlock() : block's timestamp is too early"),
2436 return state.
DoS(10,
error(
"AcceptBlock() : contains a non-final transaction"),
2441 return state.
DoS(100,
error(
"AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight),
2446 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2447 return state.
DoS(100,
error(
"AcceptBlock() : forked chain older than last checkpoint (height %d)", nHeight));
2455 return state.
Invalid(
error(
"AcceptBlock() : rejected nVersion=1 block"),
2467 if (block.
vtx[0].vin[0].scriptSig.size() < expect.size() ||
2468 !std::equal(expect.begin(), expect.end(), block.
vtx[0].vin[0].scriptSig.begin()))
2469 return state.
DoS(100,
error(
"AcceptBlock() : block height mismatch in coinbase"),
2481 if (!
FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.
nTime, dbp != NULL))
2482 return error(
"AcceptBlock() : FindBlockPos failed");
2485 return state.
Abort(
_(
"Failed to write block"));
2487 return error(
"AcceptBlock() : AddToBlockIndex failed");
2488 }
catch(std::runtime_error &e) {
2489 return state.
Abort(
_(
"System error: ") + e.what());
2507 unsigned int nFound = 0;
2508 for (
unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2510 if (pstart->
nVersion >= minVersion)
2512 pstart = pstart->
pprev;
2514 return (nFound >= nRequired);
2521 for (
int i = 0; i < nMedianTimeSpan/2; i++)
2523 if (!chainActive.
Next(pindex))
2524 return GetBlockTime();
2525 pindex = chainActive.
Next(pindex);
2548 if (mapBlockIndex.count(hash))
2549 return state.
Invalid(
error(
"ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.
ToString()), 0,
"duplicate");
2550 if (mapOrphanBlocks.count(hash))
2551 return state.
Invalid(
error(
"ProcessBlock() : already have block (orphan) %s", hash.
ToString()), 0,
"duplicate");
2555 return error(
"ProcessBlock() : CheckBlock FAILED");
2564 return state.
DoS(100,
error(
"ProcessBlock() : block with timestamp before last checkpoint"),
2571 if (bnNewBlock > bnRequired)
2573 return state.
DoS(100,
error(
"ProcessBlock() : block with too little proof-of-work"),
2595 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2596 mapOrphanBlocksByPrev.insert(make_pair(pblock2->
hashPrev, pblock2));
2606 return error(
"ProcessBlock() : AcceptBlock FAILED");
2609 vector<uint256> vWorkQueue;
2610 vWorkQueue.push_back(hash);
2611 for (
unsigned int i = 0; i < vWorkQueue.size(); i++)
2613 uint256 hashPrev = vWorkQueue[i];
2614 for (multimap<uint256, COrphanBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2615 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2627 vWorkQueue.push_back(mi->second->hashBlock);
2628 mapOrphanBlocks.erase(mi->second->hashBlock);
2631 mapOrphanBlocksByPrev.erase(hashPrev);
2649 vector<bool> vMatch;
2650 vector<uint256> vHashes;
2652 vMatch.reserve(block.
vtx.size());
2653 vHashes.reserve(block.
vtx.size());
2655 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
2660 vMatch.push_back(
true);
2661 vMatchedTxn.push_back(make_pair(i, hash));
2664 vMatch.push_back(
false);
2665 vHashes.push_back(hash);
2684 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2686 if (pos*2+1 < CalcTreeWidth(height-1))
2687 right = CalcHash(height-1, pos*2+1, vTxid);
2697 bool fParentOfMatch =
false;
2698 for (
unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2699 fParentOfMatch |= vMatch[p];
2701 vBits.push_back(fParentOfMatch);
2702 if (height==0 || !fParentOfMatch) {
2704 vHash.push_back(CalcHash(height, pos, vTxid));
2707 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2708 if (pos*2+1 < CalcTreeWidth(height-1))
2709 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2714 if (nBitsUsed >= vBits.size()) {
2719 bool fParentOfMatch = vBits[nBitsUsed++];
2720 if (height==0 || !fParentOfMatch) {
2722 if (nHashUsed >= vHash.size()) {
2727 const uint256 &hash = vHash[nHashUsed++];
2728 if (height==0 && fParentOfMatch)
2729 vMatch.push_back(hash);
2733 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2734 if (pos*2+1 < CalcTreeWidth(height-1))
2735 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2743 CPartialMerkleTree::CPartialMerkleTree(
const std::vector<uint256> &vTxid,
const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2757 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2778 unsigned int nBitsUsed = 0, nHashUsed = 0;
2784 if ((nBitsUsed+7)/8 != (
vBits.size()+7)/8)
2787 if (nHashUsed !=
vHash.size())
2789 return hashMerkleRoot;
2808 uint64_t nFreeBytesAvailable = filesystem::space(
GetDataDir()).available;
2812 return AbortNode(
_(
"Error: Disk space is low!"));
2822 boost::filesystem::create_directories(path.parent_path());
2823 FILE* file = fopen(path.string().c_str(),
"rb+");
2824 if (!file && !fReadOnly)
2825 file = fopen(path.string().c_str(),
"wb+");
2827 LogPrintf(
"Unable to open file %s\n", path.string());
2831 if (fseek(file, pos.
nPos, SEEK_SET)) {
2832 LogPrintf(
"Unable to seek to position %u of %s\n", pos.
nPos, path.string());
2854 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2855 if (mi != mapBlockIndex.end())
2856 return (*mi).second;
2861 throw runtime_error(
"LoadBlockIndex() : new CBlockIndex failed");
2862 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2863 pindexNew->phashBlock = &((*mi).first);
2873 boost::this_thread::interruption_point();
2876 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2877 vSortedByHeight.reserve(mapBlockIndex.size());
2881 vSortedByHeight.push_back(make_pair(pindex->
nHeight, pindex));
2883 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2890 setBlockIndexValid.insert(pindex);
2892 pindexBestInvalid = pindex;
2897 LogPrintf(
"LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
2899 LogPrintf(
"LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString());
2902 bool fReindexing =
false;
2908 LogPrintf(
"LoadBlockIndexDB(): transaction index %s\n",
fTxIndex ?
"enabled" :
"disabled");
2911 std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(pcoinsTip->
GetBestBlock());
2912 if (it == mapBlockIndex.end())
2914 chainActive.
SetTip(it->second);
2915 LogPrintf(
"LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
2926 if (chainActive.
Tip() == NULL || chainActive.
Tip()->
pprev == NULL)
2930 if (nCheckDepth <= 0)
2931 nCheckDepth = 1000000000;
2932 if (nCheckDepth > chainActive.
Height())
2933 nCheckDepth = chainActive.
Height();
2934 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2935 LogPrintf(
"Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2939 int nGoodTransactions = 0;
2943 boost::this_thread::interruption_point();
2951 if (nCheckLevel >= 1 && !
CheckBlock(block, state))
2954 if (nCheckLevel >= 2 && pindex) {
2967 pindexState = pindex->
pprev;
2969 nGoodTransactions = 0;
2970 pindexFailure = pindex;
2972 nGoodTransactions += block.
vtx.size();
2976 return error(
"VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.
Height() - pindexFailure->
nHeight + 1, nGoodTransactions);
2979 if (nCheckLevel >= 4) {
2981 while (pindex != chainActive.
Tip()) {
2982 boost::this_thread::interruption_point();
2983 pindex = chainActive.
Next(pindex);
2992 LogPrintf(
"No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.
Height() - pindexState->
nHeight, nGoodTransactions);
2999 mapBlockIndex.clear();
3000 setBlockIndexValid.clear();
3001 chainActive.
SetTip(NULL);
3002 pindexBestInvalid = NULL;
3017 if (chainActive.
Genesis() != NULL)
3023 LogPrintf(
"Initializing databases...\n");
3034 return error(
"LoadBlockIndex() : FindBlockPos failed");
3036 return error(
"LoadBlockIndex() : writing genesis block to disk failed");
3038 return error(
"LoadBlockIndex() : genesis block not accepted");
3039 }
catch(std::runtime_error &e) {
3040 return error(
"LoadBlockIndex() : failed to initialize block database: %s", e.what());
3053 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
3054 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
3057 mapNext[pindex->
pprev].push_back(pindex);
3063 vector<pair<int, CBlockIndex*> > vStack;
3064 vStack.push_back(make_pair(0, chainActive.
Genesis()));
3067 while (!vStack.empty())
3069 int nCol = vStack.back().first;
3074 if (nCol > nPrevCol)
3076 for (
int i = 0; i < nCol-1; i++)
3080 else if (nCol < nPrevCol)
3082 for (
int i = 0; i < nCol; i++)
3089 for (
int i = 0; i < nCol; i++)
3095 LogPrintf(
"%d (blk%05u.dat:0x%x) %s tx %u\n",
3102 vector<CBlockIndex*>& vNext = mapNext[pindex];
3103 for (
unsigned int i = 0; i < vNext.size(); i++)
3105 if (chainActive.
Next(vNext[i]))
3107 swap(vNext[0], vNext[i]);
3113 for (
unsigned int i = 0; i < vNext.size(); i++)
3114 vStack.push_back(make_pair(nCol+i, vNext[i]));
3125 uint64_t nStartByte = 0;
3130 nStartByte = info.
nSize;
3134 uint64_t nRewind = blkdat.
GetPos();
3135 while (blkdat.
good() && !blkdat.
eof()) {
3136 boost::this_thread::interruption_point();
3141 unsigned int nSize = 0;
3146 nRewind = blkdat.
GetPos()+1;
3154 }
catch (std::exception &e) {
3160 uint64_t nBlockPos = blkdat.
GetPos();
3161 blkdat.
SetLimit(nBlockPos + nSize);
3164 nRewind = blkdat.
GetPos();
3167 if (nBlockPos >= nStartByte) {
3170 dbp->
nPos = nBlockPos;
3177 }
catch (std::exception &e) {
3178 LogPrintf(
"%s : Deserialize or I/O error - %s", __func__, e.what());
3182 }
catch(std::runtime_error &e) {
3183 AbortNode(
_(
"Error: system error: ") + e.what());
3207 string strStatusBar;
3214 strStatusBar =
_(
"This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3223 if (fLargeWorkForkFound)
3226 strStatusBar = strRPC =
_(
"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3228 else if (fLargeWorkInvalidChainFound)
3231 strStatusBar = strRPC =
_(
"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
3239 const CAlert& alert = item.second;
3248 if (strFor ==
"statusbar")
3249 return strStatusBar;
3250 else if (strFor ==
"rpc")
3252 assert(!
"GetWarnings() : invalid parameter");
3275 bool txInMap =
false;
3277 return txInMap || mapOrphanTransactions.count(inv.
hash) ||
3281 return mapBlockIndex.count(inv.
hash) ||
3282 mapOrphanBlocks.count(inv.
hash);
3291 std::deque<CInv>::iterator it = pfrom->
vRecvGetData.begin();
3293 vector<CInv> vNotFound;
3302 const CInv &inv = *it;
3304 boost::this_thread::interruption_point();
3310 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.
hash);
3311 if (mi != mapBlockIndex.end())
3315 int nHeight = mi->second->nHeight;
3317 if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3318 if (!chainActive.
Contains(mi->second))
3320 LogPrintf(
"ProcessGetData(): ignoring request for old block that isn't in the main chain\n");
3348 typedef std::pair<unsigned int, uint256> PairType;
3349 BOOST_FOREACH(PairType& pair, merkleBlock.
vMatchedTxn)
3373 bool pushed =
false;
3376 map<CInv, CDataStream>::iterator mi =
mapRelay.find(inv);
3393 vNotFound.push_back(inv);
3407 if (!vNotFound.empty()) {
3422 LogPrint(
"net",
"received: %s (%u bytes)\n", strCommand, vRecv.
size());
3425 LogPrintf(
"dropmessagestest DROPPING RECV MESSAGE\n");
3436 if (strCommand ==
"version")
3449 uint64_t nNonce = 1;
3464 vRecv >> addrFrom >> nNonce;
3465 if (!vRecv.
empty()) {
3476 if (pfrom->
fInbound && addrMe.IsRoutable())
3535 LogPrintf(
"receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->
cleanSubVer, pfrom->
nVersion, pfrom->
nStartingHeight, addrMe.ToString(), addrFrom.
ToString(), pfrom->
addr.
ToString());
3549 else if (strCommand ==
"verack")
3555 else if (strCommand ==
"addr")
3557 vector<CAddress> vAddr;
3563 if (vAddr.size() > 1000)
3566 return error(
"message addr size() = %u", vAddr.size());
3570 vector<CAddress> vAddrOk;
3572 int64_t nSince = nNow - 10 * 60;
3573 BOOST_FOREACH(
CAddress& addr, vAddr)
3575 boost::this_thread::interruption_point();
3577 if (addr.
nTime <= 100000000 || addr.
nTime > nNow + 10 * 60)
3578 addr.
nTime = nNow - 5 * 24 * 60 * 60;
3591 uint64_t hashAddr = addr.
GetHash();
3592 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((
GetTime()+hashAddr)/(24*60*60));
3594 multimap<uint256, CNode*> mapMix;
3599 unsigned int nPointer;
3600 memcpy(&nPointer, &pnode,
sizeof(nPointer));
3601 uint256 hashKey = hashRand ^ nPointer;
3603 mapMix.insert(make_pair(hashKey, pnode));
3605 int nRelayNodes = fReachable ? 2 : 1;
3606 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3607 ((*mi).second)->PushAddress(addr);
3612 vAddrOk.push_back(addr);
3615 if (vAddr.size() < 1000)
3622 else if (strCommand ==
"inv")
3629 return error(
"message inv size() = %u", vInv.size());
3634 for (
unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3636 const CInv &inv = vInv[nInv];
3638 boost::this_thread::interruption_point();
3642 LogPrint(
"net",
" got inventory: %s %s\n", inv.
ToString(), fAlreadyHave ?
"have" :
"new");
3644 if (!fAlreadyHave) {
3647 AddBlockToQueue(pfrom->
GetId(), inv.
hash);
3666 else if (strCommand ==
"getdata")
3673 return error(
"message getdata size() = %u", vInv.size());
3676 if (
fDebug || (vInv.size() != 1))
3677 LogPrint(
"net",
"received getdata (%u invsz)\n", vInv.size());
3679 if ((
fDebug && vInv.size() > 0) || (vInv.size() == 1))
3680 LogPrint(
"net",
"received getdata for: %s\n", vInv[0].ToString());
3687 else if (strCommand ==
"getblocks")
3691 vRecv >> locator >> hashStop;
3700 pindex = chainActive.
Next(pindex);
3702 LogPrint(
"net",
"getblocks %d to %s limit %d\n", (pindex ? pindex->
nHeight : -1), hashStop.ToString(), nLimit);
3703 for (; pindex; pindex = chainActive.
Next(pindex))
3723 else if (strCommand ==
"getheaders")
3727 vRecv >> locator >> hashStop;
3735 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3736 if (mi == mapBlockIndex.end())
3738 pindex = (*mi).second;
3743 pindex = chainActive.
FindFork(locator);
3745 pindex = chainActive.
Next(pindex);
3749 vector<CBlock> vHeaders;
3751 LogPrint(
"net",
"getheaders %d to %s\n", (pindex ? pindex->
nHeight : -1), hashStop.ToString());
3752 for (; pindex; pindex = chainActive.
Next(pindex))
3755 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3762 else if (strCommand ==
"tx")
3764 vector<uint256> vWorkQueue;
3765 vector<uint256> vEraseQueue;
3774 bool fMissingInputs =
false;
3778 mempool.
check(pcoinsTip);
3781 vWorkQueue.push_back(inv.hash);
3782 vEraseQueue.push_back(inv.hash);
3785 LogPrint(
"mempool",
"AcceptToMemoryPool: %s %s : accepted %s (poolsz %u)\n",
3787 tx.GetHash().ToString(),
3788 mempool.
mapTx.size());
3791 set<NodeId> setMisbehaving;
3792 for (
unsigned int i = 0; i < vWorkQueue.size(); i++)
3794 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
3795 if (itByPrev == mapOrphanTransactionsByPrev.end())
3797 for (set<uint256>::iterator mi = itByPrev->second.begin();
3798 mi != itByPrev->second.end();
3801 const uint256& orphanHash = *mi;
3802 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
3803 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
3804 bool fMissingInputs2 =
false;
3810 vEraseQueue.push_back(orphanHash);
3812 if (setMisbehaving.count(fromPeer))
3819 vWorkQueue.push_back(orphanHash);
3821 else if (!fMissingInputs2)
3824 if (stateDummy.
IsInvalid(nDos) && nDos > 0)
3828 setMisbehaving.insert(fromPeer);
3834 mempool.
check(pcoinsTip);
3838 BOOST_FOREACH(
uint256 hash, vEraseQueue)
3841 else if (fMissingInputs)
3849 LogPrint(
"mempool",
"mapOrphan overflow, removed %u tx\n", nEvicted);
3854 LogPrint(
"mempool",
"%s from %s %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
3870 LogPrint(
"net",
"received block %s\n", block.GetHash().ToString());
3878 mapBlockSource[inv.hash] = pfrom->
GetId();
3879 MarkBlockAsReceived(inv.hash, pfrom->
GetId());
3886 else if (strCommand ==
"getaddr")
3890 BOOST_FOREACH(
const CAddress &addr, vAddr)
3895 else if (strCommand ==
"mempool")
3899 std::vector<uint256> vtxid;
3902 BOOST_FOREACH(
uint256& hash, vtxid) {
3905 bool fInMemPool = mempool.
lookup(hash, tx);
3906 if (!fInMemPool)
continue;
3909 vInv.push_back(inv);
3915 if (vInv.size() > 0)
3920 else if (strCommand ==
"ping")
3942 else if (strCommand ==
"pong")
3947 bool bPingFinished =
false;
3948 std::string sProblem;
3950 if (nAvail >=
sizeof(nonce)) {
3957 bPingFinished =
true;
3959 if (pingUsecTime > 0) {
3964 sProblem =
"Timing mishap";
3968 sProblem =
"Nonce mismatch";
3971 bPingFinished =
true;
3972 sProblem =
"Nonce zero";
3976 sProblem =
"Unsolicited pong without ping";
3980 bPingFinished =
true;
3981 sProblem =
"Short payload";
3984 if (!(sProblem.empty())) {
3985 LogPrint(
"net",
"pong %s %s: %s, %x expected, %x received, %u bytes\n",
3993 if (bPingFinished) {
3999 else if (strCommand ==
"alert")
4004 uint256 alertHash = alert.GetHash();
4005 if (pfrom->
setKnown.count(alertHash) == 0)
4007 if (alert.ProcessAlert())
4014 alert.RelayTo(pnode);
4030 else if (strCommand ==
"filterload")
4035 if (!filter.IsWithinSizeConstraints())
4049 else if (strCommand ==
"filteradd")
4051 vector<unsigned char> vData;
4069 else if (strCommand ==
"filterclear")
4078 else if (strCommand ==
"reject")
4082 string strMsg;
unsigned char ccode;
string strReason;
4086 ss << strMsg <<
" code " <<
itostr(ccode) <<
": " << strReason;
4088 if (strMsg ==
"block" || strMsg ==
"tx")
4092 ss <<
": hash " << hash.
ToString();
4106 if (strCommand ==
"version" || strCommand ==
"addr" || strCommand ==
"inv" || strCommand ==
"getdata" || strCommand ==
"ping")
4135 std::deque<CNetMessage>::iterator it = pfrom->
vRecvMsg.begin();
4158 LogPrintf(
"\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
4178 unsigned int nChecksum = 0;
4179 memcpy(&nChecksum, &hash,
sizeof(nChecksum));
4182 LogPrintf(
"ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4183 strCommand, nMessageSize, nChecksum, hdr.
nChecksum);
4192 boost::this_thread::interruption_point();
4194 catch (std::ios_base::failure& e)
4197 if (strstr(e.what(),
"end of data"))
4200 LogPrintf(
"ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand, nMessageSize, e.what());
4202 else if (strstr(e.what(),
"size too large"))
4205 LogPrintf(
"ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand, nMessageSize, e.what());
4212 catch (boost::thread_interrupted) {
4215 catch (std::exception& e) {
4222 LogPrintf(
"ProcessMessage(%s, %u bytes) FAILED\n", strCommand, nMessageSize);
4245 bool pingSend =
false;
4256 while (nonce == 0) {
4257 RAND_bytes((
unsigned char*)&nonce,
sizeof(nonce));
4277 static int64_t nLastRebroadcast;
4285 if (nLastRebroadcast)
4305 vector<CAddress> vAddr;
4312 vAddr.push_back(addr);
4314 if (vAddr.size() >= 1000)
4326 CNodeState &state = *State(pto->
GetId());
4327 if (state.fShouldBan) {
4334 state.fShouldBan =
false;
4337 BOOST_FOREACH(
const CBlockReject& reject, state.rejects)
4338 pto->
PushMessage(
"reject", (
string)
"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4339 state.rejects.clear();
4359 vector<CInv> vInvWait;
4378 bool fTrickleWait = ((hashRand & 3) != 0);
4382 vInvWait.push_back(inv);
4390 vInv.push_back(inv);
4391 if (vInv.size() >= 1000)
4412 LogPrintf(
"Peer %s is stalling block download, disconnecting\n", state.name.c_str());
4419 vector<CInv> vGetData;
4421 uint256 hash = state.vBlocksToDownload.front();
4423 MarkBlockAsInFlight(pto->
GetId(), hash);
4424 LogPrint(
"net",
"Requesting block %s from %s\n", hash.
ToString().c_str(), state.name.c_str());
4425 if (vGetData.size() >= 1000)
4442 vGetData.push_back(inv);
4443 if (vGetData.size() >= 1000)
4451 if (!vGetData.empty())
4469 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4470 for (; it1 != mapBlockIndex.end(); it1++)
4471 delete (*it1).second;
4472 mapBlockIndex.clear();
4475 std::map<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocks.begin();
4476 for (; it2 != mapOrphanBlocks.end(); it2++)
4477 delete (*it2).second;
4478 mapOrphanBlocks.clear();
4481 mapOrphanTransactions.clear();
4482 mapOrphanTransactionsByPrev.clear();
static void FlushBlockFile(bool fFinalize=false)
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
CClientUIInterface uiInterface
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
void PushMessage(const char *pszCommand)
uint64_t GetRand(uint64_t nMax)
bool IsDust(int64_t nMinRelayTxFee) const
int64_t GetValueOut() const
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
void check(CCoinsViewCache *pcoins) const
CDiskBlockPos GetBlockPos() const
static bool LoadBlockIndexDB()
CBigNum GetBlockWork() const
void TraverseAndBuild(int height, unsigned int pos, const std::vector< uint256 > &vTxid, const std::vector< bool > &vMatch)
static uint32_t insecure_rand(void)
bool fLargeWorkInvalidChainFound
static void FindMostWorkChain()
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule) ...
CCriticalSection cs_filter
bool AreInputsStandard(const CTransaction &tx, CCoinsViewCache &mapInputs)
Check for standard transaction types.
void Add(std::vector< T > &vChecks)
bool AddOrphanTx(const CTransaction &tx, NodeId peer)
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
int mastercore_handler_block_begin(int nBlockNow, CBlockIndex const *pBlockIndex)
const_iterator begin() const
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
bool lookup(uint256 hash, CTransaction &result) const
virtual void SetBestChain(const CBlockLocator &locator)=0
const char * GetCommand() const
#define TRY_LOCK(cs, name)
void SetBackend(CCoinsView &viewIn)
unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
Calculate the minimum amount of work a received block needs, without knowing its direct parent...
void FileCommit(FILE *fileout)
void swap(CScriptCheck &check)
std::vector< CTxOut > vout
unsigned int nTransactions
uint256 getuint256() const
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
bool ReadReindexing(bool &fReindex)
An in-memory indexed chain of blocks.
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE
Default for -blockprioritysize, maximum space for zero/low-fee transactions.
bool IsPayToScriptHash() const
bool ReadLastBlockFile(int &nFile)
int GetDepthInMainChainINTERNAL(CBlockIndex *&pindexRet) const
std::map< COutPoint, CInPoint > mapNextTx
static CCheckQueue< CScriptCheck > scriptcheckqueue(128)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
std::pair< iterator, bool > insert(const key_type &x)
void AskFor(const CInv &inv)
virtual void Inventory(const uint256 &hash)=0
bool CorruptionPossible() const
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
const CBigNum & ProofOfWorkLimit() const
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
static const int CLIENT_VERSION
void ThreadScriptCheck()
Run an instance of the script checking thread.
unsigned int GetSizeOfCompactSize(uint64_t nSize)
static const unsigned char REJECT_CHECKPOINT
static const int BIP0031_VERSION
bool VerifyDB(int nCheckLevel, int nCheckDepth)
Verify consistency of the block and coin databases.
string GetWarnings(string strFor)
Format a string that describes several potential problems detected by the core.
uint256 hashLastGetBlocksEnd
CBlockIndex * GetLastCheckpoint(const std::map< uint256, CBlockIndex * > &mapBlockIndex)
static bool ProcessMessage(CNode *pfrom, string strCommand, CDataStream &vRecv)
limitedmap< CInv, int64_t > mapAlreadyAskedFor(MAX_INV_SZ)
void queryHashes(std::vector< uint256 > &vtxid)
int64_t GetMinFee(const CTransaction &tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode)
bool AddToBlockIndex(CBlock &block, CValidationState &state, const CDiskBlockPos &pos)
bool WriteBlockIndex(const CDiskBlockIndex &blockindex)
bool MoneyRange(int64_t nValue)
static const unsigned char REJECT_OBSOLETE
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Double ended buffer combining vector and stream-like interfaces.
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Data structure that represents a partial merkle tree.
static const unsigned int BLOCK_DOWNLOAD_TIMEOUT
Timeout in seconds before considering a block download peer unresponsive.
CCriticalSection cs_inventory
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
static void InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state)
bool SeenLocal(const CService &addr)
vote for a local address
std::vector< CAddress > vAddrToSend
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
unsigned int GetSerializeSize(const T &obj)
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0)
void AddAddressKnown(const CAddress &addr)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
void CheckForkWarningConditions()
bool LoadBlockIndexGuts()
int mastercore_handler_disc_end(int nBlockNow, CBlockIndex const *pBlockIndex)
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
void RandAddSeedPerfmon()
static int64_t nMinTxFee
Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) ...
virtual void SyncTransaction(const uint256 &hash, const CTransaction &tx, const CBlock *pblock)=0
void SetRecvVersion(int nVersionIn)
void RenameThread(const char *name)
const string strMessageMagic
CChain chainActive
The currently-connected chain of blocks.
Undo information for a CTxIn.
size_type count(const key_type &k) const
void PushInventory(const CInv &inv)
bool GetCoins(const uint256 &txid, CCoins &coins)
void PrintBlockTree()
Print the loaded block tree.
static const int64_t nInterval
void insert(const uint256 &hash)
bool IsAvailable(unsigned int nPos) const
std::deque< CInv > vRecvGetData
int ScriptSigArgsExpected(txnouttype t, const std::vector< std::vector< unsigned char > > &vSolutions)
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
bool Invalid(bool ret=false, unsigned char _chRejectCode=0, std::string _strRejectReason="")
std::set< uint256 > setKnown
uint256 BuildMerkleTree() const
int GetDepthInMainChain() const
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
void UpdateTime(CBlockHeader &block, const CBlockIndex *pindexPrev)
bool VerifySignature(const CCoins &txFrom, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Verify a signature.
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee)
(try to) add transaction to memory pool
#define AssertLockHeld(cs)
std::vector< CAddress > GetAddr()
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
class CMainCleanup instance_of_cmaincleanup
int GetBlocksToMaturity() const
std::vector< uint256 > GetMerkleBranch(int nIndex) const
CBigNum & SetCompact(unsigned int nCompact)
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
#define CLIENT_VERSION_IS_RELEASE
std::deque< CNetMessage > vRecvMsg
std::vector< uint256 > vHash
int Height() const
Return the maximal height in the chain.
int mastercore_handler_disc_begin(int nBlockNow, CBlockIndex const *pBlockIndex)
Used to relay blocks as header + vector to filtered nodes.
static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS
Default for -maxorphanblocks, maximum number of orphan blocks kept in memory.
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
unsigned int CalcTreeWidth(int height)
bool TruncateFile(FILE *file, unsigned int length)
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
int64_t GetAdjustedTime()
static const unsigned int MAX_BLOCK_SIGOPS
The maximum allowed number of signature check operations in a block (network rule) ...
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip...
void AddTimeData(const CNetAddr &ip, int64_t nTime)
void EraseOrphansFor(NodeId peer)
Access to the block database (blocks/index/)
CBlockHeader GetBlockHeader() const
string SanitizeString(const string &str)
unsigned int GetSerializeSize(char a, int, int=0)
Abstract view on the open txout dataset.
void PushGetBlocks(CNode *pnode, CBlockIndex *pindexBegin, uint256 hashEnd)
static int LogPrint(const char *category, const char *format)
bool HaveCoins(const uint256 &txid)
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
An input of a transaction.
An alert is a combination of a serialized CUnsignedAlert and a signature.
std::string itostr(int n)
void AddressCurrentlyConnected(const CService &addr)
mruset< CAddress > setAddrKnown
#define MESSAGE_START_SIZE
unsigned int GetSigOpCount(bool fAccurate) const
bool HaveInputs(const CTransaction &tx)
bool AcceptBlock(CBlock &block, CValidationState &state, CDiskBlockPos *dbp)
std::vector< CTxOut > vout
void UnloadBlockIndex()
Unload database information.
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
bool SendMessages(CNode *pto, bool fSendTrickle)
Send queued protocol messages to be sent to a give node.
static bool WriteChainState(CValidationState &state)
bool IsReachable(const CNetAddr &addr)
check whether a given address is in a network we can probably connect to
CBlockHeader GetBlockHeader() const
CBlockIndex * pindexLastGetBlocksBegin
bool ActivateBestChain(CValidationState &state)
Find the best known block, and make it the tip of the block chain.
static bool error(const char *format)
bool DoS(int level, bool ret=false, unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", bool corruptionIn=false)
int64_t GetMedianTime() const
C++ wrapper for BIGNUM (OpenSSL bignum)
mruset< CInv > setInventoryKnown
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
A CService with information about it as peer.
unsigned int SendBufferSize()
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock)
bool LoadBlockIndex()
Load the block tree and coins database from disk.
static const unsigned int MAX_BLOCK_SIZE
The maximum allowed size for a serialized block, in bytes (network rule)
bool AcceptToMemoryPool(bool fLimitFree=true)
const CTxOut & GetOutputFor(const CTxIn &input)
void RelayTransaction(const CTransaction &tx, const uint256 &hash)
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, vector< vector< unsigned char > > &vSolutionsRet)
bool fSuccessfullyConnected
map< uint256, CAlert > mapAlerts
std::map< uint256, CTxMemPoolEntry > mapTx
bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo)
bool Error(std::string strRejectReasonIn="")
std::string ToString() const
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
static void InvalidChainFound(CBlockIndex *pindexNew)
std::vector< uint256 > vMerkleTree
CCriticalSection cs_mapAlerts
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch)
int GetTotalBlocksEstimate()
void PrintExceptionContinue(std::exception *pex, const char *pszThread)
uint256 Hash(const T1 pbegin, const T1 pend)
An output of a transaction.
Used to marshal pointers into hashes for db storage.
bool WriteBlockToDisk(CBlock &block, CDiskBlockPos &pos)
Functions for disk access for blocks.
std::vector< uint256 > vHave
int SubsidyHalvingInterval() const
bool ConnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck)
bool EvalScript(vector< vector< unsigned char > > &stack, const CScript &script, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
bool CheckBlock(int nHeight, const uint256 &hash)
static uint256 GetOrphanRoot(const uint256 &hash)
bool WriteLastBlockFile(int nFile)
bool SetPos(uint64_t nPos)
Queue for verifications that have to be performed.
An outpoint - a combination of a transaction hash and an index n into its vout.
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
void AddTransactionsUpdated(unsigned int n)
std::vector< CTxInUndo > vprevout
bool Abort(const std::string &msg)
std::string GetHex() const
boost::signals2::signal< bool(CNode *, bool)> SendMessages
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks)
void RegisterWallet(CWalletInterface *pwalletIn)
Register a wallet to receive updates from core.
bool DisconnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
Functions for validating blocks and updating the block tree.
map< uint256, COrphanTx > mapOrphanTransactions
bool ProcessMessages(CNode *pfrom)
Process protocol messages received from a given node.
void remove(const CTransaction &tx, std::list< CTransaction > &removed, bool fRecursive=false)
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
static const unsigned char REJECT_MALFORMED
"reject" message codes
bool ReadFlag(const std::string &name, bool &fValue)
virtual const CBlock & GenesisBlock() const =0
boost::signals2::signal< bool(CNode *)> ProcessMessages
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Closure representing one script verification Note that this stores references to the spending transac...
static void EraseOrphanTx(uint256 hash)
void removeConflicts(const CTransaction &tx, std::list< CTransaction > &removed)
std::vector< bool > vBits
const uint256 & GetTxHash(unsigned int nIndex) const
std::string GetRejectReason() const
unsigned char GetRejectCode() const
bool IsStandardTx(const CTransaction &tx, string &reason)
Check for standard transaction types.
CChain chainMostWork
The currently best known chain of headers (some of which may be invalid).
boost::signals2::signal< int()> GetHeight
unsigned int GetP2SHSigOpCount(const CTransaction &tx, CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Capture information about block/transaction validation.
void AddInventoryKnown(const CInv &inv)
static const unsigned char REJECT_INVALID
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot)
static const int64_t COIN
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock)
Push an updated transaction to all registered wallets.
int64_t nTimeBestReceived
int mastercore_handler_tx(const CTransaction &tx, int nBlock, unsigned int idx, CBlockIndex const *pBlockIndex)
CCriticalSection cs_mapRelay
static void UpdateTip(CBlockIndex *pindexNew)
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
bool RelayTo(CNode *pnode) const
bool Spend(const COutPoint &out, CTxInUndo &undo)
CBlockIndex * pindexBestForkBase
double GetPriority(const CTransaction &tx, int nHeight)
int64_t GetBlockValue(int nHeight, int64_t nFees)
bool IsRelevantAndUpdate(const CTransaction &tx, const uint256 &hash)
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
void reserve(size_type n)
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
bool CheckInputs(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector< CScriptCheck > *pvChecks)
Undo information for a CBlock.
Serialized script, used inside transaction inputs and outputs.
std::vector< CInv > vInventoryToSend
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry)
Undo information for a CTransaction.
void * memcpy(void *a, const void *b, size_t c)
unsigned int nCoinCacheSize
static void ProcessGetData(CNode *pfrom)
std::string ToString() const
static const int MIN_PEER_PROTO_VERSION
static const int PROTOCOL_VERSION
static const unsigned char REJECT_INSUFFICIENTFEE
static const unsigned char REJECT_NONSTANDARD
CBlockIndex * FindFork(const CBlockLocator &locator) const
Find the last common block between this chain and a locator.
static bool AlreadyHave(const CInv &inv)
static const unsigned int LOCKTIME_THRESHOLD
Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timest...
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
void Misbehaving(NodeId pnode, int howmuch)
Increase a node's misbehavior score.
boost::signals2::signal< void()> NotifyBlocksChanged
Block chain changed.
bool exists(uint256 hash)
bool AbortNode(const std::string &strMessage)
Abort with a message.
#define LIMITED_STRING(obj, n)
static bool DisconnectTip(CValidationState &state)
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
static const int CADDR_TIME_VERSION
static uint256 CheckMerkleBranch(uint256 hash, const std::vector< uint256 > &vMerkleBranch, int nIndex)
CBlockIndex * SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
void UnregisterAllWallets()
Unregister all wallets from core.
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
Retrieve a transaction (from memory pool, or from disk, if possible)
CMerkleBlock(const CBlock &block, CBloomFilter &filter)
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
static bool Ban(const CNetAddr &ip)
bool IsStandard(const CScript &scriptPubKey, txnouttype &whichType)
int64_t GetValueIn(const CTransaction &tx)
Amount of bitcoins coming in to a transaction Note that lightweight clients may not know anything bes...
static const int64_t nTargetTimespan
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
static int64_t nMinRelayTxFee
Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) ...
virtual void UpdatedTransaction(const uint256 &hash)=0
static const int64_t CENT
virtual void EraseFromWallet(const uint256 &hash)=0
static const unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we're willing to relay/mine.
bool WriteFlag(const std::string &name, bool fValue)
void UnregisterWallet(CWalletInterface *pwalletIn)
Unregister a wallet from core.
bool SetCoins(const uint256 &txid, const CCoins &coins)
CBlockIndex * pindexBestForkTip
std::vector< CTransaction > vtx
unsigned int GetCompact() const
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
int mastercore_handler_block_end(int nBlockNow, CBlockIndex const *pBlockIndex, unsigned int)
bool SetBestBlock(const uint256 &hashBlock)
unsigned int GetCacheSize()
static bool ConnectTip(CValidationState &state, CBlockIndex *pindexNew)
CDiskBlockPos GetUndoPos() const
vector< unsigned char > vchBlock
The basic transaction that is broadcasted on the network and contained in blocks. ...
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
Information about a peer.
static const int CURRENT_VERSION
static const unsigned char REJECT_DUPLICATE
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
Open an undo file (rev?????.dat)
boost::signals2::signal< void(NodeId)> FinalizeNode
CCoinsView that adds a memory cache for transactions to another CCoinsView.
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
virtual void ResendWalletTransactions()=0
std::string ToString() const
Wrapper around a FILE* that implements a ring buffer to deserialize from.
int64_t GetBlockTime() const
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
std::vector< CTxUndo > vtxundo
multimap< uint256, COrphanBlock * > mapOrphanBlocksByPrev
map< uint256, COrphanBlock * > mapOrphanBlocks
bool HasCanonicalPushes() const
static void PruneOrphanBlocks()
boost::signals2::signal< void(NodeId, const CNode *)> InitializeNode
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
int64_t GetMedianTimePast() const
CCoinsView that brings transactions from a memorypool into view.
map< uint256, CBlockIndex * > mapBlockIndex
std::multimap< int64_t, CInv > mapAskFor
CCriticalSection cs_vNodes
static const int64_t nTargetSpacing
map< uint256, set< uint256 > > mapOrphanTransactionsByPrev
bool CheckTransaction(const CTransaction &tx, CValidationState &state)
const uint256 & HashGenesisBlock() const
static CNodeSignals g_signals
map< string, string > mapArgs
map< CInv, CDataStream > mapRelay
int atoi(const std::string &str)
uint256 GetBlockHash() const
std::deque< CSerializeData > vSendMsg
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
const_iterator end() const
void runCommand(std::string strCommand)
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
uint256 CalcHash(int height, unsigned int pos, const std::vector< uint256 > &vTxid)
static bool IsSuperMajority(int minVersion, const CBlockIndex *pstart, unsigned int nRequired, unsigned int nToCheck)
Returns true if there are nRequired or more blocks of minVersion or above in the last nToCheck blocks...
void PushAddress(const CAddress &addr)
void Good(const CService &addr, int64_t nTime=GetAdjustedTime())
bool WriteBestInvalidWork(const CBigNum &bnBestInvalidWork)
const uint256 * phashBlock
static const uint64_t nMinDiskSpace
static const int64_t MAX_MONEY
No amount larger than this (in satoshi) is valid.