1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 #include "cryptopp/sha.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
24 CCriticalSection cs_main;
26 static map<uint256, CTransaction> mapTransactions;
27 CCriticalSection cs_mapTransactions;
28 unsigned int nTransactionsUpdated = 0;
29 map<COutPoint, CInPoint> mapNextTx;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 uint256 hashGenesisBlock("0x00000000e74ef41733382f8a94d41bf29f20c6c48a7ab489e1fab0ab719bf676");
33 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
34 const int nTotalBlocksEstimate = 0; // Conservative estimate of total nr of blocks on main chain
35 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
36 CBlockIndex* pindexGenesisBlock = NULL;
38 CBigNum bnBestChainWork = 0;
39 CBigNum bnBestInvalidWork = 0;
40 uint256 hashBestChain = 0;
41 CBlockIndex* pindexBest = NULL;
42 int64 nTimeBestReceived = 0;
44 map<uint256, CBlock*> mapOrphanBlocks;
45 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
47 map<uint256, CDataStream*> mapOrphanTransactions;
48 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
55 int fGenerateBitcoins = false;
56 int64 nTransactionFee = MIN_TX_FEE;
57 int fLimitProcessors = false;
58 int nLimitProcessors = 1;
59 int fMinimizeToTray = true;
60 int fMinimizeOnClose = true;
73 //////////////////////////////////////////////////////////////////////////////
75 // dispatching functions
78 void RegisterWallet(CWallet* pwalletIn)
80 CRITICAL_BLOCK(cs_setpwalletRegistered)
82 setpwalletRegistered.insert(pwalletIn);
86 void UnregisterWallet(CWallet* pwalletIn)
88 CRITICAL_BLOCK(cs_setpwalletRegistered)
90 setpwalletRegistered.erase(pwalletIn);
94 bool static IsFromMe(CTransaction& tx)
96 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
97 if (pwallet->IsFromMe(tx))
102 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
104 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
105 if (pwallet->GetTransaction(hashTx,wtx))
110 void static EraseFromWallets(uint256 hash)
112 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
113 pwallet->EraseFromWallet(hash);
116 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
118 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
119 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
122 void static SetBestChain(const CBlockLocator& loc)
124 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125 pwallet->SetBestChain(loc);
128 void static UpdatedTransaction(const uint256& hashTx)
130 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
131 pwallet->UpdatedTransaction(hashTx);
134 void static PrintWallets(const CBlock& block)
136 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
137 pwallet->PrintWallet(block);
140 void static Inventory(const uint256& hash)
142 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
143 pwallet->Inventory(hash);
146 void static ResendWalletTransactions()
148 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149 pwallet->ResendWalletTransactions();
158 //////////////////////////////////////////////////////////////////////////////
160 // mapOrphanTransactions
163 void static AddOrphanTx(const CDataStream& vMsg)
166 CDataStream(vMsg) >> tx;
167 uint256 hash = tx.GetHash();
168 if (mapOrphanTransactions.count(hash))
170 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
171 BOOST_FOREACH(const CTxIn& txin, tx.vin)
172 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
175 void static EraseOrphanTx(uint256 hash)
177 if (!mapOrphanTransactions.count(hash))
179 const CDataStream* pvMsg = mapOrphanTransactions[hash];
181 CDataStream(*pvMsg) >> tx;
182 BOOST_FOREACH(const CTxIn& txin, tx.vin)
184 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
185 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
187 if ((*mi).second == pvMsg)
188 mapOrphanTransactionsByPrev.erase(mi++);
194 mapOrphanTransactions.erase(hash);
204 //////////////////////////////////////////////////////////////////////////////
206 // CTransaction and CTxIndex
209 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
212 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
214 if (!ReadFromDisk(txindexRet.pos))
216 if (prevout.n >= vout.size())
224 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
227 return ReadFromDisk(txdb, prevout, txindex);
230 bool CTransaction::ReadFromDisk(COutPoint prevout)
234 return ReadFromDisk(txdb, prevout, txindex);
239 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
251 // Load the block this tx is in
253 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
255 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
260 // Update the tx's hashBlock
261 hashBlock = pblock->GetHash();
263 // Locate the transaction
264 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
265 if (pblock->vtx[nIndex] == *(CTransaction*)this)
267 if (nIndex == pblock->vtx.size())
269 vMerkleBranch.clear();
271 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
275 // Fill in merkle branch
276 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
279 // Is the tx in a block that's in the main chain
280 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
281 if (mi == mapBlockIndex.end())
283 CBlockIndex* pindex = (*mi).second;
284 if (!pindex || !pindex->IsInMainChain())
287 return pindexBest->nHeight - pindex->nHeight + 1;
296 bool CTransaction::CheckTransaction() const
298 // Basic checks that don't depend on any context
300 return error("CTransaction::CheckTransaction() : vin empty");
302 return error("CTransaction::CheckTransaction() : vout empty");
304 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
305 return error("CTransaction::CheckTransaction() : size limits failed");
307 // Check for negative or overflow output values
309 BOOST_FOREACH(const CTxOut& txout, vout)
311 if (txout.nValue < 0)
312 return error("CTransaction::CheckTransaction() : txout.nValue negative");
313 if (txout.nValue > MAX_MONEY)
314 return error("CTransaction::CheckTransaction() : txout.nValue too high");
315 nValueOut += txout.nValue;
316 if (!MoneyRange(nValueOut))
317 return error("CTransaction::CheckTransaction() : txout total out of range");
320 // Check for duplicate inputs
321 set<COutPoint> vInOutPoints;
322 BOOST_FOREACH(const CTxIn& txin, vin)
324 if (vInOutPoints.count(txin.prevout))
326 vInOutPoints.insert(txin.prevout);
331 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
332 return error("CTransaction::CheckTransaction() : coinbase script size");
336 BOOST_FOREACH(const CTxIn& txin, vin)
337 if (txin.prevout.IsNull())
338 return error("CTransaction::CheckTransaction() : prevout is null");
344 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
347 *pfMissingInputs = false;
349 if (!CheckTransaction())
350 return error("AcceptToMemoryPool() : CheckTransaction failed");
352 // Coinbase is only valid in a block, not as a loose transaction
354 return error("AcceptToMemoryPool() : coinbase as individual tx");
356 // To help v0.1.5 clients who would see it as a negative number
357 if ((int64)nLockTime > INT_MAX)
358 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
361 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
362 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
363 // attacks disallow transactions with more than one SigOp per 34 bytes.
364 // 34 bytes because a TxOut is:
365 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
366 if (GetSigOpCount() > nSize / 34 || nSize < 100)
367 return error("AcceptToMemoryPool() : nonstandard transaction");
369 // Rather not work on nonstandard transactions (unless -testnet)
370 if (!fTestNet && !IsStandard())
371 return error("AcceptToMemoryPool() : nonstandard transaction type");
373 // Do we already have it?
374 uint256 hash = GetHash();
375 CRITICAL_BLOCK(cs_mapTransactions)
376 if (mapTransactions.count(hash))
379 if (txdb.ContainsTx(hash))
382 // Check for conflicts with in-memory transactions
383 CTransaction* ptxOld = NULL;
384 for (int i = 0; i < vin.size(); i++)
386 COutPoint outpoint = vin[i].prevout;
387 if (mapNextTx.count(outpoint))
389 // Disable replacement feature for now
392 // Allow replacing with a newer version of the same transaction
395 ptxOld = mapNextTx[outpoint].ptx;
396 if (ptxOld->IsFinal())
398 if (!IsNewerThan(*ptxOld))
400 for (int i = 0; i < vin.size(); i++)
402 COutPoint outpoint = vin[i].prevout;
403 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
412 // Check against previous transactions
413 map<uint256, CTxIndex> mapUnused;
415 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
418 *pfMissingInputs = true;
419 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
422 // Don't accept it if it can't get into a block
423 if (nFees < GetMinFee(1000, false, true))
424 return error("AcceptToMemoryPool() : not enough fees");
426 // Continuously rate-limit free transactions
427 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
428 // be annoying or make other's transactions take longer to confirm.
429 if (nFees < MIN_RELAY_TX_FEE)
431 static CCriticalSection cs;
432 static double dFreeCount;
433 static int64 nLastTime;
434 int64 nNow = GetTime();
438 // Use an exponentially decaying ~10-minute window:
439 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
441 // -limitfreerelay unit is thousand-bytes-per-minute
442 // At default rate it would take over a month to fill 1GB
443 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
444 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
446 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
452 // Store transaction in memory
453 CRITICAL_BLOCK(cs_mapTransactions)
457 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
458 ptxOld->RemoveFromMemoryPool();
460 AddToMemoryPoolUnchecked();
463 ///// are we sure this is ok when loading transactions or restoring block txes
464 // If updated, erase old tx from wallet
466 EraseFromWallets(ptxOld->GetHash());
468 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
472 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
475 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
478 bool CTransaction::AddToMemoryPoolUnchecked()
480 // Add to memory pool without checking anything. Don't call this directly,
481 // call AcceptToMemoryPool to properly check the transaction first.
482 CRITICAL_BLOCK(cs_mapTransactions)
484 uint256 hash = GetHash();
485 mapTransactions[hash] = *this;
486 for (int i = 0; i < vin.size(); i++)
487 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
488 nTransactionsUpdated++;
494 bool CTransaction::RemoveFromMemoryPool()
496 // Remove transaction from memory pool
497 CRITICAL_BLOCK(cs_mapTransactions)
499 BOOST_FOREACH(const CTxIn& txin, vin)
500 mapNextTx.erase(txin.prevout);
501 mapTransactions.erase(GetHash());
502 nTransactionsUpdated++;
512 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
514 if (hashBlock == 0 || nIndex == -1)
517 // Find the block it claims to be in
518 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
519 if (mi == mapBlockIndex.end())
521 CBlockIndex* pindex = (*mi).second;
522 if (!pindex || !pindex->IsInMainChain())
525 // Make sure the merkle branch connects to this block
526 if (!fMerkleVerified)
528 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
530 fMerkleVerified = true;
533 nHeightRet = pindex->nHeight;
534 return pindexBest->nHeight - pindex->nHeight + 1;
538 int CMerkleTx::GetBlocksToMaturity() const
542 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
546 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
550 if (!IsInMainChain() && !ClientConnectInputs())
552 return CTransaction::AcceptToMemoryPool(txdb, false);
556 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
560 bool CMerkleTx::AcceptToMemoryPool()
563 return AcceptToMemoryPool(txdb);
568 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
570 CRITICAL_BLOCK(cs_mapTransactions)
572 // Add previous supporting transactions first
573 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
575 if (!tx.IsCoinBase())
577 uint256 hash = tx.GetHash();
578 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
579 tx.AcceptToMemoryPool(txdb, fCheckInputs);
582 return AcceptToMemoryPool(txdb, fCheckInputs);
587 bool CWalletTx::AcceptWalletTransaction()
590 return AcceptWalletTransaction(txdb);
593 int CTxIndex::GetDepthInMainChain() const
597 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
599 // Find the block in the index
600 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
601 if (mi == mapBlockIndex.end())
603 CBlockIndex* pindex = (*mi).second;
604 if (!pindex || !pindex->IsInMainChain())
606 return 1 + nBestHeight - pindex->nHeight;
618 //////////////////////////////////////////////////////////////////////////////
620 // CBlock and CBlockIndex
623 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
625 if (!fReadTransactions)
627 *this = pindex->GetBlockHeader();
630 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
632 if (GetHash() != pindex->GetBlockHash())
633 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
637 uint256 static GetOrphanRoot(const CBlock* pblock)
639 // Work back to the first block in the orphan chain
640 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
641 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
642 return pblock->GetHash();
645 int64 static GetBlockValue(int nHeight, int64 nFees)
647 int64 nSubsidy = 50 * COIN;
649 // Subsidy is cut in half every 4 years
650 nSubsidy >>= (nHeight / 210000);
652 return nSubsidy + nFees;
655 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
657 const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
658 const int64 nTargetSpacing = 10 * 60;
659 const int64 nInterval = nTargetTimespan / nTargetSpacing;
661 // Genesis block and first block
662 if (pindexLast == NULL || pindexLast->pprev == NULL)
663 return bnProofOfWorkLimit.GetCompact();
665 int64 nActualSpacing = pindexLast->GetBlockTime() - pindexLast->pprev->GetBlockTime();
667 // ppcoin: target change every block
668 // ppcoin: retarget with exponential moving toward target spacing
670 bnNew.SetCompact(pindexLast->nBits);
671 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
672 bnNew /= ((nInterval + 1) * nTargetSpacing);
674 if (bnNew > bnProofOfWorkLimit)
675 bnNew = bnProofOfWorkLimit;
677 return bnNew.GetCompact();
680 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
683 bnTarget.SetCompact(nBits);
686 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
687 return error("CheckProofOfWork() : nBits below minimum work");
689 // Check proof of work matches claimed amount
690 if (hash > bnTarget.getuint256())
691 return error("CheckProofOfWork() : hash doesn't match nBits");
696 // Return conservative estimate of total number of blocks, 0 if unknown
697 int GetTotalBlocksEstimate()
705 return nTotalBlocksEstimate;
709 bool IsInitialBlockDownload()
711 if (pindexBest == NULL || nBestHeight < (GetTotalBlocksEstimate()-nInitialBlockThreshold))
713 static int64 nLastUpdate;
714 static CBlockIndex* pindexLastBest;
715 if (pindexBest != pindexLastBest)
717 pindexLastBest = pindexBest;
718 nLastUpdate = GetTime();
720 return (GetTime() - nLastUpdate < 10 &&
721 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
724 void static InvalidChainFound(CBlockIndex* pindexNew)
726 if (pindexNew->bnChainWork > bnBestInvalidWork)
728 bnBestInvalidWork = pindexNew->bnChainWork;
729 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
732 printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
733 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
734 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
735 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
748 bool CTransaction::DisconnectInputs(CTxDB& txdb)
750 // Relinquish previous transactions' spent pointers
753 BOOST_FOREACH(const CTxIn& txin, vin)
755 COutPoint prevout = txin.prevout;
757 // Get prev txindex from disk
759 if (!txdb.ReadTxIndex(prevout.hash, txindex))
760 return error("DisconnectInputs() : ReadTxIndex failed");
762 if (prevout.n >= txindex.vSpent.size())
763 return error("DisconnectInputs() : prevout.n out of range");
765 // Mark outpoint as not spent
766 txindex.vSpent[prevout.n].SetNull();
769 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
770 return error("DisconnectInputs() : UpdateTxIndex failed");
774 // Remove transaction from index
775 if (!txdb.EraseTxIndex(*this))
776 return error("DisconnectInputs() : EraseTxPos failed");
782 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
783 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
785 // Take over previous transactions' spent pointers
789 for (int i = 0; i < vin.size(); i++)
791 COutPoint prevout = vin[i].prevout;
796 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
798 // Get txindex from current proposed changes
799 txindex = mapTestPool[prevout.hash];
803 // Read txindex from txdb
804 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
806 if (!fFound && (fBlock || fMiner))
807 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
811 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
813 // Get prev tx from single transactions in memory
814 CRITICAL_BLOCK(cs_mapTransactions)
816 if (!mapTransactions.count(prevout.hash))
817 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
818 txPrev = mapTransactions[prevout.hash];
821 txindex.vSpent.resize(txPrev.vout.size());
825 // Get prev tx from disk
826 if (!txPrev.ReadFromDisk(txindex.pos))
827 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
830 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
831 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
833 // If prev is coinbase, check that it's matured
834 if (txPrev.IsCoinBase())
835 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
836 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
837 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
840 if (!VerifySignature(txPrev, *this, i))
841 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
843 // Check for conflicts
844 if (!txindex.vSpent[prevout.n].IsNull())
845 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
847 // Check for negative or overflow input values
848 nValueIn += txPrev.vout[prevout.n].nValue;
849 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
850 return error("ConnectInputs() : txin values out of range");
852 // Mark outpoints as spent
853 txindex.vSpent[prevout.n] = posThisTx;
856 if (fBlock || fMiner)
858 mapTestPool[prevout.hash] = txindex;
862 if (nValueIn < GetValueOut())
863 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
865 // Tally transaction fees
866 int64 nTxFee = nValueIn - GetValueOut();
868 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
869 if (nTxFee < nMinFee)
872 if (!MoneyRange(nFees))
873 return error("ConnectInputs() : nFees out of range");
878 // Add transaction to changes
879 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
883 // Add transaction to test pool
884 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
891 bool CTransaction::ClientConnectInputs()
896 // Take over previous transactions' spent pointers
897 CRITICAL_BLOCK(cs_mapTransactions)
900 for (int i = 0; i < vin.size(); i++)
902 // Get prev tx from single transactions in memory
903 COutPoint prevout = vin[i].prevout;
904 if (!mapTransactions.count(prevout.hash))
906 CTransaction& txPrev = mapTransactions[prevout.hash];
908 if (prevout.n >= txPrev.vout.size())
912 if (!VerifySignature(txPrev, *this, i))
913 return error("ConnectInputs() : VerifySignature failed");
915 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
916 ///// this has to go away now that posNext is gone
917 // // Check for conflicts
918 // if (!txPrev.vout[prevout.n].posNext.IsNull())
919 // return error("ConnectInputs() : prev tx already used");
921 // // Flag outpoints as used
922 // txPrev.vout[prevout.n].posNext = posThisTx;
924 nValueIn += txPrev.vout[prevout.n].nValue;
926 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
927 return error("ClientConnectInputs() : txin values out of range");
929 if (GetValueOut() > nValueIn)
939 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
941 // Disconnect in reverse order
942 for (int i = vtx.size()-1; i >= 0; i--)
943 if (!vtx[i].DisconnectInputs(txdb))
946 // Update block index on disk without changing it in memory.
947 // The memory index structure will be changed after the db commits.
950 CDiskBlockIndex blockindexPrev(pindex->pprev);
951 blockindexPrev.hashNext = 0;
952 if (!txdb.WriteBlockIndex(blockindexPrev))
953 return error("DisconnectBlock() : WriteBlockIndex failed");
959 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
961 // Check it again in case a previous version let a bad block in
965 //// issue here: it doesn't know the version
966 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
968 map<uint256, CTxIndex> mapQueuedChanges;
970 BOOST_FOREACH(CTransaction& tx, vtx)
972 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
973 nTxPos += ::GetSerializeSize(tx, SER_DISK);
975 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false))
978 // Write queued txindex changes
979 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
981 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
982 return error("ConnectBlock() : UpdateTxIndex failed");
985 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
988 // Update block index on disk without changing it in memory.
989 // The memory index structure will be changed after the db commits.
992 CDiskBlockIndex blockindexPrev(pindex->pprev);
993 blockindexPrev.hashNext = pindex->GetBlockHash();
994 if (!txdb.WriteBlockIndex(blockindexPrev))
995 return error("ConnectBlock() : WriteBlockIndex failed");
998 // Watch for transactions paying to me
999 BOOST_FOREACH(CTransaction& tx, vtx)
1000 SyncWithWallets(tx, this, true);
1005 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1007 printf("REORGANIZE\n");
1010 CBlockIndex* pfork = pindexBest;
1011 CBlockIndex* plonger = pindexNew;
1012 while (pfork != plonger)
1014 while (plonger->nHeight > pfork->nHeight)
1015 if (!(plonger = plonger->pprev))
1016 return error("Reorganize() : plonger->pprev is null");
1017 if (pfork == plonger)
1019 if (!(pfork = pfork->pprev))
1020 return error("Reorganize() : pfork->pprev is null");
1023 // List of what to disconnect
1024 vector<CBlockIndex*> vDisconnect;
1025 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1026 vDisconnect.push_back(pindex);
1028 // List of what to connect
1029 vector<CBlockIndex*> vConnect;
1030 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1031 vConnect.push_back(pindex);
1032 reverse(vConnect.begin(), vConnect.end());
1034 // Disconnect shorter branch
1035 vector<CTransaction> vResurrect;
1036 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1039 if (!block.ReadFromDisk(pindex))
1040 return error("Reorganize() : ReadFromDisk for disconnect failed");
1041 if (!block.DisconnectBlock(txdb, pindex))
1042 return error("Reorganize() : DisconnectBlock failed");
1044 // Queue memory transactions to resurrect
1045 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1046 if (!tx.IsCoinBase())
1047 vResurrect.push_back(tx);
1050 // Connect longer branch
1051 vector<CTransaction> vDelete;
1052 for (int i = 0; i < vConnect.size(); i++)
1054 CBlockIndex* pindex = vConnect[i];
1056 if (!block.ReadFromDisk(pindex))
1057 return error("Reorganize() : ReadFromDisk for connect failed");
1058 if (!block.ConnectBlock(txdb, pindex))
1062 return error("Reorganize() : ConnectBlock failed");
1065 // Queue memory transactions to delete
1066 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1067 vDelete.push_back(tx);
1069 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1070 return error("Reorganize() : WriteHashBestChain failed");
1072 // Make sure it's successfully written to disk before changing memory structure
1073 if (!txdb.TxnCommit())
1074 return error("Reorganize() : TxnCommit failed");
1076 // Disconnect shorter branch
1077 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1079 pindex->pprev->pnext = NULL;
1081 // Connect longer branch
1082 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1084 pindex->pprev->pnext = pindex;
1086 // Resurrect memory transactions that were in the disconnected branch
1087 BOOST_FOREACH(CTransaction& tx, vResurrect)
1088 tx.AcceptToMemoryPool(txdb, false);
1090 // Delete redundant memory transactions that are in the connected branch
1091 BOOST_FOREACH(CTransaction& tx, vDelete)
1092 tx.RemoveFromMemoryPool();
1098 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1100 uint256 hash = GetHash();
1103 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1105 txdb.WriteHashBestChain(hash);
1106 if (!txdb.TxnCommit())
1107 return error("SetBestChain() : TxnCommit failed");
1108 pindexGenesisBlock = pindexNew;
1110 else if (hashPrevBlock == hashBestChain)
1112 // Adding to current best branch
1113 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1116 InvalidChainFound(pindexNew);
1117 return error("SetBestChain() : ConnectBlock failed");
1119 if (!txdb.TxnCommit())
1120 return error("SetBestChain() : TxnCommit failed");
1122 // Add to current best branch
1123 pindexNew->pprev->pnext = pindexNew;
1125 // Delete redundant memory transactions
1126 BOOST_FOREACH(CTransaction& tx, vtx)
1127 tx.RemoveFromMemoryPool();
1132 if (!Reorganize(txdb, pindexNew))
1135 InvalidChainFound(pindexNew);
1136 return error("SetBestChain() : Reorganize failed");
1140 // Update best block in wallet (so we can detect restored wallets)
1141 if (!IsInitialBlockDownload())
1143 const CBlockLocator locator(pindexNew);
1144 ::SetBestChain(locator);
1148 hashBestChain = hash;
1149 pindexBest = pindexNew;
1150 nBestHeight = pindexBest->nHeight;
1151 bnBestChainWork = pindexNew->bnChainWork;
1152 nTimeBestReceived = GetTime();
1153 nTransactionsUpdated++;
1154 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1160 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1162 // Check for duplicate
1163 uint256 hash = GetHash();
1164 if (mapBlockIndex.count(hash))
1165 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1167 // Construct new block index object
1168 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1170 return error("AddToBlockIndex() : new CBlockIndex failed");
1171 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1172 pindexNew->phashBlock = &((*mi).first);
1173 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1174 if (miPrev != mapBlockIndex.end())
1176 pindexNew->pprev = (*miPrev).second;
1177 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1179 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1183 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1184 if (!txdb.TxnCommit())
1188 if (pindexNew->bnChainWork > bnBestChainWork)
1189 if (!SetBestChain(txdb, pindexNew))
1194 if (pindexNew == pindexBest)
1196 // Notify UI to display prev block's coinbase if it was ours
1197 static uint256 hashPrevBestCoinBase;
1198 UpdatedTransaction(hashPrevBestCoinBase);
1199 hashPrevBestCoinBase = vtx[0].GetHash();
1209 bool CBlock::CheckBlock() const
1211 // These are checks that are independent of context
1212 // that can be verified before saving an orphan block.
1215 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1216 return error("CheckBlock() : size limits failed");
1218 // Check proof of work matches claimed amount
1219 if (!CheckProofOfWork(GetHash(), nBits))
1220 return error("CheckBlock() : proof of work failed");
1223 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1224 return error("CheckBlock() : block timestamp too far in the future");
1226 // First transaction must be coinbase, the rest must not be
1227 if (vtx.empty() || !vtx[0].IsCoinBase())
1228 return error("CheckBlock() : first tx is not coinbase");
1229 for (int i = 1; i < vtx.size(); i++)
1230 if (vtx[i].IsCoinBase())
1231 return error("CheckBlock() : more than one coinbase");
1233 // Check transactions
1234 BOOST_FOREACH(const CTransaction& tx, vtx)
1235 if (!tx.CheckTransaction())
1236 return error("CheckBlock() : CheckTransaction failed");
1238 // Check that it's not full of nonstandard transactions
1239 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1240 return error("CheckBlock() : too many nonstandard transactions");
1243 if (hashMerkleRoot != BuildMerkleTree())
1244 return error("CheckBlock() : hashMerkleRoot mismatch");
1249 bool CBlock::AcceptBlock()
1251 // Check for duplicate
1252 uint256 hash = GetHash();
1253 if (mapBlockIndex.count(hash))
1254 return error("AcceptBlock() : block already in mapBlockIndex");
1256 // Get prev block index
1257 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1258 if (mi == mapBlockIndex.end())
1259 return error("AcceptBlock() : prev block not found");
1260 CBlockIndex* pindexPrev = (*mi).second;
1261 int nHeight = pindexPrev->nHeight+1;
1263 // Check proof of work
1264 if (nBits != GetNextWorkRequired(pindexPrev))
1265 return error("AcceptBlock() : incorrect proof of work");
1267 // Check timestamp against prev
1268 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1269 return error("AcceptBlock() : block's timestamp is too early");
1271 // Check that all transactions are finalized
1272 BOOST_FOREACH(const CTransaction& tx, vtx)
1273 if (!tx.IsFinal(nHeight, GetBlockTime()))
1274 return error("AcceptBlock() : contains a non-final transaction");
1276 // Check that the block chain matches the known block chain up to a checkpoint
1278 // ppcoin: no checkpoint yet; to be created after beta
1279 if ((nHeight == -1 && hash != uint256("0x83f760b87b13d7002eaccc4a5a154aaea0f861e52b6eb481d30a344f55605c01")))
1280 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1282 // Write block to history file
1283 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1284 return error("AcceptBlock() : out of disk space");
1285 unsigned int nFile = -1;
1286 unsigned int nBlockPos = 0;
1287 if (!WriteToDisk(nFile, nBlockPos))
1288 return error("AcceptBlock() : WriteToDisk failed");
1289 if (!AddToBlockIndex(nFile, nBlockPos))
1290 return error("AcceptBlock() : AddToBlockIndex failed");
1292 // Relay inventory, but don't relay old inventory during initial block download
1293 if (hashBestChain == hash)
1294 CRITICAL_BLOCK(cs_vNodes)
1295 BOOST_FOREACH(CNode* pnode, vNodes)
1296 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1297 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1302 bool static ProcessBlock(CNode* pfrom, CBlock* pblock)
1304 // Check for duplicate
1305 uint256 hash = pblock->GetHash();
1306 if (mapBlockIndex.count(hash))
1307 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1308 if (mapOrphanBlocks.count(hash))
1309 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1311 // Preliminary checks
1312 if (!pblock->CheckBlock())
1313 return error("ProcessBlock() : CheckBlock FAILED");
1315 // If don't already have its previous block, shunt it off to holding area until we get it
1316 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1318 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1319 CBlock* pblock2 = new CBlock(*pblock);
1320 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1321 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1323 // Ask this guy to fill in what we're missing
1325 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1330 if (!pblock->AcceptBlock())
1331 return error("ProcessBlock() : AcceptBlock FAILED");
1333 // Recursively process any orphan blocks that depended on this one
1334 vector<uint256> vWorkQueue;
1335 vWorkQueue.push_back(hash);
1336 for (int i = 0; i < vWorkQueue.size(); i++)
1338 uint256 hashPrev = vWorkQueue[i];
1339 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1340 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1343 CBlock* pblockOrphan = (*mi).second;
1344 if (pblockOrphan->AcceptBlock())
1345 vWorkQueue.push_back(pblockOrphan->GetHash());
1346 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1347 delete pblockOrphan;
1349 mapOrphanBlocksByPrev.erase(hashPrev);
1352 printf("ProcessBlock: ACCEPTED\n");
1363 bool CheckDiskSpace(uint64 nAdditionalBytes)
1365 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1367 // Check for 15MB because database could create another 10MB log file at any time
1368 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1371 string strMessage = _("Warning: Disk space is low ");
1372 strMiscWarning = strMessage;
1373 printf("*** %s\n", strMessage.c_str());
1374 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1375 CreateThread(Shutdown, NULL);
1381 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1385 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1388 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1390 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1399 static unsigned int nCurrentBlockFile = 1;
1401 FILE* AppendBlockFile(unsigned int& nFileRet)
1406 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1409 if (fseek(file, 0, SEEK_END) != 0)
1411 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1412 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1414 nFileRet = nCurrentBlockFile;
1418 nCurrentBlockFile++;
1422 bool LoadBlockIndex(bool fAllowNew)
1426 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1427 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1428 pchMessageStart[0] = 0xfa;
1429 pchMessageStart[1] = 0xbf;
1430 pchMessageStart[2] = 0xb5;
1431 pchMessageStart[3] = 0xda;
1438 if (!txdb.LoadBlockIndex())
1443 // Init with genesis block
1445 if (mapBlockIndex.empty())
1451 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1452 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1453 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1454 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1455 // vMerkleTree: 4a5e1e
1458 const char* pszTimestamp = "MarketWatch 07/Nov/2011 Gold tops $1,790 to end at over six-week high";
1460 txNew.vin.resize(1);
1461 txNew.vout.resize(1);
1462 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1463 txNew.vout[0].nValue = 50 * COIN;
1464 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1466 block.vtx.push_back(txNew);
1467 block.hashPrevBlock = 0;
1468 block.hashMerkleRoot = block.BuildMerkleTree();
1470 block.nTime = 1320941849;
1471 block.nBits = 0x1d00ffff;
1472 block.nNonce = 725069208;
1476 block.nTime = 1296688602;
1477 block.nBits = 0x1d07fff8;
1478 block.nNonce = 384568319;
1482 printf("%s\n", block.GetHash().ToString().c_str());
1483 printf("%s\n", hashGenesisBlock.ToString().c_str());
1484 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1485 assert(block.hashMerkleRoot == uint256("0x09cc647316c90e7e14f225113eec3539e80284695c91e7262a65c72c5d75a868"));
1487 assert(block.GetHash() == hashGenesisBlock);
1489 // Start new block file
1491 unsigned int nBlockPos;
1492 if (!block.WriteToDisk(nFile, nBlockPos))
1493 return error("LoadBlockIndex() : writing genesis block to disk failed");
1494 if (!block.AddToBlockIndex(nFile, nBlockPos))
1495 return error("LoadBlockIndex() : genesis block not accepted");
1503 void PrintBlockTree()
1505 // precompute tree structure
1506 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1507 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1509 CBlockIndex* pindex = (*mi).second;
1510 mapNext[pindex->pprev].push_back(pindex);
1512 //while (rand() % 3 == 0)
1513 // mapNext[pindex->pprev].push_back(pindex);
1516 vector<pair<int, CBlockIndex*> > vStack;
1517 vStack.push_back(make_pair(0, pindexGenesisBlock));
1520 while (!vStack.empty())
1522 int nCol = vStack.back().first;
1523 CBlockIndex* pindex = vStack.back().second;
1526 // print split or gap
1527 if (nCol > nPrevCol)
1529 for (int i = 0; i < nCol-1; i++)
1533 else if (nCol < nPrevCol)
1535 for (int i = 0; i < nCol; i++)
1542 for (int i = 0; i < nCol; i++)
1547 block.ReadFromDisk(pindex);
1548 printf("%d (%u,%u) %s %s tx %d",
1552 block.GetHash().ToString().substr(0,20).c_str(),
1553 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1556 PrintWallets(block);
1558 // put the main timechain first
1559 vector<CBlockIndex*>& vNext = mapNext[pindex];
1560 for (int i = 0; i < vNext.size(); i++)
1562 if (vNext[i]->pnext)
1564 swap(vNext[0], vNext[i]);
1570 for (int i = 0; i < vNext.size(); i++)
1571 vStack.push_back(make_pair(nCol+i, vNext[i]));
1584 //////////////////////////////////////////////////////////////////////////////
1589 map<uint256, CAlert> mapAlerts;
1590 CCriticalSection cs_mapAlerts;
1592 string GetWarnings(string strFor)
1595 string strStatusBar;
1597 if (GetBoolArg("-testsafemode"))
1600 // Misc warnings like out of disk space and clock is wrong
1601 if (strMiscWarning != "")
1604 strStatusBar = strMiscWarning;
1607 // Longer invalid proof-of-work chain
1608 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1611 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1615 CRITICAL_BLOCK(cs_mapAlerts)
1617 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1619 const CAlert& alert = item.second;
1620 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1622 nPriority = alert.nPriority;
1623 strStatusBar = alert.strStatusBar;
1628 if (strFor == "statusbar")
1629 return strStatusBar;
1630 else if (strFor == "rpc")
1632 assert(!"GetWarnings() : invalid parameter");
1636 bool CAlert::ProcessAlert()
1638 if (!CheckSignature())
1643 CRITICAL_BLOCK(cs_mapAlerts)
1645 // Cancel previous alerts
1646 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1648 const CAlert& alert = (*mi).second;
1651 printf("cancelling alert %d\n", alert.nID);
1652 mapAlerts.erase(mi++);
1654 else if (!alert.IsInEffect())
1656 printf("expiring alert %d\n", alert.nID);
1657 mapAlerts.erase(mi++);
1663 // Check if this alert has been cancelled
1664 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1666 const CAlert& alert = item.second;
1667 if (alert.Cancels(*this))
1669 printf("alert already cancelled by %d\n", alert.nID);
1675 mapAlerts.insert(make_pair(GetHash(), *this));
1678 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1690 //////////////////////////////////////////////////////////////////////////////
1696 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1700 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1701 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1703 // Don't know what it is, just say we already got one
1710 // The message start string is designed to be unlikely to occur in normal data.
1711 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1712 // a large 4-byte int at any alignment.
1713 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1716 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1718 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1719 RandAddSeedPerfmon();
1721 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1722 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1724 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1726 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1734 if (strCommand == "version")
1736 // Each connection can only send one version message
1737 if (pfrom->nVersion != 0)
1744 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1745 if (pfrom->nVersion == 10300)
1746 pfrom->nVersion = 300;
1747 if (pfrom->nVersion >= 106 && !vRecv.empty())
1748 vRecv >> addrFrom >> nNonce;
1749 if (pfrom->nVersion >= 106 && !vRecv.empty())
1750 vRecv >> pfrom->strSubVer;
1751 if (pfrom->nVersion >= 209 && !vRecv.empty())
1752 vRecv >> pfrom->nStartingHeight;
1754 if (pfrom->nVersion == 0)
1757 // Disconnect if we connected to ourself
1758 if (nNonce == nLocalHostNonce && nNonce > 1)
1760 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1761 pfrom->fDisconnect = true;
1765 // Be shy and don't send version until we hear
1766 if (pfrom->fInbound)
1767 pfrom->PushVersion();
1769 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1771 AddTimeData(pfrom->addr.ip, nTime);
1774 if (pfrom->nVersion >= 209)
1775 pfrom->PushMessage("verack");
1776 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1777 if (pfrom->nVersion < 209)
1778 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1780 if (!pfrom->fInbound)
1782 // Advertise our address
1783 if (addrLocalHost.IsRoutable() && !fUseProxy)
1785 CAddress addr(addrLocalHost);
1786 addr.nTime = GetAdjustedTime();
1787 pfrom->PushAddress(addr);
1790 // Get recent addresses
1791 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1793 pfrom->PushMessage("getaddr");
1794 pfrom->fGetAddr = true;
1798 // Ask the first connected node for block updates
1799 static int nAskedForBlocks;
1800 if (!pfrom->fClient &&
1801 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
1802 (nAskedForBlocks < 1 || vNodes.size() <= 1))
1805 pfrom->PushGetBlocks(pindexBest, uint256(0));
1809 CRITICAL_BLOCK(cs_mapAlerts)
1810 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1811 item.second.RelayTo(pfrom);
1813 pfrom->fSuccessfullyConnected = true;
1815 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1819 else if (pfrom->nVersion == 0)
1821 // Must have a version message before anything else
1826 else if (strCommand == "verack")
1828 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1832 else if (strCommand == "addr")
1834 vector<CAddress> vAddr;
1837 // Don't want addr from older versions unless seeding
1838 if (pfrom->nVersion < 209)
1840 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1842 if (vAddr.size() > 1000)
1843 return error("message addr size() = %d", vAddr.size());
1845 // Store the new addresses
1848 int64 nNow = GetAdjustedTime();
1849 int64 nSince = nNow - 10 * 60;
1850 BOOST_FOREACH(CAddress& addr, vAddr)
1854 // ignore IPv6 for now, since it isn't implemented anyway
1857 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1858 addr.nTime = nNow - 5 * 24 * 60 * 60;
1859 AddAddress(addr, 2 * 60 * 60, &addrDB);
1860 pfrom->AddAddressKnown(addr);
1861 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1863 // Relay to a limited number of other nodes
1864 CRITICAL_BLOCK(cs_vNodes)
1866 // Use deterministic randomness to send to the same nodes for 24 hours
1867 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1868 static uint256 hashSalt;
1870 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1871 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1872 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1873 multimap<uint256, CNode*> mapMix;
1874 BOOST_FOREACH(CNode* pnode, vNodes)
1876 if (pnode->nVersion < 31402)
1878 unsigned int nPointer;
1879 memcpy(&nPointer, &pnode, sizeof(nPointer));
1880 uint256 hashKey = hashRand ^ nPointer;
1881 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1882 mapMix.insert(make_pair(hashKey, pnode));
1884 int nRelayNodes = 2;
1885 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1886 ((*mi).second)->PushAddress(addr);
1890 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
1891 if (vAddr.size() < 1000)
1892 pfrom->fGetAddr = false;
1896 else if (strCommand == "inv")
1900 if (vInv.size() > 50000)
1901 return error("message inv size() = %d", vInv.size());
1904 BOOST_FOREACH(const CInv& inv, vInv)
1908 pfrom->AddInventoryKnown(inv);
1910 bool fAlreadyHave = AlreadyHave(txdb, inv);
1912 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1916 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
1917 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
1919 // Track requests for our stuff
1920 Inventory(inv.hash);
1925 else if (strCommand == "getdata")
1929 if (vInv.size() > 50000)
1930 return error("message getdata size() = %d", vInv.size());
1932 BOOST_FOREACH(const CInv& inv, vInv)
1936 printf("received getdata for: %s\n", inv.ToString().c_str());
1938 if (inv.type == MSG_BLOCK)
1940 // Send block from disk
1941 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
1942 if (mi != mapBlockIndex.end())
1945 block.ReadFromDisk((*mi).second);
1946 pfrom->PushMessage("block", block);
1948 // Trigger them to send a getblocks request for the next batch of inventory
1949 if (inv.hash == pfrom->hashContinue)
1951 // Bypass PushInventory, this must send even if redundant,
1952 // and we want it right after the last block so they don't
1953 // wait for other stuff first.
1955 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
1956 pfrom->PushMessage("inv", vInv);
1957 pfrom->hashContinue = 0;
1961 else if (inv.IsKnownType())
1963 // Send stream from relay memory
1964 CRITICAL_BLOCK(cs_mapRelay)
1966 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
1967 if (mi != mapRelay.end())
1968 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
1972 // Track requests for our stuff
1973 Inventory(inv.hash);
1978 else if (strCommand == "getblocks")
1980 CBlockLocator locator;
1982 vRecv >> locator >> hashStop;
1984 // Find the last block the caller has in the main chain
1985 CBlockIndex* pindex = locator.GetBlockIndex();
1987 // Send the rest of the chain
1989 pindex = pindex->pnext;
1990 int nLimit = 500 + locator.GetDistanceBack();
1991 unsigned int nBytes = 0;
1992 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
1993 for (; pindex; pindex = pindex->pnext)
1995 if (pindex->GetBlockHash() == hashStop)
1997 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2000 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2002 block.ReadFromDisk(pindex, true);
2003 nBytes += block.GetSerializeSize(SER_NETWORK);
2004 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2006 // When this block is requested, we'll send an inv that'll make them
2007 // getblocks the next batch of inventory.
2008 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2009 pfrom->hashContinue = pindex->GetBlockHash();
2016 else if (strCommand == "getheaders")
2018 CBlockLocator locator;
2020 vRecv >> locator >> hashStop;
2022 CBlockIndex* pindex = NULL;
2023 if (locator.IsNull())
2025 // If locator is null, return the hashStop block
2026 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2027 if (mi == mapBlockIndex.end())
2029 pindex = (*mi).second;
2033 // Find the last block the caller has in the main chain
2034 pindex = locator.GetBlockIndex();
2036 pindex = pindex->pnext;
2039 vector<CBlock> vHeaders;
2040 int nLimit = 2000 + locator.GetDistanceBack();
2041 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2042 for (; pindex; pindex = pindex->pnext)
2044 vHeaders.push_back(pindex->GetBlockHeader());
2045 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2048 pfrom->PushMessage("headers", vHeaders);
2052 else if (strCommand == "tx")
2054 vector<uint256> vWorkQueue;
2055 CDataStream vMsg(vRecv);
2059 CInv inv(MSG_TX, tx.GetHash());
2060 pfrom->AddInventoryKnown(inv);
2062 bool fMissingInputs = false;
2063 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2065 SyncWithWallets(tx, NULL, true);
2066 RelayMessage(inv, vMsg);
2067 mapAlreadyAskedFor.erase(inv);
2068 vWorkQueue.push_back(inv.hash);
2070 // Recursively process any orphan transactions that depended on this one
2071 for (int i = 0; i < vWorkQueue.size(); i++)
2073 uint256 hashPrev = vWorkQueue[i];
2074 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2075 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2078 const CDataStream& vMsg = *((*mi).second);
2080 CDataStream(vMsg) >> tx;
2081 CInv inv(MSG_TX, tx.GetHash());
2083 if (tx.AcceptToMemoryPool(true))
2085 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2086 SyncWithWallets(tx, NULL, true);
2087 RelayMessage(inv, vMsg);
2088 mapAlreadyAskedFor.erase(inv);
2089 vWorkQueue.push_back(inv.hash);
2094 BOOST_FOREACH(uint256 hash, vWorkQueue)
2095 EraseOrphanTx(hash);
2097 else if (fMissingInputs)
2099 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2105 else if (strCommand == "block")
2110 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2113 CInv inv(MSG_BLOCK, block.GetHash());
2114 pfrom->AddInventoryKnown(inv);
2116 if (ProcessBlock(pfrom, &block))
2117 mapAlreadyAskedFor.erase(inv);
2121 else if (strCommand == "getaddr")
2123 // Nodes rebroadcast an addr every 24 hours
2124 pfrom->vAddrToSend.clear();
2125 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2126 CRITICAL_BLOCK(cs_mapAddresses)
2128 unsigned int nCount = 0;
2129 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2131 const CAddress& addr = item.second;
2132 if (addr.nTime > nSince)
2135 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2137 const CAddress& addr = item.second;
2138 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2139 pfrom->PushAddress(addr);
2145 else if (strCommand == "checkorder")
2150 if (!GetBoolArg("-allowreceivebyip"))
2152 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2159 /// we have a chance to check the order here
2161 // Keep giving the same key to the same ip until they use it
2162 if (!mapReuseKey.count(pfrom->addr.ip))
2163 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2165 // Send back approval of order and pubkey to use
2166 CScript scriptPubKey;
2167 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2168 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2172 else if (strCommand == "reply")
2177 CRequestTracker tracker;
2178 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2180 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2181 if (mi != pfrom->mapRequests.end())
2183 tracker = (*mi).second;
2184 pfrom->mapRequests.erase(mi);
2187 if (!tracker.IsNull())
2188 tracker.fn(tracker.param1, vRecv);
2192 else if (strCommand == "ping")
2197 else if (strCommand == "alert")
2202 if (alert.ProcessAlert())
2205 pfrom->setKnown.insert(alert.GetHash());
2206 CRITICAL_BLOCK(cs_vNodes)
2207 BOOST_FOREACH(CNode* pnode, vNodes)
2208 alert.RelayTo(pnode);
2215 // Ignore unknown commands for extensibility
2219 // Update the last seen time for this node's address
2220 if (pfrom->fNetworkNode)
2221 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2222 AddressCurrentlyConnected(pfrom->addr);
2228 bool ProcessMessages(CNode* pfrom)
2230 CDataStream& vRecv = pfrom->vRecv;
2234 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2238 // (4) message start
2247 // Scan for message start
2248 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2249 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2250 if (vRecv.end() - pstart < nHeaderSize)
2252 if (vRecv.size() > nHeaderSize)
2254 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2255 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2259 if (pstart - vRecv.begin() > 0)
2260 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2261 vRecv.erase(vRecv.begin(), pstart);
2264 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2269 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2272 string strCommand = hdr.GetCommand();
2275 unsigned int nMessageSize = hdr.nMessageSize;
2276 if (nMessageSize > MAX_SIZE)
2278 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2281 if (nMessageSize > vRecv.size())
2283 // Rewind and wait for rest of message
2284 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2289 if (vRecv.GetVersion() >= 209)
2291 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2292 unsigned int nChecksum = 0;
2293 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2294 if (nChecksum != hdr.nChecksum)
2296 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2297 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2302 // Copy message to its own buffer
2303 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2304 vRecv.ignore(nMessageSize);
2310 CRITICAL_BLOCK(cs_main)
2311 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2315 catch (std::ios_base::failure& e)
2317 if (strstr(e.what(), "end of data"))
2319 // Allow exceptions from underlength message on vRecv
2320 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2322 else if (strstr(e.what(), "size too large"))
2324 // Allow exceptions from overlong size
2325 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2329 PrintExceptionContinue(&e, "ProcessMessage()");
2332 catch (std::exception& e) {
2333 PrintExceptionContinue(&e, "ProcessMessage()");
2335 PrintExceptionContinue(NULL, "ProcessMessage()");
2339 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2347 bool SendMessages(CNode* pto, bool fSendTrickle)
2349 CRITICAL_BLOCK(cs_main)
2351 // Don't send anything until we get their version message
2352 if (pto->nVersion == 0)
2356 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2357 pto->PushMessage("ping");
2359 // Resend wallet transactions that haven't gotten in a block yet
2360 ResendWalletTransactions();
2362 // Address refresh broadcast
2363 static int64 nLastRebroadcast;
2364 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2366 nLastRebroadcast = GetTime();
2367 CRITICAL_BLOCK(cs_vNodes)
2369 BOOST_FOREACH(CNode* pnode, vNodes)
2371 // Periodically clear setAddrKnown to allow refresh broadcasts
2372 pnode->setAddrKnown.clear();
2374 // Rebroadcast our address
2375 if (addrLocalHost.IsRoutable() && !fUseProxy)
2377 CAddress addr(addrLocalHost);
2378 addr.nTime = GetAdjustedTime();
2379 pnode->PushAddress(addr);
2385 // Clear out old addresses periodically so it's not too much work at once
2386 static int64 nLastClear;
2387 if (nLastClear == 0)
2388 nLastClear = GetTime();
2389 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2391 nLastClear = GetTime();
2392 CRITICAL_BLOCK(cs_mapAddresses)
2395 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2396 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2397 mi != mapAddresses.end();)
2399 const CAddress& addr = (*mi).second;
2400 if (addr.nTime < nSince)
2402 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2404 addrdb.EraseAddress(addr);
2405 mapAddresses.erase(mi++);
2419 vector<CAddress> vAddr;
2420 vAddr.reserve(pto->vAddrToSend.size());
2421 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2423 // returns true if wasn't already contained in the set
2424 if (pto->setAddrKnown.insert(addr).second)
2426 vAddr.push_back(addr);
2427 // receiver rejects addr messages larger than 1000
2428 if (vAddr.size() >= 1000)
2430 pto->PushMessage("addr", vAddr);
2435 pto->vAddrToSend.clear();
2437 pto->PushMessage("addr", vAddr);
2442 // Message: inventory
2445 vector<CInv> vInvWait;
2446 CRITICAL_BLOCK(pto->cs_inventory)
2448 vInv.reserve(pto->vInventoryToSend.size());
2449 vInvWait.reserve(pto->vInventoryToSend.size());
2450 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2452 if (pto->setInventoryKnown.count(inv))
2455 // trickle out tx inv to protect privacy
2456 if (inv.type == MSG_TX && !fSendTrickle)
2458 // 1/4 of tx invs blast to all immediately
2459 static uint256 hashSalt;
2461 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2462 uint256 hashRand = inv.hash ^ hashSalt;
2463 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2464 bool fTrickleWait = ((hashRand & 3) != 0);
2466 // always trickle our own transactions
2470 if (GetTransaction(inv.hash, wtx))
2472 fTrickleWait = true;
2477 vInvWait.push_back(inv);
2482 // returns true if wasn't already contained in the set
2483 if (pto->setInventoryKnown.insert(inv).second)
2485 vInv.push_back(inv);
2486 if (vInv.size() >= 1000)
2488 pto->PushMessage("inv", vInv);
2493 pto->vInventoryToSend = vInvWait;
2496 pto->PushMessage("inv", vInv);
2502 vector<CInv> vGetData;
2503 int64 nNow = GetTime() * 1000000;
2505 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2507 const CInv& inv = (*pto->mapAskFor.begin()).second;
2508 if (!AlreadyHave(txdb, inv))
2510 printf("sending getdata: %s\n", inv.ToString().c_str());
2511 vGetData.push_back(inv);
2512 if (vGetData.size() >= 1000)
2514 pto->PushMessage("getdata", vGetData);
2518 mapAlreadyAskedFor[inv] = nNow;
2519 pto->mapAskFor.erase(pto->mapAskFor.begin());
2521 if (!vGetData.empty())
2522 pto->PushMessage("getdata", vGetData);
2541 //////////////////////////////////////////////////////////////////////////////
2546 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2548 unsigned char* pdata = (unsigned char*)pbuffer;
2549 unsigned int blocks = 1 + ((len + 8) / 64);
2550 unsigned char* pend = pdata + 64 * blocks;
2551 memset(pdata + len, 0, 64 * blocks - len);
2553 unsigned int bits = len * 8;
2554 pend[-1] = (bits >> 0) & 0xff;
2555 pend[-2] = (bits >> 8) & 0xff;
2556 pend[-3] = (bits >> 16) & 0xff;
2557 pend[-4] = (bits >> 24) & 0xff;
2561 using CryptoPP::ByteReverse;
2563 static const unsigned int pSHA256InitState[8] =
2564 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2566 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2568 memcpy(pstate, pinit, 32);
2569 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2573 // ScanHash scans nonces looking for a hash with at least some zero bits.
2574 // It operates on big endian data. Caller does the byte reversing.
2575 // All input buffers are 16-byte aligned. nNonce is usually preserved
2576 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2577 // the block is rebuilt and nNonce starts over at zero.
2579 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2581 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2585 // Hash pdata using pmidstate as the starting state into
2586 // preformatted buffer phash1, then hash phash1 into phash
2588 SHA256Transform(phash1, pdata, pmidstate);
2589 SHA256Transform(phash, phash1, pSHA256InitState);
2591 // Return the nonce if the hash has at least some zero bits,
2592 // caller will check if it has enough to reach the target
2593 if (((unsigned short*)phash)[14] == 0)
2596 // If nothing found after trying for a while, return -1
2597 if ((nNonce & 0xffff) == 0)
2599 nHashesDone = 0xffff+1;
2605 // Some explaining would be appreciated
2610 set<uint256> setDependsOn;
2613 COrphan(CTransaction* ptxIn)
2621 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2622 BOOST_FOREACH(uint256 hash, setDependsOn)
2623 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2628 CBlock* CreateNewBlock(CReserveKey& reservekey)
2630 CBlockIndex* pindexPrev = pindexBest;
2633 auto_ptr<CBlock> pblock(new CBlock());
2637 // Create coinbase tx
2639 txNew.vin.resize(1);
2640 txNew.vin[0].prevout.SetNull();
2641 txNew.vout.resize(1);
2642 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2644 // Add our coinbase tx as first transaction
2645 pblock->vtx.push_back(txNew);
2647 // Collect memory pool transactions into the block
2649 CRITICAL_BLOCK(cs_main)
2650 CRITICAL_BLOCK(cs_mapTransactions)
2654 // Priority order to process transactions
2655 list<COrphan> vOrphan; // list memory doesn't move
2656 map<uint256, vector<COrphan*> > mapDependers;
2657 multimap<double, CTransaction*> mapPriority;
2658 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2660 CTransaction& tx = (*mi).second;
2661 if (tx.IsCoinBase() || !tx.IsFinal())
2664 COrphan* porphan = NULL;
2665 double dPriority = 0;
2666 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2668 // Read prev transaction
2669 CTransaction txPrev;
2671 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2673 // Has to wait for dependencies
2676 // Use list for automatic deletion
2677 vOrphan.push_back(COrphan(&tx));
2678 porphan = &vOrphan.back();
2680 mapDependers[txin.prevout.hash].push_back(porphan);
2681 porphan->setDependsOn.insert(txin.prevout.hash);
2684 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2686 // Read block header
2687 int nConf = txindex.GetDepthInMainChain();
2689 dPriority += (double)nValueIn * nConf;
2691 if (fDebug && GetBoolArg("-printpriority"))
2692 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2695 // Priority is sum(valuein * age) / txsize
2696 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2699 porphan->dPriority = dPriority;
2701 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2703 if (fDebug && GetBoolArg("-printpriority"))
2705 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2712 // Collect transactions into block
2713 map<uint256, CTxIndex> mapTestPool;
2714 uint64 nBlockSize = 1000;
2715 int nBlockSigOps = 100;
2716 while (!mapPriority.empty())
2718 // Take highest priority transaction off priority queue
2719 double dPriority = -(*mapPriority.begin()).first;
2720 CTransaction& tx = *(*mapPriority.begin()).second;
2721 mapPriority.erase(mapPriority.begin());
2724 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2725 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2727 int nTxSigOps = tx.GetSigOpCount();
2728 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2731 // ppcoin: simplify transaction fee - allow free = false
2732 int64 nMinFee = tx.GetMinFee(nBlockSize, false, true);
2734 // Connecting shouldn't fail due to dependency on other memory pool transactions
2735 // because we're already processing them in order of dependency
2736 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2737 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2739 swap(mapTestPool, mapTestPoolTmp);
2742 pblock->vtx.push_back(tx);
2743 nBlockSize += nTxSize;
2744 nBlockSigOps += nTxSigOps;
2746 // Add transactions that depend on this one to the priority queue
2747 uint256 hash = tx.GetHash();
2748 if (mapDependers.count(hash))
2750 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2752 if (!porphan->setDependsOn.empty())
2754 porphan->setDependsOn.erase(hash);
2755 if (porphan->setDependsOn.empty())
2756 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2762 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2765 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2766 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2767 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2768 pblock->nBits = GetNextWorkRequired(pindexPrev);
2771 return pblock.release();
2775 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2777 // Update nExtraNonce
2778 static uint256 hashPrevBlock;
2779 if (hashPrevBlock != pblock->hashPrevBlock)
2782 hashPrevBlock = pblock->hashPrevBlock;
2785 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
2786 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2790 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2793 // Prebuild hash buffers
2800 uint256 hashPrevBlock;
2801 uint256 hashMerkleRoot;
2804 unsigned int nNonce;
2807 unsigned char pchPadding0[64];
2809 unsigned char pchPadding1[64];
2812 memset(&tmp, 0, sizeof(tmp));
2814 tmp.block.nVersion = pblock->nVersion;
2815 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2816 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2817 tmp.block.nTime = pblock->nTime;
2818 tmp.block.nBits = pblock->nBits;
2819 tmp.block.nNonce = pblock->nNonce;
2821 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2822 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2824 // Byte swap all the input buffer
2825 for (int i = 0; i < sizeof(tmp)/4; i++)
2826 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2828 // Precalc the first half of the first hash, which stays constant
2829 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2831 memcpy(pdata, &tmp.block, 128);
2832 memcpy(phash1, &tmp.hash1, 64);
2836 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2838 uint256 hash = pblock->GetHash();
2839 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2841 if (hash > hashTarget)
2845 printf("BitcoinMiner:\n");
2846 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2848 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2849 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2852 CRITICAL_BLOCK(cs_main)
2854 if (pblock->hashPrevBlock != hashBestChain)
2855 return error("BitcoinMiner : generated block is stale");
2857 // Remove key from key pool
2858 reservekey.KeepKey();
2860 // Track how many getdata requests this block gets
2861 CRITICAL_BLOCK(wallet.cs_wallet)
2862 wallet.mapRequestCount[pblock->GetHash()] = 0;
2864 // Process this block the same as if we had received it from another node
2865 if (!ProcessBlock(NULL, pblock))
2866 return error("BitcoinMiner : ProcessBlock, block not accepted");
2873 void static ThreadBitcoinMiner(void* parg);
2875 void static BitcoinMiner(CWallet *pwallet)
2877 printf("BitcoinMiner started\n");
2878 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2880 // Each thread has its own key and counter
2881 CReserveKey reservekey(pwallet);
2882 unsigned int nExtraNonce = 0;
2884 while (fGenerateBitcoins)
2886 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2890 while (vNodes.empty() || IsInitialBlockDownload())
2895 if (!fGenerateBitcoins)
2903 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2904 CBlockIndex* pindexPrev = pindexBest;
2906 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2909 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
2911 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2915 // Prebuild hash buffers
2917 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
2918 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
2919 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
2921 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
2923 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
2924 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
2930 int64 nStart = GetTime();
2931 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2933 uint256& hash = *alignup<16>(hashbuf);
2936 unsigned int nHashesDone = 0;
2937 unsigned int nNonceFound;
2940 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
2941 (char*)&hash, nHashesDone);
2943 // Check if something found
2944 if (nNonceFound != -1)
2946 for (int i = 0; i < sizeof(hash)/4; i++)
2947 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
2949 if (hash <= hashTarget)
2952 pblock->nNonce = ByteReverse(nNonceFound);
2953 assert(hash == pblock->GetHash());
2955 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2956 CheckWork(pblock.get(), *pwalletMain, reservekey);
2957 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2963 static int64 nHashCounter;
2964 if (nHPSTimerStart == 0)
2966 nHPSTimerStart = GetTimeMillis();
2970 nHashCounter += nHashesDone;
2971 if (GetTimeMillis() - nHPSTimerStart > 4000)
2973 static CCriticalSection cs;
2976 if (GetTimeMillis() - nHPSTimerStart > 4000)
2978 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
2979 nHPSTimerStart = GetTimeMillis();
2981 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
2982 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
2983 static int64 nLogTime;
2984 if (GetTime() - nLogTime > 30 * 60)
2986 nLogTime = GetTime();
2987 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2988 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
2994 // Check for stop or if block needs to be rebuilt
2997 if (!fGenerateBitcoins)
2999 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3003 if (nBlockNonce >= 0xffff0000)
3005 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3007 if (pindexPrev != pindexBest)
3010 // Update nTime every few seconds
3011 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3012 nBlockTime = ByteReverse(pblock->nTime);
3017 void static ThreadBitcoinMiner(void* parg)
3019 CWallet* pwallet = (CWallet*)parg;
3022 vnThreadsRunning[3]++;
3023 BitcoinMiner(pwallet);
3024 vnThreadsRunning[3]--;
3026 catch (std::exception& e) {
3027 vnThreadsRunning[3]--;
3028 PrintException(&e, "ThreadBitcoinMiner()");
3030 vnThreadsRunning[3]--;
3031 PrintException(NULL, "ThreadBitcoinMiner()");
3033 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3035 if (vnThreadsRunning[3] == 0)
3037 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3041 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3043 if (fGenerateBitcoins != fGenerate)
3045 fGenerateBitcoins = fGenerate;
3046 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3049 if (fGenerateBitcoins)
3051 int nProcessors = boost::thread::hardware_concurrency();
3052 printf("%d processors\n", nProcessors);
3053 if (nProcessors < 1)
3055 if (fLimitProcessors && nProcessors > nLimitProcessors)
3056 nProcessors = nLimitProcessors;
3057 int nAddThreads = nProcessors - vnThreadsRunning[3];
3058 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3059 for (int i = 0; i < nAddThreads; i++)
3061 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3062 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");