18 #include <boost/algorithm/string/replace.hpp>
19 #include <boost/filesystem.hpp>
20 #include <boost/filesystem/fstream.hpp>
23 using namespace boost;
99 LOCK(cs_setpwalletRegistered);
107 LOCK(cs_setpwalletRegistered);
125 pwallet->EraseFromWallet(hash);
143 void static UpdatedTransaction(const
uint256& hashTx)
146 pwallet->UpdatedTransaction(hashTx);
150 void static PrintWallets(const
CBlock& block)
153 pwallet->PrintWallet(block);
157 void static Inventory(const
uint256& hash)
160 pwallet->Inventory(hash);
164 void static ResendWalletTransactions()
167 pwallet->ResendWalletTransactions();
215 std::map<uint256,CCoins>::iterator it =
cacheCoins.lower_bound(txid);
216 if (it !=
cacheCoins.end() && it->first == txid)
221 std::map<uint256,CCoins>::iterator ret =
cacheCoins.insert(it, std::make_pair(txid,
CCoins()));
222 tmp.
swap(ret->second);
227 std::map<uint256,CCoins>::iterator it =
FetchCoins(txid);
253 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
277 if (mempool.
exists(txid)) {
279 coins =
CCoins(tx, MEMPOOL_HEIGHT);
300 if (mapOrphanTransactions.count(hash))
313 printf(
"ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.
ToString().c_str());
317 mapOrphanTransactions[
hash] = tx;
318 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
319 mapOrphanTransactionsByPrev[txin.
prevout.
hash].insert(hash);
322 mapOrphanTransactions.size());
326 void static EraseOrphanTx(
uint256 hash)
328 if (!mapOrphanTransactions.count(hash))
331 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
333 mapOrphanTransactionsByPrev[txin.
prevout.
hash].erase(hash);
334 if (mapOrphanTransactionsByPrev[txin.
prevout.
hash].empty())
335 mapOrphanTransactionsByPrev.erase(txin.
prevout.
hash);
337 mapOrphanTransactions.erase(hash);
342 unsigned int nEvicted = 0;
343 while (mapOrphanTransactions.size() > nMaxOrphans)
347 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
348 if (it == mapOrphanTransactions.end())
349 it = mapOrphanTransactions.begin();
350 EraseOrphanTx(it->first);
377 strReason =
"version";
382 strReason =
"not-final";
391 if (sz >= MAX_STANDARD_TX_SIZE) {
392 strReason =
"tx-size";
396 BOOST_FOREACH(
const CTxIn& txin,
vin)
402 strReason =
"scriptsig-size";
406 strReason =
"scriptsig-not-pushonly";
412 strReason =
"scriptpubkey";
439 for (
unsigned int i = 0; i <
vin.size(); i++)
443 vector<vector<unsigned char> > vSolutions;
447 if (!
Solver(prevScript, whichType, vSolutions))
450 if (nArgsExpected < 0)
458 vector<vector<unsigned char> > stack;
459 if (!
EvalScript(stack,
vin[i].scriptSig, *
this, i,
false, 0))
466 CScript subscript(stack.back().begin(), stack.back().end());
467 vector<vector<unsigned char> > vSolutions2;
469 if (!
Solver(subscript, whichType2, vSolutions2))
478 nArgsExpected += tmpExpected;
481 if (stack.size() != (
unsigned int)nArgsExpected)
490 unsigned int nSigOps = 0;
491 BOOST_FOREACH(
const CTxIn& txin,
vin)
503 int CMerkleTx::SetMerkleBranch(
const CBlock* pblock)
507 if (pblock == NULL) {
531 printf(
"ERROR: SetMerkleBranch() : couldn't find tx in block\n");
560 return state.
DoS(10,
error(
"CTransaction::CheckTransaction() : vin empty"));
562 return state.
DoS(10,
error(
"CTransaction::CheckTransaction() : vout empty"));
565 return state.
DoS(100,
error(
"CTransaction::CheckTransaction() : size limits failed"));
572 return state.
DoS(100,
error(
"CTransaction::CheckTransaction() : txout.nValue negative"));
573 if (txout.
nValue > MAX_MONEY)
574 return state.
DoS(100,
error(
"CTransaction::CheckTransaction() : txout.nValue too high"));
575 nValueOut += txout.
nValue;
577 return state.
DoS(100,
error(
"CTransaction::CheckTransaction() : txout total out of range"));
581 set<COutPoint> vInOutPoints;
582 BOOST_FOREACH(
const CTxIn& txin,
vin)
584 if (vInOutPoints.count(txin.
prevout))
585 return state.
DoS(100,
error(
"CTransaction::CheckTransaction() : duplicate inputs"));
586 vInOutPoints.insert(txin.
prevout);
591 if (
vin[0].scriptSig.size() < 2 ||
vin[0].scriptSig.size() > 100)
592 return state.
DoS(100,
error(
"CTransaction::CheckTransaction() : coinbase script size"));
596 BOOST_FOREACH(
const CTxIn& txin,
vin)
598 return state.
DoS(10,
error(
"CTransaction::CheckTransaction() : prevout is null"));
611 unsigned int nNewBlockSize = nBlockSize + nBytes;
612 int64 nMinFee = (1 + (
int64)nBytes / 1000) * nBaseFee;
622 if (nBytes < (mode ==
GMF_SEND ? 5000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
629 if (txout.
nValue < DUST_SOFT_LIMIT)
633 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
635 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
637 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
649 std::map<COutPoint, CInPoint>::iterator it =
mapNextTx.lower_bound(
COutPoint(hashTx, 0));
652 while (it !=
mapNextTx.end() && it->first.hash == hashTx) {
653 coins.
Spend(it->first.n);
659 bool* pfMissingInputs)
662 *pfMissingInputs =
false;
665 return error(
"CTxMemPool::accept() : CheckTransaction failed");
669 return state.
DoS(100,
error(
"CTxMemPool::accept() : coinbase as individual tx"));
673 return error(
"CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
678 return error(
"CTxMemPool::accept() : nonstandard transaction (%s)",
685 if (
mapTx.count(hash))
691 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
707 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
734 BOOST_FOREACH(
const CTxIn txin, tx.
vin) {
737 *pfMissingInputs =
true;
744 return state.
Invalid(
error(
"CTxMemPool::accept() : inputs already spent"));
755 return error(
"CTxMemPool::accept() : nonstandard transaction input");
766 if (fLimitFree && nFees < txMinFee)
774 if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
776 static double dFreeCount;
777 static int64 nLastTime;
783 dFreeCount *= pow(1.0 - 1.0/600.0, (
double)(nNow - nLastTime));
787 if (dFreeCount >=
GetArg(
"-limitfreerelay", 15)*10*1000)
788 return error(
"CTxMemPool::accept() : free transaction rejected by rate limiter");
790 printf(
"Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
798 return error(
"CTxMemPool::accept() : ConnectInputs failed %s", hash.
ToString().c_str());
807 printf(
"CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->
GetHash().
ToString().c_str());
816 EraseFromWallets(ptxOld->
GetHash());
825 return mempool.
accept(state, *
this, fCheckInputs, fLimitFree, pfMissingInputs);
826 }
catch(std::runtime_error &e) {
827 return state.
Abort(
_(
"System error: ") + e.what());
837 for (
unsigned int i = 0; i < tx.
vin.size(); i++)
852 for (
unsigned int i = 0; i < tx.
vout.size(); i++) {
855 remove(*it->second.ptx,
true);
858 if (
mapTx.count(hash))
860 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
873 BOOST_FOREACH(
const CTxIn &txin, tx.
vin) {
877 if (txConflict != tx)
878 remove(txConflict,
true);
897 vtxid.reserve(
mapTx.size());
898 for (map<uint256, CTransaction>::iterator mi =
mapTx.begin(); mi !=
mapTx.end(); ++mi)
899 vtxid.push_back((*mi).first);
977 txOut = mempool.
lookup(hash);
991 }
catch (std::exception &e) {
992 return error(
"%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
996 return error(
"%s() : txid mismatch", __PRETTY_FUNCTION__);
1044 if (nHeight < nBestHeight / 2)
1048 if (pblockindexFBBHLast && abs(nHeight - pblockindex->
nHeight) > abs(nHeight - pblockindexFBBHLast->
nHeight))
1049 pblockindex = pblockindexFBBHLast;
1050 while (pblockindex->
nHeight > nHeight)
1051 pblockindex = pblockindex->
pprev;
1052 while (pblockindex->
nHeight < nHeight)
1053 pblockindex = pblockindex->
pnext;
1054 pblockindexFBBHLast = pblockindex;
1063 return error(
"CBlock::ReadFromDisk() : GetHash() doesn't match index");
1075 int64 static GetBlockValue(
int nHeight,
int64 nFees)
1077 int64 nSubsidy = 200 * COIN;
1079 if(nHeight >= nForkThree || (
fTestNet))
1080 nSubsidy = 80 * COIN;
1084 nSubsidy >>= (nHeight + 306960) / 2100000;
1086 return nSubsidy + nFees;
1094 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.
GetCompact();
1097 if (pindexLast == NULL)
1098 return nProofOfWorkLimit;
1101 int nHeight = pindexLast->
nHeight + 1;
1103 if (nHeight >= nForkOne)
1104 nTargetTimespan = (7 * 24 * 60 * 60) / 8;
1106 if (nHeight >= nForkTwo)
1107 nTargetTimespan = (7 * 24 * 60 * 60) / 32;
1109 if (nHeight >= nForkThree ||
fTestNet) {
1110 nTargetTimespan = 60;
1111 nTargetSpacing = 60;
1117 bool fHardFork = (nHeight ==
nForkOne) || (nHeight == nForkTwo) || (nHeight ==
nForkThree);
1121 if((nHeight % nInterval != 0) && !(fHardFork) && (nHeight < nForkThree)) {
1128 if (pblock->
nTime > pindexLast->
nTime + nTargetSpacing*2)
1129 return nProofOfWorkLimit;
1134 while (pindex->
pprev && pindex->
nHeight % nInterval != 0 && pindex->
nBits == nProofOfWorkLimit)
1135 pindex = pindex->
pprev;
1136 return pindex->
nBits;
1140 return pindexLast->
nBits;
1144 if(nInterval >= nHeight) nInterval = nHeight - 1;
1148 for(
int i = 0; pindexFirst && i < nInterval; i++)
1149 pindexFirst = pindexFirst->
pprev;
1150 assert(pindexFirst);
1154 printf(
"RETARGET: nActualTimespan = %d before bounds\n", nActualTimespan);
1157 if((nHeight >= nForkTwo) && (nHeight < nForkThree)) {
1161 for(
int i = 0; pindexFirst && i < nInterval; i++)
1162 pindexFirst = pindexFirst->
pprev;
1164 int nActualTimespanLong =
1168 int nActualTimespanAvg = (nActualTimespan + nActualTimespanLong)/2;
1172 nActualTimespan /= 4;
1174 printf(
"RETARGET: nActualTimespanLong = %d, nActualTimeSpanAvg = %d, nActualTimespan (damped) = %d\n",
1175 nActualTimespanLong, nActualTimespanAvg, nActualTimespan);
1179 if((nHeight >= nForkThree) ||
fTestNet) {
1183 int pindexFirstShortTime = 0;
1184 int pindexFirstMediumTime = 0;
1186 for(
int i = 0; pindexFirstLong && i < nInterval && i < nHeight - 1; i++) {
1187 pindexFirstLong = pindexFirstLong->
pprev;
1189 pindexFirstShortTime = pindexFirstLong->
GetBlockTime();
1192 pindexFirstMediumTime = pindexFirstLong->
GetBlockTime();
1196 int nActualTimespanShort =
1197 (pindexLast->
GetBlockTime() - pindexFirstShortTime)/15;
1199 int nActualTimespanMedium =
1200 (pindexLast->
GetBlockTime() - pindexFirstMediumTime)/120;
1202 int nActualTimespanLong =
1205 int nActualTimespanAvg = 0;
1206 nActualTimespanAvg = (nActualTimespanShort + nActualTimespanMedium + nActualTimespanLong)/3;
1210 nActualTimespan /= 4;
1212 printf(
"RETARGET: nActualTimespanShort = %d, nActualTimespanMedium = %d, nActualTimespanLong = %d, nActualTimeSpanAvg = %d, nActualTimespan (damped) = %d\n",
1213 nActualTimespanShort, nActualTimespanMedium, nActualTimespanLong, nActualTimespanAvg, nActualTimespan);
1217 int nActualTimespanMax = nTargetTimespan*4;
1218 int nActualTimespanMin = nTargetTimespan/4;
1221 if(nHeight >= nForkOne) {
1222 nActualTimespanMax = nTargetTimespan*99/70;
1223 nActualTimespanMin = nTargetTimespan*70/99;
1227 if(nHeight >= nForkTwo ||
fTestNet) {
1228 nActualTimespanMax = nTargetTimespan*494/453;
1229 nActualTimespanMin = nTargetTimespan*453/494;
1232 if(nActualTimespan < nActualTimespanMin) nActualTimespan = nActualTimespanMin;
1233 if(nActualTimespan > nActualTimespanMax) nActualTimespan = nActualTimespanMax;
1235 printf(
"RETARGET: nActualTimespan = %d after bounds\n", nActualTimespan);
1236 printf(
"RETARGET: nTargetTimespan = %d, nTargetTimespan/nActualTimespan = %.4f\n", nTargetTimespan, (
float) nTargetTimespan/nActualTimespan);
1241 bnNew *= nActualTimespan;
1244 if (bnNew > bnProofOfWorkLimit)
1245 bnNew = bnProofOfWorkLimit;
1247 printf(
"GetNextWorkRequired RETARGET\n");
1260 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1261 return error(
"CheckProofOfWork() : nBits below minimum work");
1265 return error(
"CheckProofOfWork() : hash doesn't match nBits");
1280 static int64 nLastUpdate;
1282 if (pindexBest != pindexLastBest)
1287 return (
GetTime() - nLastUpdate < 10 &&
1291 void static InvalidChainFound(
CBlockIndex* pindexNew)
1293 if (pindexNew->
nChainWork > nBestInvalidWork)
1299 printf(
"InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1303 printf(
"InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1306 if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->
GetBlockWork() * 6).getuint256())
1307 printf(
"InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1310 void static InvalidBlockFound(
CBlockIndex *pindex) {
1313 setBlockIndexValid.erase(pindex);
1314 InvalidChainFound(pindex);
1315 if (pindex->
pnext) {
1326 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1327 if (it == setBlockIndexValid.rend())
1329 pindexNewBest = *it;
1332 if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->
nChainWork == pindexBest->
nChainWork))
1337 std::vector<CBlockIndex*> vAttach;
1342 while (pindexTest != pindexFailed) {
1344 setBlockIndexValid.erase(pindexFailed);
1346 pindexFailed = pindexFailed->
pprev;
1348 InvalidChainFound(pindexNewBest);
1353 vAttach.push_back(pindexTest);
1355 if (pindexTest->
pprev == NULL || pindexTest->
pnext != NULL) {
1356 reverse(vAttach.begin(), vAttach.end());
1357 BOOST_FOREACH(
CBlockIndex *pindexSwitch, vAttach) {
1358 boost::this_thread::interruption_point();
1362 }
catch(std::runtime_error &e) {
1363 return state.
Abort(
_(
"System error: ") + e.what());
1368 pindexTest = pindexTest->
pprev;
1379 nBits = GetNextWorkRequired(pindexPrev,
this);
1405 for (
unsigned int i = 0; i <
vin.size(); i++)
1416 unsigned int nSigOps = 0;
1417 for (
unsigned int i = 0; i <
vin.size(); i++)
1430 BOOST_FOREACH(
const CTxIn &txin,
vin) {
1446 for (
unsigned int i = 0; i <
vin.size(); i++) {
1453 for (
unsigned int i = 0; i <
vin.size(); i++) {
1472 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1480 pvChecks->reserve(
vin.size());
1492 for (
unsigned int i = 0; i <
vin.size(); i++)
1499 if (nSpendHeight - coins.
nHeight < COINBASE_MATURITY)
1500 return state.
Invalid(
error(
"CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.
nHeight));
1504 nValueIn += coins.
vout[prevout.
n].nValue;
1506 return state.
DoS(100,
error(
"CheckInputs() : txin values out of range"));
1519 return state.
DoS(100,
error(
"CheckInputs() : nFees out of range"));
1528 if (fScriptChecks) {
1529 for (
unsigned int i = 0; i <
vin.size(); i++) {
1537 check.
swap(pvChecks->back());
1538 }
else if (!check()) {
1542 CScriptCheck check(coins, *
this, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
1546 return state.
DoS(100,
false);
1570 return error(
"DisconnectBlock() : no undo data available");
1572 return error(
"DisconnectBlock() : failure reading undo data");
1574 if (blockUndo.
vtxundo.size() + 1 !=
vtx.size())
1575 return error(
"DisconnectBlock() : block and undo data inconsistent");
1578 for (
int i =
vtx.size() - 1; i >= 0; i--) {
1584 fClean = fClean &&
error(
"DisconnectBlock() : outputs still spent? database corrupted");
1595 if (outs != outsBlock)
1596 fClean = fClean &&
error(
"DisconnectBlock() : added transaction mismatch? database corrupted");
1605 return error(
"DisconnectBlock() : transaction and undo data inconsistent");
1606 for (
unsigned int j = tx.
vin.size(); j-- > 0;) {
1614 fClean = fClean &&
error(
"DisconnectBlock() : undo data overwriting existing transaction");
1621 fClean = fClean &&
error(
"DisconnectBlock() : undo data adding output to missing transaction");
1624 fClean = fClean &&
error(
"DisconnectBlock() : undo data overwriting existing output");
1625 if (coins.
vout.size() < out.
n+1)
1626 coins.
vout.resize(out.
n+1);
1629 return error(
"DisconnectBlock() : cannot restore coin inputs");
1645 void static FlushBlockFile(
bool fFinalize =
false)
1674 scriptcheckqueue.Thread();
1680 if (!
CheckBlock(state, !fJustCheck, !fJustCheck))
1690 pindexGenesisBlock = pindex;
1707 bool fEnforceBIP30 =
true;
1709 if (fEnforceBIP30) {
1710 for (
unsigned int i=0; i<
vtx.size(); i++) {
1713 return state.
DoS(100,
error(
"ConnectBlock() : tried to overwrite transaction"));
1718 int64 nBIP16SwitchTime = 1349049600;
1719 bool fStrictPayToScriptHash = (pindex->
nTime >= nBIP16SwitchTime);
1731 unsigned int nSigOps = 0;
1733 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1734 vPos.reserve(
vtx.size());
1735 for (
unsigned int i=0; i<
vtx.size(); i++)
1739 nInputs += tx.
vin.size();
1741 if (nSigOps > MAX_BLOCK_SIGOPS)
1742 return state.
DoS(100,
error(
"ConnectBlock() : too many sigops"));
1747 return state.
DoS(100,
error(
"ConnectBlock() : inputs missing/spent"));
1749 if (fStrictPayToScriptHash)
1755 if (nSigOps > MAX_BLOCK_SIGOPS)
1756 return state.
DoS(100,
error(
"ConnectBlock() : too many sigops"));
1761 std::vector<CScriptCheck> vChecks;
1762 if (!tx.
CheckInputs(state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1764 control.
Add(vChecks);
1770 blockundo.
vtxundo.push_back(txundo);
1772 vPos.push_back(std::make_pair(
GetTxHash(i), pos));
1777 printf(
"- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (
unsigned)
vtx.size(), 0.001 *
nTime, 0.001 * nTime /
vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
1779 if (
vtx[0].GetValueOut() > GetBlockValue(pindex->
nHeight, nFees))
1780 return state.
DoS(100,
error(
"ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")",
vtx[0].GetValueOut(), GetBlockValue(pindex->
nHeight, nFees)));
1784 (
vtx[0].GetValueOut() != GetBlockValue(pindex->
nHeight, nFees)))
1787 if (!control.
Wait())
1788 return state.
DoS(100,
false);
1791 printf(
"- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1802 return error(
"ConnectBlock() : FindUndoPos failed");
1804 return state.
Abort(
_(
"Failed to write undo data"));
1815 return state.
Abort(
_(
"Failed to write block index"));
1820 return state.
Abort(
_(
"Failed to write transaction index"));
1826 for (
unsigned int i=0; i<
vtx.size(); i++)
1841 while (pfork && pfork != plonger)
1844 plonger = plonger->
pprev;
1845 assert(plonger != NULL);
1847 if (pfork == plonger)
1849 pfork = pfork->
pprev;
1850 assert(pfork != NULL);
1854 vector<CBlockIndex*> vDisconnect;
1856 vDisconnect.push_back(pindex);
1859 vector<CBlockIndex*> vConnect;
1860 for (
CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->
pprev)
1861 vConnect.push_back(pindex);
1862 reverse(vConnect.begin(), vConnect.end());
1864 if (vDisconnect.size() > 0) {
1870 vector<CTransaction> vResurrect;
1874 return state.
Abort(
_(
"Failed to read block"));
1886 vResurrect.push_back(tx);
1890 vector<CTransaction> vDelete;
1894 return state.
Abort(
_(
"Failed to read block"));
1898 InvalidChainFound(pindexNew);
1899 InvalidBlockFound(pindex);
1908 vDelete.push_back(tx);
1914 assert(view.
Flush());
1917 printf(
"- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
1928 return state.
Error();
1931 if (!pcoinsTip->
Flush())
1932 return state.
Abort(
_(
"Failed to write to coin database"));
1953 mempool.
remove(tx,
true);
1963 if ((pindexNew->
nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->
nHeight % 144) == 0))
1971 pindexBest = pindexNew;
1972 pblockindexFBBHLast = NULL;
1973 nBestHeight = pindexBest->
nHeight;
1975 nTimeBestReceived =
GetTime();
1977 printf(
"SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
1983 if (!fIsInitialDownload)
1987 for (
int i = 0; i < 100 && pindex != NULL; i++)
1991 pindex = pindex->
pprev;
1995 if (nUpgraded > 100/2)
1997 strMiscWarning =
_(
"Warning: This version is obsolete, upgrade required!");
2003 strCheckpointWarning =
_(
"Warning: checkpoint on different blockchain fork, contact developers to resolve the issue");
2008 std::string strCmd =
GetArg(
"-blocknotify",
"");
2010 if (!fIsInitialDownload && !strCmd.empty())
2012 boost::replace_all(strCmd,
"%s", hashBestChain.
GetHex());
2030 map<uint256, CBlockIndex*>::iterator mi =
mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2035 pindexNew->
pprev = (*miPrev).second;
2038 pindexNew->
nTx =
vtx.size();
2045 setBlockIndexValid.insert(pindexNew);
2048 return state.
Abort(
_(
"Failed to write block index"));
2054 if (pindexNew == pindexBest)
2057 static uint256 hashPrevBestCoinBase;
2058 UpdatedTransaction(hashPrevBestCoinBase);
2062 if (!pblocktree->
Flush())
2063 return state.
Abort(
_(
"Failed to sync block index"));
2072 bool fUpdatedLast =
false;
2081 fUpdatedLast =
true;
2086 FlushBlockFile(
true);
2090 fUpdatedLast =
true;
2100 unsigned int nOldChunks = (pos.
nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2102 if (nNewChunks > nOldChunks) {
2106 printf(
"Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.
nFile);
2112 return state.
Error();
2117 return state.
Abort(
_(
"Failed to write file info"));
2130 unsigned int nNewSize;
2135 return state.
Abort(
_(
"Failed to write block info"));
2139 return state.
Abort(
_(
"Failed to read block info"));
2141 nNewSize = (info.
nUndoSize += nAddSize);
2143 return state.
Abort(
_(
"Failed to write block info"));
2146 unsigned int nOldChunks = (pos.
nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2147 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2148 if (nNewChunks > nOldChunks) {
2152 printf(
"Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.
nFile);
2158 return state.
Error();
2172 return state.
DoS(100,
error(
"CheckBlock() : size limits failed"));
2176 return state.
DoS(50,
error(
"CheckBlock() : proof of work failed"));
2179 if (
vtx.empty() || !
vtx[0].IsCoinBase())
2180 return state.
DoS(100,
error(
"CheckBlock() : first tx is not coinbase"));
2181 for (
unsigned int i = 1; i <
vtx.size(); i++)
2182 if (
vtx[i].IsCoinBase())
2183 return state.
DoS(100,
error(
"CheckBlock() : more than one coinbase"));
2188 return error(
"CheckBlock() : CheckTransaction failed");
2197 set<uint256> uniqueTx;
2198 for (
unsigned int i=0; i<
vtx.size(); i++) {
2201 if (uniqueTx.size() !=
vtx.size())
2202 return state.
DoS(100,
error(
"CheckBlock() : duplicate transaction"),
true);
2204 unsigned int nSigOps = 0;
2209 if (nSigOps > MAX_BLOCK_SIGOPS)
2210 return state.
DoS(100,
error(
"CheckBlock() : out-of-bounds SigOpCount"));
2214 return state.
DoS(100,
error(
"CheckBlock() : hashMerkleRoot mismatch"));
2224 return state.
Invalid(
error(
"AcceptBlock() : block already in mapBlockIndex"));
2232 return state.
DoS(10,
error(
"AcceptBlock() : prev block not found"));
2233 pindexPrev = (*mi).second;
2234 nHeight = pindexPrev->
nHeight+1;
2237 if (
nBits != GetNextWorkRequired(pindexPrev,
this))
2238 return state.
DoS(100,
error(
"AcceptBlock() : incorrect proof of work"));
2242 return state.
Invalid(
error(
"AcceptBlock() : block's timestamp is too early"));
2246 return error(
"AcceptBlock() : block's timestamp too far in the future");
2252 return error(
"AcceptBlock() : block's timestamp is too early compare to last block");
2257 return state.
DoS(10,
error(
"AcceptBlock() : contains a non-final transaction"));
2261 return state.
DoS(100,
error(
"AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2266 return error(
"AcceptBlock() : rejected by synchronized checkpoint");
2274 return state.
Invalid(
error(
"AcceptBlock() : rejected nVersion=1 block"));
2285 if (
vtx[0].vin[0].scriptSig.size() < expect.size() ||
2286 !std::equal(expect.begin(), expect.end(),
vtx[0].vin[0].scriptSig.begin()))
2287 return state.
DoS(100,
error(
"AcceptBlock() : block height mismatch in coinbase"));
2299 return error(
"AcceptBlock() : FindBlockPos failed");
2302 return state.
Abort(
_(
"Failed to write block"));
2304 return error(
"AcceptBlock() : AddToBlockIndex failed");
2305 }
catch(std::runtime_error &e) {
2306 return state.
Abort(
_(
"System error: ") + e.what());
2311 if (hashBestChain == hash)
2329 unsigned int nFound = 0;
2330 for (
unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2332 if (pstart->
nVersion >= minVersion)
2334 pstart = pstart->
pprev;
2336 return (nFound >= nRequired);
2345 if (mapOrphanBlocks.count(hash))
2346 return state.
Invalid(
error(
"ProcessBlock() : already have block (orphan) %s", hash.
ToString().c_str()));
2350 return error(
"ProcessBlock() : CheckBlock FAILED");
2358 return error(
"ProcessBlock() : block has a time stamp of %u before the last checkpoint of %u", pblock->
GetBlockTime(), pcheckpoint->
nTime);
2379 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2380 mapOrphanBlocksByPrev.insert(make_pair(pblock2->
hashPrevBlock, pblock2));
2390 return error(
"ProcessBlock() : AcceptBlock FAILED");
2393 vector<uint256> vWorkQueue;
2394 vWorkQueue.push_back(hash);
2395 for (
unsigned int i = 0; i < vWorkQueue.size(); i++)
2397 uint256 hashPrev = vWorkQueue[i];
2398 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2399 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2402 CBlock* pblockOrphan = (*mi).second;
2406 vWorkQueue.push_back(pblockOrphan->
GetHash());
2407 mapOrphanBlocks.erase(pblockOrphan->
GetHash());
2408 delete pblockOrphan;
2410 mapOrphanBlocksByPrev.erase(hashPrev);
2413 printf(
"ProcessBlock: ACCEPTED\n");
2417 (
int)
GetArg(
"-checkpointdepth", -1) >= 0)
2434 vector<bool> vMatch;
2435 vector<uint256> vHashes;
2437 vMatch.reserve(block.
vtx.size());
2438 vHashes.reserve(block.
vtx.size());
2440 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
2445 vMatch.push_back(
true);
2449 vMatch.push_back(
false);
2450 vHashes.push_back(hash);
2472 right =
CalcHash(height-1, pos*2+1, vTxid);
2482 bool fParentOfMatch =
false;
2483 for (
unsigned int p = pos << height; p < (pos+1) << height && p <
nTransactions; p++)
2484 fParentOfMatch |= vMatch[p];
2486 vBits.push_back(fParentOfMatch);
2487 if (height==0 || !fParentOfMatch) {
2499 if (nBitsUsed >=
vBits.size()) {
2504 bool fParentOfMatch =
vBits[nBitsUsed++];
2505 if (height==0 || !fParentOfMatch) {
2507 if (nHashUsed >=
vHash.size()) {
2513 if (height==0 && fParentOfMatch)
2514 vMatch.push_back(hash);
2528 CPartialMerkleTree::CPartialMerkleTree(
const std::vector<uint256> &vTxid,
const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2542 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2563 unsigned int nBitsUsed = 0, nHashUsed = 0;
2569 if ((nBitsUsed+7)/8 != (
vBits.size()+7)/8)
2572 if (nHashUsed !=
vHash.size())
2574 return hashMerkleRoot;
2585 printf(
"*** %s\n", strMessage.c_str());
2596 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2597 return AbortNode(
_(
"Error: Disk space is low!"));
2611 boost::filesystem::create_directories(path.parent_path());
2612 FILE* file = fopen(path.string().c_str(),
"rb+");
2613 if (!file && !fReadOnly)
2614 file = fopen(path.string().c_str(),
"wb+");
2616 printf(
"Unable to open file %s\n", path.string().c_str());
2620 if (fseek(file, pos.
nPos, SEEK_SET)) {
2621 printf(
"Unable to seek to position %u of %s\n", pos.
nPos, path.string().c_str());
2643 map<uint256, CBlockIndex*>::iterator mi =
mapBlockIndex.find(hash);
2645 return (*mi).second;
2650 throw runtime_error(
"LoadBlockIndex() : new CBlockIndex failed");
2651 mi =
mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2657 bool static LoadBlockIndexDB()
2662 boost::this_thread::interruption_point();
2665 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2670 vSortedByHeight.push_back(make_pair(pindex->
nHeight, pindex));
2672 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2679 setBlockIndexValid.insert(pindex);
2684 printf(
"LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
2686 printf(
"LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.
ToString().c_str());
2690 printf(
"LoadBlockIndexDB(): synchronized checkpoint not read\n");
2697 nBestInvalidWork = bnBestInvalidWork.getuint256();
2700 bool fReindexing =
false;
2702 fReindex |= fReindexing;
2705 pblocktree->
ReadFlag(
"txindex", fTxIndex);
2706 printf(
"LoadBlockIndexDB(): transaction index %s\n", fTxIndex ?
"enabled" :
"disabled");
2710 if (pindexBest == NULL)
2713 nBestHeight = pindexBest->
nHeight;
2718 while(pindex != NULL && pindex->
pprev != NULL) {
2720 pindexPrev->
pnext = pindex;
2721 pindex = pindexPrev;
2723 printf(
"LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
2732 if (pindexBest == NULL || pindexBest->
pprev == NULL)
2736 if (nCheckDepth <= 0)
2737 nCheckDepth = 1000000000;
2738 if (nCheckDepth > nBestHeight)
2740 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2741 printf(
"Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2745 int nGoodTransactions = 0;
2749 boost::this_thread::interruption_point();
2750 if (pindex->
nHeight < nBestHeight-nCheckDepth)
2757 if (nCheckLevel >= 1 && !block.
CheckBlock(state))
2760 if (nCheckLevel >= 2 && pindex) {
2769 if (nCheckLevel >= 3 && pindex == pindexState && (coins.
GetCacheSize() + pcoinsTip->
GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2773 pindexState = pindex->
pprev;
2775 nGoodTransactions = 0;
2776 pindexFailure = pindex;
2778 nGoodTransactions += block.
vtx.size();
2782 return error(
"VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->
nHeight - pindexFailure->
nHeight + 1, nGoodTransactions);
2785 if (nCheckLevel >= 4) {
2787 while (pindex != pindexBest) {
2788 boost::this_thread::interruption_point();
2789 pindex = pindex->
pnext;
2798 printf(
"No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->
nHeight - pindexState->
nHeight, nGoodTransactions);
2806 setBlockIndexValid.clear();
2807 pindexGenesisBlock = NULL;
2810 nBestInvalidWork = 0;
2829 if (!fReindex && !LoadBlockIndexDB())
2838 if (pindexGenesisBlock != NULL)
2843 pblocktree->
WriteFlag(
"txindex", fTxIndex);
2844 printf(
"Initializing databases...\n");
2856 const char* pszTimestamp =
"NY Times 05/Oct/2011 Steve Jobs, Apple’s Visionary, Dies at 56";
2858 txNew.
vin.resize(1);
2859 txNew.
vout.resize(1);
2860 txNew.
vin[0].scriptSig =
CScript() << 486604799 <<
CBigNum(4) << vector<unsigned char>((
const unsigned char*)pszTimestamp, (
const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2861 txNew.
vout[0].nValue = 50 * COIN;
2862 txNew.
vout[0].scriptPubKey =
CScript() <<
ParseHex(
"040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") <<
OP_CHECKSIG;
2864 block.
vtx.push_back(txNew);
2868 block.
nTime = 1317972665;
2869 block.
nBits = 0x1e0ffff0;
2870 block.
nNonce = 2084524493;
2874 block.
nTime = 1396255061;
2875 block.
nNonce = 3250989159;
2883 assert(block.
hashMerkleRoot ==
uint256(
"0x97ddfbbae6be97fd6cdf3e7ca13232a3afff2353e29badfab7f73011edd4ced9"));
2893 return error(
"LoadBlockIndex() : FindBlockPos failed");
2895 return error(
"LoadBlockIndex() : writing genesis block to disk failed");
2897 return error(
"LoadBlockIndex() : genesis block not accepted");
2901 return error(
"LoadBlockIndex() : failed to init sync checkpoint");
2902 }
catch(std::runtime_error &e) {
2903 return error(
"LoadBlockIndex() : failed to initialize block database: %s", e.what());
2909 return error(
"LoadBlockIndex() : failed to reset checkpoint master pubkey");
2919 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2923 mapNext[pindex->
pprev].push_back(pindex);
2929 vector<pair<int, CBlockIndex*> > vStack;
2930 vStack.push_back(make_pair(0, pindexGenesisBlock));
2933 while (!vStack.empty())
2935 int nCol = vStack.back().first;
2940 if (nCol > nPrevCol)
2942 for (
int i = 0; i < nCol-1; i++)
2946 else if (nCol < nPrevCol)
2948 for (
int i = 0; i < nCol; i++)
2955 for (
int i = 0; i < nCol; i++)
2967 PrintWallets(block);
2970 vector<CBlockIndex*>& vNext = mapNext[pindex];
2971 for (
unsigned int i = 0; i < vNext.size(); i++)
2973 if (vNext[i]->pnext)
2975 swap(vNext[0], vNext[i]);
2981 for (
unsigned int i = 0; i < vNext.size(); i++)
2982 vStack.push_back(make_pair(nCol+i, vNext[i]));
2998 nStartByte = info.
nSize;
3003 while (blkdat.
good() && !blkdat.
eof()) {
3004 boost::this_thread::interruption_point();
3009 unsigned int nSize = 0;
3012 unsigned char buf[4];
3014 nRewind = blkdat.
GetPos()+1;
3020 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3022 }
catch (std::exception &e) {
3029 blkdat.
SetLimit(nBlockPos + nSize);
3032 nRewind = blkdat.
GetPos();
3035 if (nBlockPos >= nStartByte) {
3038 dbp->
nPos = nBlockPos;
3045 }
catch (std::exception &e) {
3046 printf(
"%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
3050 }
catch(std::runtime_error &e) {
3051 AbortNode(
_(
"Error: system error: ") + e.what());
3078 string strStatusBar;
3085 strStatusBar =
_(
"This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3102 if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->
GetBlockWork() * 6).getuint256())
3105 strStatusBar = strRPC =
_(
"Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
3112 strStatusBar = strRPC =
"WARNING: Inconsistent checkpoint found! Stop enforcing checkpoints and notify developers to resolve the issue.";
3120 const CAlert& alert = item.second;
3129 if (strFor ==
"statusbar")
3130 return strStatusBar;
3131 else if (strFor ==
"rpc")
3133 assert(!
"GetWarnings() : invalid parameter");
3150 bool static AlreadyHave(
const CInv& inv)
3156 bool txInMap =
false;
3161 return txInMap || mapOrphanTransactions.count(inv.
hash) ||
3166 mapOrphanBlocks.count(inv.
hash);
3181 void static ProcessGetData(
CNode* pfrom)
3183 std::deque<CInv>::iterator it = pfrom->
vRecvGetData.begin();
3185 vector<CInv> vNotFound;
3198 const CInv &inv = *it;
3200 boost::this_thread::interruption_point();
3227 typedef std::pair<unsigned int, uint256> PairType;
3228 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3229 if (!pfrom->setInventoryKnown.count(
CInv(
MSG_TX, pair.second)))
3230 pfrom->PushMessage("tx", block.vtx[pair.first]);
3237 if (inv.hash == pfrom->hashContinue)
3252 bool pushed =
false;
3255 map<CInv, CDataStream>::iterator mi =
mapRelay.find(inv);
3261 if (!pushed && inv.
type == MSG_TX) {
3273 vNotFound.push_back(inv);
3278 Inventory(inv.
hash);
3287 if (!vNotFound.empty()) {
3299 bool static ProcessMessage(
CNode* pfrom,
string strCommand,
CDataStream& vRecv)
3303 printf(
"received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.
size());
3306 printf(
"dropmessagestest DROPPING RECV MESSAGE\n");
3314 if (strCommand ==
"version")
3328 if (pfrom->
nVersion < MIN_PEER_PROTO_VERSION)
3339 vRecv >> addrFrom >> nNonce;
3340 if (!vRecv.
empty()) {
3351 if (pfrom->
fInbound && addrMe.IsRoutable())
3406 item.second.RelayTo(pfrom);
3416 pfrom->fSuccessfullyConnected =
true;
3418 printf(
"receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->cleanSubVer.c_str(), pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.
ToString().c_str(), pfrom->addr.ToString().c_str());
3428 else if (pfrom->nVersion == 0)
3431 pfrom->Misbehaving(1);
3436 else if (strCommand ==
"verack")
3438 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3442 else if (strCommand ==
"addr")
3444 vector<CAddress> vAddr;
3448 if (pfrom->nVersion < CADDR_TIME_VERSION &&
addrman.
size() > 1000)
3450 if (vAddr.size() > 1000)
3452 pfrom->Misbehaving(20);
3453 return error(
"message addr size() = %"PRIszu"", vAddr.size());
3457 vector<CAddress> vAddrOk;
3459 int64 nSince = nNow - 10 * 60;
3460 BOOST_FOREACH(
CAddress& addr, vAddr)
3462 boost::this_thread::interruption_point();
3464 if (addr.
nTime <= 100000000 || addr.
nTime > nNow + 10 * 60)
3465 addr.
nTime = nNow - 5 * 24 * 60 * 60;
3466 pfrom->AddAddressKnown(addr);
3468 if (addr.
nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.
IsRoutable())
3479 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((
GetTime()+hashAddr)/(24*60*60));
3481 multimap<uint256, CNode*> mapMix;
3484 if (pnode->
nVersion < CADDR_TIME_VERSION)
3486 unsigned int nPointer;
3487 memcpy(&nPointer, &pnode,
sizeof(nPointer));
3488 uint256 hashKey = hashRand ^ nPointer;
3490 mapMix.insert(make_pair(hashKey, pnode));
3492 int nRelayNodes = fReachable ? 2 : 1;
3493 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3494 ((*mi).second)->PushAddress(addr);
3499 vAddrOk.push_back(addr);
3501 addrman.
Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3502 if (vAddr.size() < 1000)
3503 pfrom->fGetAddr =
false;
3504 if (pfrom->fOneShot)
3505 pfrom->fDisconnect =
true;
3509 else if (strCommand ==
"inv")
3513 if (vInv.size() > MAX_INV_SZ)
3515 pfrom->Misbehaving(20);
3516 return error(
"message inv size() = %"PRIszu"", vInv.size());
3520 unsigned int nLastBlock = (
unsigned int)(-1);
3521 for (
unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3522 if (vInv[vInv.size() - 1 - nInv].type ==
MSG_BLOCK) {
3523 nLastBlock = vInv.size() - 1 - nInv;
3527 for (
unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3529 const CInv &inv = vInv[nInv];
3531 boost::this_thread::interruption_point();
3532 pfrom->AddInventoryKnown(inv);
3534 bool fAlreadyHave = AlreadyHave(inv);
3536 printf(
" got inventory: %s %s\n", inv.
ToString().c_str(), fAlreadyHave ?
"have" :
"new");
3538 if (!fAlreadyHave) {
3539 if (!fImporting && !fReindex)
3542 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.
hash]));
3543 }
else if (nInv == nLastBlock) {
3553 Inventory(inv.
hash);
3558 else if (strCommand ==
"getdata")
3562 if (vInv.size() > MAX_INV_SZ)
3564 pfrom->Misbehaving(20);
3565 return error(
"message getdata size() = %"PRIszu"", vInv.size());
3569 printf(
"received getdata (%"PRIszu" invsz)\n", vInv.size());
3571 if ((
fDebugNet && vInv.size() > 0) || (vInv.size() == 1))
3572 printf(
"received getdata for: %s\n", vInv[0].ToString().c_str());
3574 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3575 ProcessGetData(pfrom);
3579 else if (strCommand ==
"getblocks")
3583 vRecv >> locator >> hashStop;
3590 pindex = pindex->
pnext;
3592 printf(
"getblocks %d to %s limit %d\n", (pindex ? pindex->
nHeight : -1), hashStop.ToString().c_str(), nLimit);
3593 for (; pindex; pindex = pindex->
pnext)
3613 else if (strCommand ==
"getheaders")
3617 vRecv >> locator >> hashStop;
3623 map<uint256, CBlockIndex*>::iterator mi =
mapBlockIndex.find(hashStop);
3626 pindex = (*mi).second;
3633 pindex = pindex->
pnext;
3637 vector<CBlock> vHeaders;
3639 printf(
"getheaders %d to %s\n", (pindex ? pindex->
nHeight : -1), hashStop.ToString().c_str());
3640 for (; pindex; pindex = pindex->
pnext)
3643 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3646 pfrom->PushMessage(
"headers", vHeaders);
3650 else if (strCommand ==
"tx")
3652 vector<uint256> vWorkQueue;
3653 vector<uint256> vEraseQueue;
3658 CInv inv(MSG_TX, tx.GetHash());
3659 pfrom->AddInventoryKnown(inv);
3661 bool fMissingInputs =
false;
3663 if (tx.AcceptToMemoryPool(state,
true,
true, &fMissingInputs))
3667 vWorkQueue.push_back(inv.
hash);
3668 vEraseQueue.push_back(inv.
hash);
3670 printf(
"AcceptToMemoryPool: %s %s : accepted %s (poolsz %"PRIszu")\n",
3671 pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
3672 tx.GetHash().ToString().c_str(),
3673 mempool.
mapTx.size());
3676 for (
unsigned int i = 0; i < vWorkQueue.size(); i++)
3678 uint256 hashPrev = vWorkQueue[i];
3679 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3680 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3683 const uint256& orphanHash = *mi;
3684 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash];
3685 bool fMissingInputs2 =
false;
3691 if (tx.AcceptToMemoryPool(stateDummy,
true,
true, &fMissingInputs2))
3693 printf(
" accepted orphan tx %s\n", orphanHash.
ToString().c_str());
3696 vWorkQueue.push_back(orphanHash);
3697 vEraseQueue.push_back(orphanHash);
3699 else if (!fMissingInputs2)
3702 vEraseQueue.push_back(orphanHash);
3703 printf(
" removed orphan tx %s\n", orphanHash.
ToString().c_str());
3708 BOOST_FOREACH(
uint256 hash, vEraseQueue)
3709 EraseOrphanTx(hash);
3711 else if (fMissingInputs)
3718 printf(
"mapOrphan overflow, removed %u tx\n", nEvicted);
3723 printf(
"%s from %s %s was not accepted into the memory pool\n", tx.GetHash().ToString().c_str(),
3724 pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str());
3726 pfrom->Misbehaving(nDoS);
3731 else if (strCommand ==
"block" && !fImporting && !fReindex)
3736 printf(
"received block %s\n", block.GetHash().ToString().c_str());
3740 pfrom->AddInventoryKnown(inv);
3747 pfrom->Misbehaving(nDoS);
3751 else if (strCommand ==
"getaddr")
3753 pfrom->vAddrToSend.clear();
3755 BOOST_FOREACH(
const CAddress &addr, vAddr)
3756 pfrom->PushAddress(addr);
3760 else if (strCommand == "mempool")
3762 std::vector<uint256> vtxid;
3763 LOCK2(mempool.cs, pfrom->cs_filter);
3764 mempool.queryHashes(vtxid);
3766 BOOST_FOREACH(
uint256& hash, vtxid) {
3767 CInv inv(MSG_TX, hash);
3768 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash),
hash)) ||
3770 vInv.push_back(inv);
3771 if (vInv.size() == MAX_INV_SZ)
3774 if (vInv.size() > 0)
3775 pfrom->PushMessage(
"inv", vInv);
3779 else if (strCommand ==
"ping")
3781 if (pfrom->nVersion > BIP0031_VERSION)
3796 pfrom->PushMessage(
"pong", nonce);
3801 else if (strCommand ==
"alert")
3806 uint256 alertHash = alert.GetHash();
3807 if (pfrom->setKnown.count(alertHash) == 0)
3809 if (alert.ProcessAlert())
3812 pfrom->setKnown.insert(alertHash);
3816 alert.RelayTo(pnode);
3826 pfrom->Misbehaving(10);
3833 (strCommand ==
"filterload" ||
3834 strCommand ==
"filteradd" ||
3835 strCommand ==
"filterclear"))
3837 pfrom->CloseSocketDisconnect();
3838 return error(
"peer %s attempted to set a bloom filter even though we do not advertise that service",
3839 pfrom->addr.ToString().c_str());
3842 else if (strCommand ==
"checkpoint")
3845 vRecv >> checkpoint;
3847 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3853 checkpoint.RelayTo(pnode);
3857 else if (strCommand == "filterload")
3862 if (!filter.IsWithinSizeConstraints())
3864 pfrom->Misbehaving(100);
3867 LOCK(pfrom->cs_filter);
3868 delete pfrom->pfilter;
3870 pfrom->pfilter->UpdateEmptyFull();
3872 pfrom->fRelayTxes =
true;
3876 else if (strCommand ==
"filteradd")
3878 vector<unsigned char> vData;
3883 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3885 pfrom->Misbehaving(100);
3887 LOCK(pfrom->cs_filter);
3889 pfrom->pfilter->insert(vData);
3891 pfrom->Misbehaving(100);
3896 else if (strCommand ==
"filterclear")
3898 LOCK(pfrom->cs_filter);
3899 delete pfrom->pfilter;
3901 pfrom->fRelayTxes =
true;
3912 if (pfrom->fNetworkNode)
3913 if (strCommand ==
"version" || strCommand ==
"addr" || strCommand ==
"inv" || strCommand ==
"getdata" || strCommand ==
"ping")
3937 ProcessGetData(pfrom);
3942 std::deque<CNetMessage>::iterator it = pfrom->
vRecvMsg.begin();
3964 if (memcmp(msg.
hdr.
pchMessageStart, pchMessageStart,
sizeof(pchMessageStart)) != 0) {
3965 printf(
"\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
3974 printf(
"\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.
GetCommand().c_str());
3985 unsigned int nChecksum = 0;
3986 memcpy(&nChecksum, &hash,
sizeof(nChecksum));
3989 printf(
"ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3990 strCommand.c_str(), nMessageSize, nChecksum, hdr.
nChecksum);
4000 fRet = ProcessMessage(pfrom, strCommand, vRecv);
4002 boost::this_thread::interruption_point();
4004 catch (std::ios_base::failure& e)
4006 if (strstr(e.what(),
"end of data"))
4009 printf(
"ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
4011 else if (strstr(e.what(),
"size too large"))
4014 printf(
"ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
4021 catch (boost::thread_interrupted) {
4024 catch (std::exception& e) {
4031 printf(
"ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
4056 if (pto->
nVersion > BIP0031_VERSION)
4063 if (pto->
fStartSync && !fImporting && !fReindex) {
4073 ResendWalletTransactions();
4077 static int64 nLastRebroadcast;
4085 if (nLastRebroadcast)
4105 vector<CAddress> vAddr;
4112 vAddr.push_back(addr);
4114 if (vAddr.size() >= 1000)
4131 vector<CInv> vInvWait;
4142 if (inv.
type == MSG_TX && !fSendTrickle)
4150 bool fTrickleWait = ((hashRand & 3) != 0);
4158 fTrickleWait =
true;
4163 vInvWait.push_back(inv);
4171 vInv.push_back(inv);
4172 if (vInv.size() >= 1000)
4188 vector<CInv> vGetData;
4193 if (!AlreadyHave(inv))
4197 vGetData.push_back(inv);
4198 if (vGetData.size() >= 1000)
4206 if (!vGetData.empty())
4231 int static FormatHashBlocks(
void* pbuffer,
unsigned int len)
4233 unsigned char* pdata = (
unsigned char*)pbuffer;
4234 unsigned int blocks = 1 + ((len + 8) / 64);
4235 unsigned char* pend = pdata + 64 * blocks;
4236 memset(pdata + len, 0, 64 * blocks - len);
4238 unsigned int bits = len * 8;
4239 pend[-1] = (bits >> 0) & 0xff;
4240 pend[-2] = (bits >> 8) & 0xff;
4241 pend[-3] = (bits >> 16) & 0xff;
4242 pend[-4] = (bits >> 24) & 0xff;
4246 static const unsigned int pSHA256InitState[8] =
4247 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
4252 unsigned char data[64];
4256 for (
int i = 0; i < 16; i++)
4259 for (
int i = 0; i < 8; i++)
4262 SHA256_Update(&ctx, data,
sizeof(data));
4263 for (
int i = 0; i < 8; i++)
4279 dPriority = dFeePerKb = 0;
4284 printf(
"COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4286 BOOST_FOREACH(
uint256 hash, setDependsOn)
4306 if (a.get<1>() == b.get<1>())
4307 return a.get<0>() < b.get<0>();
4308 return a.get<1>() < b.get<1>();
4312 if (a.get<0>() == b.get<0>())
4313 return a.get<1>() < b.get<1>();
4314 return a.get<0>() < b.get<0>();
4323 if(!pblocktemplate.get())
4325 CBlock *pblock = &pblocktemplate->block;
4329 txNew.
vin.resize(1);
4330 txNew.
vin[0].prevout.SetNull();
4331 txNew.
vout.resize(1);
4332 txNew.
vout[0].scriptPubKey = scriptPubKeyIn;
4335 pblock->
vtx.push_back(txNew);
4336 pblocktemplate->vTxFees.push_back(-1);
4337 pblocktemplate->vTxSigOps.push_back(-1);
4340 unsigned int nBlockMaxSize =
GetArg(
"-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
4342 nBlockMaxSize = std::max((
unsigned int)1000, std::min((
unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4346 unsigned int nBlockPrioritySize =
GetArg(
"-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
4347 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4351 unsigned int nBlockMinSize =
GetArg(
"-blockminsize", 0);
4352 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4357 LOCK2(cs_main, mempool.cs);
4362 list<COrphan> vOrphan;
4363 map<uint256, vector<COrphan*> > mapDependers;
4364 bool fPrintPriority =
GetBoolArg(
"-printpriority");
4367 vector<TxPriority> vecPriority;
4368 vecPriority.reserve(mempool.mapTx.size());
4369 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4376 double dPriority = 0;
4378 bool fMissingInputs =
false;
4379 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
4389 printf(
"ERROR: mempool transaction missing input\n");
4390 if (
fDebug) assert(
"mempool transaction missing input" == 0);
4391 fMissingInputs =
true;
4401 vOrphan.push_back(
COrphan(&tx));
4402 porphan = &vOrphan.back();
4404 mapDependers[txin.
prevout.
hash].push_back(porphan);
4412 nTotalIn += nValueIn;
4416 dPriority += (double)nValueIn * nConf;
4418 if (fMissingInputs)
continue;
4422 dPriority /= nTxSize;
4427 double dFeePerKb = double(nTotalIn-tx.
GetValueOut()) / (
double(nTxSize)/1000.0);
4435 vecPriority.push_back(
TxPriority(dPriority, dFeePerKb, &(*mi).second));
4439 uint64 nBlockSize = 1000;
4441 int nBlockSigOps = 100;
4442 bool fSortedByFee = (nBlockPrioritySize <= 0);
4445 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4447 while (!vecPriority.empty())
4450 double dPriority = vecPriority.front().get<0>();
4451 double dFeePerKb = vecPriority.front().get<1>();
4454 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4455 vecPriority.pop_back();
4459 if (nBlockSize + nTxSize >= nBlockMaxSize)
4464 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4468 if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4473 if (!fSortedByFee &&
4474 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 576 / 250)))
4476 fSortedByFee =
true;
4478 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4487 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4499 pblock->
vtx.push_back(tx);
4500 pblocktemplate->vTxFees.push_back(nTxFees);
4501 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
4502 nBlockSize += nTxSize;
4504 nBlockSigOps += nTxSigOps;
4509 printf(
"priority %.1f feeperkb %.1f txid %s\n",
4514 if (mapDependers.count(hash))
4516 BOOST_FOREACH(
COrphan* porphan, mapDependers[hash])
4524 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4531 nLastBlockTx = nBlockTx;
4532 nLastBlockSize = nBlockSize;
4533 printf(
"CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4535 pblock->
vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->
nHeight+1, nFees);
4536 pblocktemplate->vTxFees[0] = -nFees;
4541 pblock->
nBits = GetNextWorkRequired(pindexPrev, pblock);
4544 pblocktemplate->vTxSigOps[0] = pblock->
vtx[0].GetLegacySigOpCount();
4547 indexDummy.
pprev = pindexPrev;
4551 if (!pblock->
ConnectBlock(state, &indexDummy, viewNew,
true))
4552 throw std::runtime_error(
"CreateNewBlock() : ConnectBlock failed");
4555 return pblocktemplate.release();
4578 unsigned int nHeight = pindexPrev->
nHeight+1;
4579 pblock->
vtx[0].vin[0].scriptSig = (
CScript() << nHeight <<
CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4580 assert(pblock->
vtx[0].vin[0].scriptSig.size() <= 100);
4600 unsigned int nNonce;
4603 unsigned char pchPadding0[64];
4605 unsigned char pchPadding1[64];
4608 memset(&tmp, 0,
sizeof(tmp));
4610 tmp.block.nVersion = pblock->
nVersion;
4613 tmp.block.nTime = pblock->
nTime;
4614 tmp.block.nBits = pblock->
nBits;
4615 tmp.block.nNonce = pblock->
nNonce;
4617 FormatHashBlocks(&tmp.block,
sizeof(tmp.block));
4618 FormatHashBlocks(&tmp.hash1,
sizeof(tmp.hash1));
4621 for (
unsigned int i = 0; i <
sizeof(tmp)/4; i++)
4622 ((
unsigned int*)&tmp)[i] =
ByteReverse(((
unsigned int*)&tmp)[i]);
4627 memcpy(pdata, &tmp.block, 128);
4628 memcpy(phash1, &tmp.hash1, 64);
4637 if (hash > hashTarget)
4641 printf(
"FeathercoinMiner:\n");
4642 printf(
"proof-of-work found \n hash: %s \ntarget: %s\n", hash.
GetHex().c_str(), hashTarget.
GetHex().c_str());
4650 return error(
"FeathercoinMiner : generated block is stale");
4664 return error(
"FeathercoinMiner : ProcessBlock, block not accepted");
4670 void static FeathercoinMiner(
CWallet *pwallet)
4672 printf(
"FeathercoinMiner started\n");
4678 unsigned int nExtraNonce = 0;
4691 if (!pblocktemplate.get())
4693 CBlock *pblock = &pblocktemplate->block;
4696 printf(
"Running FeathercoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->
vtx.size(),
4702 char pmidstatebuf[32+16];
char* pmidstate = alignup<16>(pmidstatebuf);
4703 char pdatabuf[128+16];
char* pdata = alignup<16>(pdatabuf);
4704 char phash1buf[64+16];
char* phash1 = alignup<16>(phash1buf);
4708 unsigned int& nBlockTime = *(
unsigned int*)(pdata + 64 + 4);
4709 unsigned int& nBlockBits = *(
unsigned int*)(pdata + 64 + 8);
4720 unsigned int nHashesDone = 0;
4723 char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
4728 if (thash <= hashTarget)
4732 CheckWork(pblock, *pwallet, reservekey);
4738 if ((pblock->
nNonce & 0xFF) == 0)
4743 static int64 nHashCounter;
4744 if (nHPSTimerStart == 0)
4750 nHashCounter += nHashesDone;
4761 static int64 nLogTime;
4762 if (
GetTime() - nLogTime > 30 * 60)
4765 printf(
"hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
4772 boost::this_thread::interruption_point();
4775 if (pblock->
nNonce >= 0xffff0000)
4779 if (pindexPrev != pindexBest)
4793 catch (boost::thread_interrupted)
4795 printf(
"FeathercoinMiner terminated\n");
4802 static boost::thread_group* minerThreads = NULL;
4804 int nThreads =
GetArg(
"-genproclimit", -1);
4806 nThreads = boost::thread::hardware_concurrency();
4808 if (minerThreads != NULL)
4810 minerThreads->interrupt_all();
4811 delete minerThreads;
4812 minerThreads = NULL;
4815 if (nThreads == 0 || !fGenerate)
4818 minerThreads =
new boost::thread_group();
4819 for (
int i = 0; i < nThreads; i++)
4820 minerThreads->create_thread(boost::bind(&FeathercoinMiner, pwallet));
4837 while (((n % 10) == 0) && e < 9) {
4843 assert(d >= 1 && d <= 9);
4845 return 1 + (n*9 + d - 1)*10 + e;
4847 return 1 + (n - 1)*10 + 9;
4863 int d = (x % 9) + 1;
4884 std::map<uint256, CBlockIndex*>::iterator it1 =
mapBlockIndex.begin();
4886 delete (*it1).second;
4890 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4891 for (; it2 != mapOrphanBlocks.end(); it2++)
4892 delete (*it2).second;
4893 mapOrphanBlocks.clear();
4896 mapOrphanTransactions.clear();
CBlockIndex * FindBlockByHeight(int nHeight)
Find a block by height in the currently-connected chain.
bool error(const char *format,...)
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
std::multimap< int64, CInv > mapAskFor
void PushMessage(const char *pszCommand)
void GenerateBitcoins(bool fGenerate, CWallet *pwallet)
Run the miner threads.
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
CCriticalSection cs_setpwalletRegistered
bool AddOrphanTx(const CTransaction &tx)
CDiskBlockPos GetBlockPos() const
#define strprintf(format,...)
bool HaveCoins(const uint256 &txid)
CBigNum GetBlockWork() const
void TraverseAndBuild(int height, unsigned int pos, const std::vector< uint256 > &vTxid, const std::vector< bool > &vMatch)
#define THREAD_PRIORITY_LOWEST
bool addUnchecked(const uint256 &hash, const CTransaction &tx)
bool remove(const CTransaction &tx, bool fRecursive=false)
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
#define THREAD_PRIORITY_NORMAL
CCriticalSection cs_filter
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
const_iterator begin() const
bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp=NULL)
bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks=true, unsigned int flags=SCRIPT_VERIFY_P2SH|SCRIPT_VERIFY_STRICTENC, std::vector< CScriptCheck > *pvChecks=NULL) const
const char * GetCommand() const
#define TRY_LOCK(cs, name)
void SetBackend(CCoinsView &viewIn)
void FileCommit(FILE *fileout)
void swap(CScriptCheck &check)
std::vector< CTxOut > vout
unsigned int nTransactions
bool SetBestBlock(CBlockIndex *pindex)
uint256 getuint256() const
bool CheckTransaction(CValidationState &state) const
static uint64 CompressAmount(uint64 nAmount)
bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false)
CCriticalSection cs_wallet
bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree=true, bool *pfMissingInputs=NULL)
bool ReadReindexing(bool &fReindex)
unsigned int GetLegacySigOpCount() const
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
bool IsPayToScriptHash() const
bool ReadLastBlockFile(int &nFile)
int64 GetBlockTime() const
bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction &tx, const CBlock *pblock, bool fUpdate=false, bool fFindBlock=false)
void UnregisterWallet(CWallet *pwalletIn)
Unregister a wallet from core.
std::map< COutPoint, CInPoint > mapNextTx
CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn)
CCoinsView that brings transactions from a memorypool into view.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
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)
map< uint256, CAlert > mapAlerts
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
void ThreadScriptCheck()
Run an instance of the script checking thread.
std::vector< CMerkleTx > vtxPrev
bool RelayTo(CNode *pnode) const
bool Invalid(bool ret=false)
bool SetLimit(uint64 nPos=(uint64)(-1))
void IncrementExtraNonce(CBlock *pblock, CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
bool VerifyDB(int nCheckLevel, int nCheckDepth)
Verify consistency of the block and coin databases.
string GetWarnings(string strFor)
CBlockIndex * GetLastCheckpoint(const std::map< uint256, CBlockIndex * > &mapBlockIndex)
bool AreInputsStandard(CCoinsViewCache &mapInputs) const
Check for standard transaction types.
void queryHashes(std::vector< uint256 > &vtxid)
bool Add(const CAddress &addr, const CNetAddr &source, int64 nTimePenalty=0)
bool WriteBlockIndex(const CDiskBlockIndex &blockindex)
Double ended buffer combining vector and stream-like interfaces.
#define scrypt_1024_1_1_256_sp(input, output, scratchpad)
Data structure that represents a partial merkle tree.
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
CCriticalSection cs_inventory
uint256 GetPoWHash() const
bool SeenLocal(const CService &addr)
vote for a local address
std::vector< CAddress > vAddrToSend
unsigned long long uint64
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
map< uint256, CBlock * > mapOrphanBlocks
int64 GetMedianTimePast() const
bool LoadBlockIndexGuts()
bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean=NULL)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
void RandAddSeedPerfmon()
unsigned int GetSizeOfCompactSize(uint64 nSize)
bool GetStats(CCoinsStats &stats)
COrphan(CTransaction *ptxIn)
void RenameThread(const char *name)
uint256 hashGenesisBlock("0x12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2")
const string strMessageMagic
CSyncCheckpoint checkpointMessage
Undo information for a CTxIn.
size_type count(const key_type &k) const
void PushInventory(const CInv &inv)
bool CheckDiskSpace(uint64 nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
bool GetCoins(const uint256 &txid, CCoins &coins)
bool IsNewerThan(const CTransaction &old) const
bool BatchWrite(const std::map< uint256, CCoins > &mapCoins, CBlockIndex *pindex)
limitedmap< CInv, int64 > mapAlreadyAskedFor(MAX_INV_SZ)
void PrintBlockTree()
Print the loaded block tree.
bool CheckCheckpointPubKey()
static std::string strMasterPrivKey
bool IsAvailable(unsigned int nPos) const
std::deque< CInv > vRecvGetData
CBlockTemplate * CreateNewBlockWithKey(CReserveKey &reservekey)
int ScriptSigArgsExpected(txnouttype t, const std::vector< std::vector< unsigned char > > &vSolutions)
bool WriteSyncCheckpoint(const uint256 &hashCheckpoint)
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
static int64 nMinTxFee
Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) ...
uint256 BuildMerkleTree() const
int GetDepthInMainChain() const
bool CheckSyncCheckpoint(const uint256 &hashBlock, const CBlockIndex *pindexPrev)
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
bool VerifySignature(const CCoins &txFrom, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Verify a signature.
unsigned int GetP2SHSigOpCount(CCoinsViewCache &mapInputs) const
Count ECDSA signature operations in pay-to-script-hash inputs.
bool CheckWork(CBlock *pblock, CWallet &wallet, CReserveKey &reservekey)
Check mined block.
int std::string int dummy
#define CLIENT_VERSION_IS_RELEASE
bool BatchWrite(const std::map< uint256, CCoins > &mapCoins, CBlockIndex *pindex)
std::vector< CAddress > GetAddr()
CCriticalSection cs_hashSyncCheckpoint
class CMainCleanup instance_of_cmaincleanup
int GetBlocksToMaturity() const
void AddBlock(unsigned int nHeightIn, uint64 nTimeIn)
CBigNum & SetCompact(unsigned int nCompact)
std::deque< CNetMessage > vRecvMsg
uint256 hashInvalidCheckpoint
std::vector< uint256 > vHash
Used to relay blocks as header + vector to filtered nodes.
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.
void AskForPendingSyncCheckpoint(CNode *pfrom)
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.
bool SetBestChain(CValidationState &state, CBlockIndex *pindexNew)
Connect/disconnect blocks until pindexNew is the new tip of the active block chain.
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.
virtual bool GetCoins(const uint256 &txid, CCoins &coins)
void AddressCurrentlyConnected(const CService &addr)
uint64 GetRand(uint64 nMax)
unsigned int GetSigOpCount(bool fAccurate) const
std::vector< CTxOut > vout
std::map< uint256, CCoins >::iterator FetchCoins(const uint256 &txid)
bool CorruptionPossible()
void UnloadBlockIndex()
Unload database information.
bool SendMessages(CNode *pto, bool fSendTrickle)
Send queued protocol messages to be sent to a give node.
CBlockIndex * GetBlockIndex()
int GetNumBlocksOfPeers()
Get the number of active peers.
bool IsReachable(const CNetAddr &addr)
check whether a given address is in a network we can probably connect to
CBlockHeader GetBlockHeader() const
An encapsulated public key.
uint256 AutoSelectSyncCheckpoint()
bool ReadBestInvalidWork(CBigNum &bnBestInvalidWork)
bool GetCoins(const uint256 &txid, CCoins &coins)
bool IsInMainChain() const
bool DoS(int level, bool ret=false, bool corruptionIn=false)
set< uint256 > setDependsOn
CClientUIInterface uiInterface
C++ wrapper for BIGNUM (OpenSSL bignum)
mruset< CInv > setInventoryKnown
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos)
std::vector< uint256 > vMerkleBranch
A CService with information about it as peer.
unsigned int SendBufferSize()
uint256 hashSyncCheckpoint
bool SetBestBlock(CBlockIndex *pindex)
bool LoadBlockIndex()
Load the block tree and coins database from disk.
void RelayTransaction(const CTransaction &tx, const uint256 &hash)
std::map< uint256, CTransaction > mapTx
virtual bool HaveCoins(const uint256 &txid)
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, vector< vector< unsigned char > > &vSolutionsRet)
bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo)
bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true)
std::string ToString() const
CCoinsViewCache(CCoinsView &baseIn, bool fDummy=false)
std::string strCheckpointWarning
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch)
int64 GetValueIn(CCoinsViewCache &mapInputs) const
Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything ...
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.
void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock, bool fUpdate)
Push an updated transaction to all registered wallets.
bool GetReservedKey(CPubKey &pubkey)
bool ReadSyncCheckpoint(uint256 &hashCheckpoint)
std::string DateTimeStrFormat(const char *pszFormat, int64 nTime)
int64 GetValueOut() const
Amount of bitcoins spent by this transaction.
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)
bool WriteLastBlockFile(int nFile)
std::map< uint256, int > mapRequestCount
Queue for verifications that have to be performed.
CCoinsViewBacked(CCoinsView &viewIn)
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)
std::vector< CTxInUndo > vprevout
bool Abort(const std::string &msg)
std::string GetHex() const
std::vector< uint256 > GetMerkleBranch(int nIndex) const
bool ConnectBestBlock(CValidationState &state)
Find the best known block, and make it the tip of the block chain.
bool ProcessMessages(CNode *pfrom)
Process protocol messages received from a given node.
std::string ToString() const
CBlockTemplate * CreateNewBlock(const CScript &scriptPubKeyIn)
Generate a new block, without valid proof-of-work.
multimap< uint256, CBlock * > mapOrphanBlocksByPrev
bool ReadFlag(const std::string &name, bool &fValue)
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
A transaction with a bunch of additional info that only the owner cares about.
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Closure representing one script verification Note that this stores references to the spending transac...
bool WriteToDisk(CDiskBlockPos &pos)
CTransaction & lookup(uint256 hash)
bool HaveInputs(CCoinsViewCache &view) const
bool IsSyncCheckpointEnforced()
void SetThreadPriority(int nPriority)
CBlockIndex * GetBestBlock()
std::vector< bool > vBits
const uint256 & GetTxHash(unsigned int nIndex) const
virtual bool GetStats(CCoinsStats &stats)
virtual bool SetBestBlock(CBlockIndex *pindex)
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Capture information about block/transaction validation.
bool removeConflicts(const CTransaction &tx)
CBlockIndex * pindexGenesisBlock
const CTransaction * ptxTo
bool SendSyncCheckpoint(uint256 hashCheckpoint)
static uint64 DecompressAmount(uint64 nAmount)
void pruneSpent(const uint256 &hash, CCoins &coins)
CCriticalSection cs_mapAlerts
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
void SHA256Transform(void *pstate, void *pinput, const void *pinit)
CBlockFileInfo infoLastBlockFile
CCriticalSection cs_mapRelay
bool Spend(const COutPoint &out, CTxInUndo &undo)
void AddTimeData(const CNetAddr &ip, int64 nTime)
bool IsRelevantAndUpdate(const CTransaction &tx, const uint256 &hash)
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
bool SetCoins(const uint256 &txid, const CCoins &coins)
A key allocated from the key pool.
uint32_t ByteReverse(uint32_t value)
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
The block chain is a tree shaped structure starting with the genesis block at the root...
bool HaveCoins(const uint256 &txid)
Undo information for a CBlock.
Serialized script, used inside transaction inputs and outputs.
std::vector< CInv > vInventoryToSend
Undo information for a CTransaction.
unsigned int nCoinCacheSize
std::string ToString() const
string FormatMoney(int64 n, bool fPlus)
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...
boost::signals2::signal< void()> NotifyBlocksChanged
Block chain changed.
void Good(const CService &addr, int64 nTime=GetAdjustedTime())
bool exists(uint256 hash)
bool AbortNode(const std::string &strMessage)
Abort with a message.
An inpoint - a combination of a transaction and an index n into its vin.
void RegisterWallet(CWallet *pwalletIn)
Register a wallet to receive updates from core.
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
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)
unsigned int nTransactionsUpdated
CMerkleBlock(const CBlock &block, CBloomFilter &filter)
bool AcceptPendingSyncCheckpoint()
set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexValid
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
CBlockIndex * GetBestBlock()
boost::tuple< double, double, CTransaction * > TxPriority
std::string ToString() const
bool GetCoins(const uint256 &txid, CCoins &coins)
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
bool Misbehaving(int howmuch)
bool operator()(const TxPriority &a, const TxPriority &b)
virtual bool BatchWrite(const std::map< uint256, CCoins > &mapCoins, CBlockIndex *pindex)
bool WriteFlag(const std::string &name, bool fValue)
map< uint256, CTransaction > mapOrphanTransactions
bool SetCoins(const uint256 &txid, const CCoins &coins)
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.
unsigned int GetCacheSize()
void Add(std::vector< T > &vChecks)
std::string ToString() const
CDiskBlockPos GetUndoPos() const
The basic transaction that is broadcasted on the network and contained in blocks. ...
CCoinsView backed by another CCoinsView.
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
Information about a peer.
static const int CURRENT_VERSION
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
Open an undo file (rev?????.dat)
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
CCoinsView that adds a memory cache for transactions to another CCoinsView.
bool IsStandard(std::string &strReason) const
Check for standard transaction types.
bool AcceptWalletTransaction(bool fCheckInputs=true)
std::string ToString() const
bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool *pfMissingInputs)
Wrapper around a FILE* that implements a ring buffer to deserialize from.
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
std::vector< CTxUndo > vtxundo
bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const
unsigned char pchMessageStart[4]
CCriticalSection cs_LastBlockFile
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown=false)
bool ReadFromDisk(const CDiskBlockPos &pos)
void PushGetBlocks(CBlockIndex *pindexBegin, uint256 hashEnd)
TxPriorityCompare(bool _byFee)
CCoinsView that brings transactions from a memorypool into view.
map< uint256, CBlockIndex * > mapBlockIndex
double GuessVerificationProgress(CBlockIndex *pindex)
vector< unsigned char > ParseHex(const char *psz)
static int64 nMinRelayTxFee
Fees smaller than this (in satoshi) are considered zero fee (for relaying)
CCriticalSection cs_vNodes
bool MoneyRange(int64 nValue)
map< uint256, set< uint256 > > mapOrphanTransactionsByPrev
set< CWallet * > setpwalletRegistered
virtual CBlockIndex * GetBestBlock()
std::set< CAddress > setAddrKnown
map< string, string > mapArgs
map< CInv, CDataStream > mapRelay
int atoi(const std::string &str)
static uint256 CheckMerkleBranch(uint256 hash, const std::vector< uint256 > &vMerkleBranch, int nIndex)
uint256 GetBlockHash() const
A transaction with a merkle branch linking it to the block chain.
std::deque< CSerializeData > vSendMsg
static const CTxOut & GetOutputFor(const CTxIn &input, CCoinsViewCache &mapInputs)
void runCommand(std::string strCommand)
uint256 CalcHash(int height, unsigned int pos, const std::vector< uint256 > &vTxid)
CMedianFilter< int > cPeerBlockCounts(8, 0)
std::map< uint256, CCoins > cacheCoins
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 FormatHashBuffers(CBlock *pblock, char *pmidstate, char *pdata, char *phash1)
Do mining precalculation.
virtual bool SetCoins(const uint256 &txid, const CCoins &coins)
const uint256 * phashBlock
bool WriteBestInvalidWork(const CBigNum &bnBestInvalidWork)