1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8 #include "cryptopp/sha.h"
9 #include <boost/filesystem/fstream.hpp>
12 using namespace boost;
18 CCriticalSection cs_main;
20 map<uint256, CTransaction> mapTransactions;
21 CCriticalSection cs_mapTransactions;
22 unsigned int nTransactionsUpdated = 0;
23 map<COutPoint, CInPoint> mapNextTx;
25 map<uint256, CBlockIndex*> mapBlockIndex;
26 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
27 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
28 CBlockIndex* pindexGenesisBlock = NULL;
30 CBigNum bnBestChainWork = 0;
31 CBigNum bnBestInvalidWork = 0;
32 uint256 hashBestChain = 0;
33 CBlockIndex* pindexBest = NULL;
34 int64 nTimeBestReceived = 0;
36 map<uint256, CBlock*> mapOrphanBlocks;
37 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
39 map<uint256, CDataStream*> mapOrphanTransactions;
40 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
42 map<uint256, CWalletTx> mapWallet;
43 vector<uint256> vWalletUpdated;
44 CCriticalSection cs_mapWallet;
46 map<vector<unsigned char>, CPrivKey> mapKeys;
47 map<uint160, vector<unsigned char> > mapPubKeys;
48 CCriticalSection cs_mapKeys;
51 map<uint256, int> mapRequestCount;
52 CCriticalSection cs_mapRequestCount;
54 map<string, string> mapAddressBook;
55 CCriticalSection cs_mapAddressBook;
57 set<int64> setKeyPool;
58 CCriticalSection cs_setKeyPool;
60 vector<unsigned char> vchDefaultKey;
66 int fGenerateBitcoins = false;
67 int64 nTransactionFee = 0;
68 CAddress addrIncoming;
69 int fLimitProcessors = false;
70 int nLimitProcessors = 1;
71 int fMinimizeToTray = true;
72 int fMinimizeOnClose = true;
85 //////////////////////////////////////////////////////////////////////////////
87 // mapOrphanTransactions
90 void AddOrphanTx(const CDataStream& vMsg)
93 CDataStream(vMsg) >> tx;
94 uint256 hash = tx.GetHash();
95 if (mapOrphanTransactions.count(hash))
97 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
98 BOOST_FOREACH(const CTxIn& txin, tx.vin)
99 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
102 void EraseOrphanTx(uint256 hash)
104 if (!mapOrphanTransactions.count(hash))
106 const CDataStream* pvMsg = mapOrphanTransactions[hash];
108 CDataStream(*pvMsg) >> tx;
109 BOOST_FOREACH(const CTxIn& txin, tx.vin)
111 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
112 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
114 if ((*mi).second == pvMsg)
115 mapOrphanTransactionsByPrev.erase(mi++);
121 mapOrphanTransactions.erase(hash);
131 //////////////////////////////////////////////////////////////////////////////
133 // CTransaction and CTxIndex
136 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
139 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
141 if (!ReadFromDisk(txindexRet.pos))
143 if (prevout.n >= vout.size())
151 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
154 return ReadFromDisk(txdb, prevout, txindex);
157 bool CTransaction::ReadFromDisk(COutPoint prevout)
161 return ReadFromDisk(txdb, prevout, txindex);
166 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
178 // Load the block this tx is in
180 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
182 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
187 // Update the tx's hashBlock
188 hashBlock = pblock->GetHash();
190 // Locate the transaction
191 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
192 if (pblock->vtx[nIndex] == *(CTransaction*)this)
194 if (nIndex == pblock->vtx.size())
196 vMerkleBranch.clear();
198 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
202 // Fill in merkle branch
203 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
206 // Is the tx in a block that's in the main chain
207 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
208 if (mi == mapBlockIndex.end())
210 CBlockIndex* pindex = (*mi).second;
211 if (!pindex || !pindex->IsInMainChain())
214 return pindexBest->nHeight - pindex->nHeight + 1;
223 bool CTransaction::CheckTransaction() const
225 // Basic checks that don't depend on any context
226 if (vin.empty() || vout.empty())
227 return error("CTransaction::CheckTransaction() : vin or vout empty");
230 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
231 return error("CTransaction::CheckTransaction() : size limits failed");
233 // Check for negative or overflow output values
235 BOOST_FOREACH(const CTxOut& txout, vout)
237 if (txout.nValue < 0)
238 return error("CTransaction::CheckTransaction() : txout.nValue negative");
239 if (txout.nValue > MAX_MONEY)
240 return error("CTransaction::CheckTransaction() : txout.nValue too high");
241 nValueOut += txout.nValue;
242 if (!MoneyRange(nValueOut))
243 return error("CTransaction::CheckTransaction() : txout total out of range");
248 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
249 return error("CTransaction::CheckTransaction() : coinbase script size");
253 BOOST_FOREACH(const CTxIn& txin, vin)
254 if (txin.prevout.IsNull())
255 return error("CTransaction::CheckTransaction() : prevout is null");
261 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
264 *pfMissingInputs = false;
266 if (!CheckTransaction())
267 return error("AcceptToMemoryPool() : CheckTransaction failed");
269 // Coinbase is only valid in a block, not as a loose transaction
271 return error("AcceptToMemoryPool() : coinbase as individual tx");
273 // To help v0.1.5 clients who would see it as a negative number
274 if ((int64)nLockTime > INT_MAX)
275 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
278 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
279 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
280 // attacks disallow transactions with more than one SigOp per 34 bytes.
281 // 34 bytes because a TxOut is:
282 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
283 if (GetSigOpCount() > nSize / 34 || nSize < 100)
284 return error("AcceptToMemoryPool() : nonstandard transaction");
286 // Rather not work on nonstandard transactions (unless -testnet)
287 if (!fTestNet && !IsStandard())
288 return error("AcceptToMemoryPool() : nonstandard transaction type");
290 // Do we already have it?
291 uint256 hash = GetHash();
292 CRITICAL_BLOCK(cs_mapTransactions)
293 if (mapTransactions.count(hash))
296 if (txdb.ContainsTx(hash))
299 // Check for conflicts with in-memory transactions
300 CTransaction* ptxOld = NULL;
301 for (int i = 0; i < vin.size(); i++)
303 COutPoint outpoint = vin[i].prevout;
304 if (mapNextTx.count(outpoint))
306 // Disable replacement feature for now
309 // Allow replacing with a newer version of the same transaction
312 ptxOld = mapNextTx[outpoint].ptx;
313 if (ptxOld->IsFinal())
315 if (!IsNewerThan(*ptxOld))
317 for (int i = 0; i < vin.size(); i++)
319 COutPoint outpoint = vin[i].prevout;
320 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
329 // Check against previous transactions
330 map<uint256, CTxIndex> mapUnused;
332 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
335 *pfMissingInputs = true;
336 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
339 // Don't accept it if it can't get into a block
340 if (nFees < GetMinFee(1000, true, true))
341 return error("AcceptToMemoryPool() : not enough fees");
343 // Continuously rate-limit free transactions
344 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
345 // be annoying or make other's transactions take longer to confirm.
346 if (nFees < MIN_RELAY_TX_FEE)
348 static CCriticalSection cs;
349 static double dFreeCount;
350 static int64 nLastTime;
351 int64 nNow = GetTime();
355 // Use an exponentially decaying ~10-minute window:
356 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
358 // -limitfreerelay unit is thousand-bytes-per-minute
359 // At default rate it would take over a month to fill 1GB
360 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())
361 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
363 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
369 // Store transaction in memory
370 CRITICAL_BLOCK(cs_mapTransactions)
374 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
375 ptxOld->RemoveFromMemoryPool();
377 AddToMemoryPoolUnchecked();
380 ///// are we sure this is ok when loading transactions or restoring block txes
381 // If updated, erase old tx from wallet
383 EraseFromWallet(ptxOld->GetHash());
385 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
389 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
392 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
395 bool CTransaction::AddToMemoryPoolUnchecked()
397 // Add to memory pool without checking anything. Don't call this directly,
398 // call AcceptToMemoryPool to properly check the transaction first.
399 CRITICAL_BLOCK(cs_mapTransactions)
401 uint256 hash = GetHash();
402 mapTransactions[hash] = *this;
403 for (int i = 0; i < vin.size(); i++)
404 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
405 nTransactionsUpdated++;
411 bool CTransaction::RemoveFromMemoryPool()
413 // Remove transaction from memory pool
414 CRITICAL_BLOCK(cs_mapTransactions)
416 BOOST_FOREACH(const CTxIn& txin, vin)
417 mapNextTx.erase(txin.prevout);
418 mapTransactions.erase(GetHash());
419 nTransactionsUpdated++;
429 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
431 if (hashBlock == 0 || nIndex == -1)
434 // Find the block it claims to be in
435 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
436 if (mi == mapBlockIndex.end())
438 CBlockIndex* pindex = (*mi).second;
439 if (!pindex || !pindex->IsInMainChain())
442 // Make sure the merkle branch connects to this block
443 if (!fMerkleVerified)
445 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
447 fMerkleVerified = true;
450 nHeightRet = pindex->nHeight;
451 return pindexBest->nHeight - pindex->nHeight + 1;
455 int CMerkleTx::GetBlocksToMaturity() const
459 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
463 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
467 if (!IsInMainChain() && !ClientConnectInputs())
469 return CTransaction::AcceptToMemoryPool(txdb, false);
473 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
477 bool CMerkleTx::AcceptToMemoryPool()
480 return AcceptToMemoryPool(txdb);
485 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
487 CRITICAL_BLOCK(cs_mapTransactions)
489 // Add previous supporting transactions first
490 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
492 if (!tx.IsCoinBase())
494 uint256 hash = tx.GetHash();
495 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
496 tx.AcceptToMemoryPool(txdb, fCheckInputs);
499 return AcceptToMemoryPool(txdb, fCheckInputs);
504 bool CWalletTx::AcceptWalletTransaction()
507 return AcceptWalletTransaction(txdb);
510 int CTxIndex::GetDepthInMainChain() const
514 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
516 // Find the block in the index
517 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
518 if (mi == mapBlockIndex.end())
520 CBlockIndex* pindex = (*mi).second;
521 if (!pindex || !pindex->IsInMainChain())
523 return 1 + nBestHeight - pindex->nHeight;
535 //////////////////////////////////////////////////////////////////////////////
537 // CBlock and CBlockIndex
540 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
542 if (!fReadTransactions)
544 *this = pindex->GetBlockHeader();
547 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
549 if (GetHash() != pindex->GetBlockHash())
550 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
555 uint256 GetOrphanRoot(const CBlock* pblock)
557 // Work back to the first block in the orphan chain
558 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
559 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
560 return pblock->GetHash();
563 int64 GetBlockValue(int nHeight, int64 nFees)
565 int64 nSubsidy = 50 * COIN;
567 // Subsidy is cut in half every 4 years
568 nSubsidy >>= (nHeight / 210000);
570 return nSubsidy + nFees;
573 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
575 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
576 const int64 nTargetSpacing = 10 * 60;
577 const int64 nInterval = nTargetTimespan / nTargetSpacing;
580 if (pindexLast == NULL)
581 return bnProofOfWorkLimit.GetCompact();
583 // Only change once per interval
584 if ((pindexLast->nHeight+1) % nInterval != 0)
585 return pindexLast->nBits;
587 // Go back by what we want to be 14 days worth of blocks
588 const CBlockIndex* pindexFirst = pindexLast;
589 for (int i = 0; pindexFirst && i < nInterval-1; i++)
590 pindexFirst = pindexFirst->pprev;
593 // Limit adjustment step
594 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
595 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
596 if (nActualTimespan < nTargetTimespan/4)
597 nActualTimespan = nTargetTimespan/4;
598 if (nActualTimespan > nTargetTimespan*4)
599 nActualTimespan = nTargetTimespan*4;
603 bnNew.SetCompact(pindexLast->nBits);
604 bnNew *= nActualTimespan;
605 bnNew /= nTargetTimespan;
607 if (bnNew > bnProofOfWorkLimit)
608 bnNew = bnProofOfWorkLimit;
611 printf("GetNextWorkRequired RETARGET\n");
612 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
613 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
614 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
616 return bnNew.GetCompact();
619 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
622 bnTarget.SetCompact(nBits);
625 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
626 return error("CheckProofOfWork() : nBits below minimum work");
628 // Check proof of work matches claimed amount
629 if (hash > bnTarget.getuint256())
630 return error("CheckProofOfWork() : hash doesn't match nBits");
635 bool IsInitialBlockDownload()
637 if (pindexBest == NULL || (!fTestNet && nBestHeight < 118000))
639 static int64 nLastUpdate;
640 static CBlockIndex* pindexLastBest;
641 if (pindexBest != pindexLastBest)
643 pindexLastBest = pindexBest;
644 nLastUpdate = GetTime();
646 return (GetTime() - nLastUpdate < 10 &&
647 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
650 void InvalidChainFound(CBlockIndex* pindexNew)
652 if (pindexNew->bnChainWork > bnBestInvalidWork)
654 bnBestInvalidWork = pindexNew->bnChainWork;
655 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
658 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());
659 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
660 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
661 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
674 bool CTransaction::DisconnectInputs(CTxDB& txdb)
676 // Relinquish previous transactions' spent pointers
679 BOOST_FOREACH(const CTxIn& txin, vin)
681 COutPoint prevout = txin.prevout;
683 // Get prev txindex from disk
685 if (!txdb.ReadTxIndex(prevout.hash, txindex))
686 return error("DisconnectInputs() : ReadTxIndex failed");
688 if (prevout.n >= txindex.vSpent.size())
689 return error("DisconnectInputs() : prevout.n out of range");
691 // Mark outpoint as not spent
692 txindex.vSpent[prevout.n].SetNull();
695 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
696 return error("DisconnectInputs() : UpdateTxIndex failed");
700 // Remove transaction from index
701 if (!txdb.EraseTxIndex(*this))
702 return error("DisconnectInputs() : EraseTxPos failed");
708 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
709 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
711 // Take over previous transactions' spent pointers
715 for (int i = 0; i < vin.size(); i++)
717 COutPoint prevout = vin[i].prevout;
722 if (fMiner && mapTestPool.count(prevout.hash))
724 // Get txindex from current proposed changes
725 txindex = mapTestPool[prevout.hash];
729 // Read txindex from txdb
730 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
732 if (!fFound && (fBlock || fMiner))
733 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());
737 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
739 // Get prev tx from single transactions in memory
740 CRITICAL_BLOCK(cs_mapTransactions)
742 if (!mapTransactions.count(prevout.hash))
743 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
744 txPrev = mapTransactions[prevout.hash];
747 txindex.vSpent.resize(txPrev.vout.size());
751 // Get prev tx from disk
752 if (!txPrev.ReadFromDisk(txindex.pos))
753 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
756 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
757 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());
759 // If prev is coinbase, check that it's matured
760 if (txPrev.IsCoinBase())
761 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
762 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
763 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
766 if (!VerifySignature(txPrev, *this, i))
767 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
769 // Check for conflicts
770 if (!txindex.vSpent[prevout.n].IsNull())
771 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());
773 // Check for negative or overflow input values
774 nValueIn += txPrev.vout[prevout.n].nValue;
775 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
776 return error("ConnectInputs() : txin values out of range");
778 // Mark outpoints as spent
779 txindex.vSpent[prevout.n] = posThisTx;
784 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
785 return error("ConnectInputs() : UpdateTxIndex failed");
789 mapTestPool[prevout.hash] = txindex;
793 if (nValueIn < GetValueOut())
794 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
796 // Tally transaction fees
797 int64 nTxFee = nValueIn - GetValueOut();
799 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
800 if (nTxFee < nMinFee)
803 if (!MoneyRange(nFees))
804 return error("ConnectInputs() : nFees out of range");
809 // Add transaction to disk index
810 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
811 return error("ConnectInputs() : AddTxPos failed");
815 // Add transaction to test pool
816 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
823 bool CTransaction::ClientConnectInputs()
828 // Take over previous transactions' spent pointers
829 CRITICAL_BLOCK(cs_mapTransactions)
832 for (int i = 0; i < vin.size(); i++)
834 // Get prev tx from single transactions in memory
835 COutPoint prevout = vin[i].prevout;
836 if (!mapTransactions.count(prevout.hash))
838 CTransaction& txPrev = mapTransactions[prevout.hash];
840 if (prevout.n >= txPrev.vout.size())
844 if (!VerifySignature(txPrev, *this, i))
845 return error("ConnectInputs() : VerifySignature failed");
847 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
848 ///// this has to go away now that posNext is gone
849 // // Check for conflicts
850 // if (!txPrev.vout[prevout.n].posNext.IsNull())
851 // return error("ConnectInputs() : prev tx already used");
853 // // Flag outpoints as used
854 // txPrev.vout[prevout.n].posNext = posThisTx;
856 nValueIn += txPrev.vout[prevout.n].nValue;
858 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
859 return error("ClientConnectInputs() : txin values out of range");
861 if (GetValueOut() > nValueIn)
871 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
873 // Disconnect in reverse order
874 for (int i = vtx.size()-1; i >= 0; i--)
875 if (!vtx[i].DisconnectInputs(txdb))
878 // Update block index on disk without changing it in memory.
879 // The memory index structure will be changed after the db commits.
882 CDiskBlockIndex blockindexPrev(pindex->pprev);
883 blockindexPrev.hashNext = 0;
884 if (!txdb.WriteBlockIndex(blockindexPrev))
885 return error("DisconnectBlock() : WriteBlockIndex failed");
891 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
893 // Check it again in case a previous version let a bad block in
897 //// issue here: it doesn't know the version
898 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
900 map<uint256, CTxIndex> mapUnused;
902 BOOST_FOREACH(CTransaction& tx, vtx)
904 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
905 nTxPos += ::GetSerializeSize(tx, SER_DISK);
907 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
911 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
914 // Update block index on disk without changing it in memory.
915 // The memory index structure will be changed after the db commits.
918 CDiskBlockIndex blockindexPrev(pindex->pprev);
919 blockindexPrev.hashNext = pindex->GetBlockHash();
920 if (!txdb.WriteBlockIndex(blockindexPrev))
921 return error("ConnectBlock() : WriteBlockIndex failed");
924 // Watch for transactions paying to me
925 BOOST_FOREACH(CTransaction& tx, vtx)
926 AddToWalletIfInvolvingMe(tx, this, true);
931 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
933 printf("REORGANIZE\n");
936 CBlockIndex* pfork = pindexBest;
937 CBlockIndex* plonger = pindexNew;
938 while (pfork != plonger)
940 while (plonger->nHeight > pfork->nHeight)
941 if (!(plonger = plonger->pprev))
942 return error("Reorganize() : plonger->pprev is null");
943 if (pfork == plonger)
945 if (!(pfork = pfork->pprev))
946 return error("Reorganize() : pfork->pprev is null");
949 // List of what to disconnect
950 vector<CBlockIndex*> vDisconnect;
951 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
952 vDisconnect.push_back(pindex);
954 // List of what to connect
955 vector<CBlockIndex*> vConnect;
956 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
957 vConnect.push_back(pindex);
958 reverse(vConnect.begin(), vConnect.end());
960 // Disconnect shorter branch
961 vector<CTransaction> vResurrect;
962 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
965 if (!block.ReadFromDisk(pindex))
966 return error("Reorganize() : ReadFromDisk for disconnect failed");
967 if (!block.DisconnectBlock(txdb, pindex))
968 return error("Reorganize() : DisconnectBlock failed");
970 // Queue memory transactions to resurrect
971 BOOST_FOREACH(const CTransaction& tx, block.vtx)
972 if (!tx.IsCoinBase())
973 vResurrect.push_back(tx);
976 // Connect longer branch
977 vector<CTransaction> vDelete;
978 for (int i = 0; i < vConnect.size(); i++)
980 CBlockIndex* pindex = vConnect[i];
982 if (!block.ReadFromDisk(pindex))
983 return error("Reorganize() : ReadFromDisk for connect failed");
984 if (!block.ConnectBlock(txdb, pindex))
988 return error("Reorganize() : ConnectBlock failed");
991 // Queue memory transactions to delete
992 BOOST_FOREACH(const CTransaction& tx, block.vtx)
993 vDelete.push_back(tx);
995 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
996 return error("Reorganize() : WriteHashBestChain failed");
998 // Make sure it's successfully written to disk before changing memory structure
999 if (!txdb.TxnCommit())
1000 return error("Reorganize() : TxnCommit failed");
1002 // Disconnect shorter branch
1003 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1005 pindex->pprev->pnext = NULL;
1007 // Connect longer branch
1008 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1010 pindex->pprev->pnext = pindex;
1012 // Resurrect memory transactions that were in the disconnected branch
1013 BOOST_FOREACH(CTransaction& tx, vResurrect)
1014 tx.AcceptToMemoryPool(txdb, false);
1016 // Delete redundant memory transactions that are in the connected branch
1017 BOOST_FOREACH(CTransaction& tx, vDelete)
1018 tx.RemoveFromMemoryPool();
1024 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1026 uint256 hash = GetHash();
1029 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1031 txdb.WriteHashBestChain(hash);
1032 if (!txdb.TxnCommit())
1033 return error("SetBestChain() : TxnCommit failed");
1034 pindexGenesisBlock = pindexNew;
1036 else if (hashPrevBlock == hashBestChain)
1038 // Adding to current best branch
1039 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1042 InvalidChainFound(pindexNew);
1043 return error("SetBestChain() : ConnectBlock failed");
1045 if (!txdb.TxnCommit())
1046 return error("SetBestChain() : TxnCommit failed");
1048 // Add to current best branch
1049 pindexNew->pprev->pnext = pindexNew;
1051 // Delete redundant memory transactions
1052 BOOST_FOREACH(CTransaction& tx, vtx)
1053 tx.RemoveFromMemoryPool();
1058 if (!Reorganize(txdb, pindexNew))
1061 InvalidChainFound(pindexNew);
1062 return error("SetBestChain() : Reorganize failed");
1066 // Update best block in wallet (so we can detect restored wallets)
1067 if (!IsInitialBlockDownload())
1070 const CBlockLocator locator(pindexNew);
1071 if (!walletdb.WriteBestBlock(locator))
1072 return error("SetBestChain() : WriteWalletBest failed");
1076 hashBestChain = hash;
1077 pindexBest = pindexNew;
1078 nBestHeight = pindexBest->nHeight;
1079 bnBestChainWork = pindexNew->bnChainWork;
1080 nTimeBestReceived = GetTime();
1081 nTransactionsUpdated++;
1082 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1088 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1090 // Check for duplicate
1091 uint256 hash = GetHash();
1092 if (mapBlockIndex.count(hash))
1093 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1095 // Construct new block index object
1096 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1098 return error("AddToBlockIndex() : new CBlockIndex failed");
1099 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1100 pindexNew->phashBlock = &((*mi).first);
1101 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1102 if (miPrev != mapBlockIndex.end())
1104 pindexNew->pprev = (*miPrev).second;
1105 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1107 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1111 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1112 if (!txdb.TxnCommit())
1116 if (pindexNew->bnChainWork > bnBestChainWork)
1117 if (!SetBestChain(txdb, pindexNew))
1122 if (pindexNew == pindexBest)
1124 // Notify UI to display prev block's coinbase if it was ours
1125 static uint256 hashPrevBestCoinBase;
1126 CRITICAL_BLOCK(cs_mapWallet)
1127 vWalletUpdated.push_back(hashPrevBestCoinBase);
1128 hashPrevBestCoinBase = vtx[0].GetHash();
1138 bool CBlock::CheckBlock() const
1140 // These are checks that are independent of context
1141 // that can be verified before saving an orphan block.
1144 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1145 return error("CheckBlock() : size limits failed");
1147 // Check proof of work matches claimed amount
1148 if (!CheckProofOfWork(GetHash(), nBits))
1149 return error("CheckBlock() : proof of work failed");
1152 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1153 return error("CheckBlock() : block timestamp too far in the future");
1155 // First transaction must be coinbase, the rest must not be
1156 if (vtx.empty() || !vtx[0].IsCoinBase())
1157 return error("CheckBlock() : first tx is not coinbase");
1158 for (int i = 1; i < vtx.size(); i++)
1159 if (vtx[i].IsCoinBase())
1160 return error("CheckBlock() : more than one coinbase");
1162 // Check transactions
1163 BOOST_FOREACH(const CTransaction& tx, vtx)
1164 if (!tx.CheckTransaction())
1165 return error("CheckBlock() : CheckTransaction failed");
1167 // Check that it's not full of nonstandard transactions
1168 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1169 return error("CheckBlock() : too many nonstandard transactions");
1172 if (hashMerkleRoot != BuildMerkleTree())
1173 return error("CheckBlock() : hashMerkleRoot mismatch");
1178 bool CBlock::AcceptBlock()
1180 // Check for duplicate
1181 uint256 hash = GetHash();
1182 if (mapBlockIndex.count(hash))
1183 return error("AcceptBlock() : block already in mapBlockIndex");
1185 // Get prev block index
1186 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1187 if (mi == mapBlockIndex.end())
1188 return error("AcceptBlock() : prev block not found");
1189 CBlockIndex* pindexPrev = (*mi).second;
1190 int nHeight = pindexPrev->nHeight+1;
1192 // Check proof of work
1193 if (nBits != GetNextWorkRequired(pindexPrev))
1194 return error("AcceptBlock() : incorrect proof of work");
1196 // Check timestamp against prev
1197 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1198 return error("AcceptBlock() : block's timestamp is too early");
1200 // Check that all transactions are finalized
1201 BOOST_FOREACH(const CTransaction& tx, vtx)
1202 if (!tx.IsFinal(nHeight, GetBlockTime()))
1203 return error("AcceptBlock() : contains a non-final transaction");
1205 // Check that the block chain matches the known block chain up to a checkpoint
1207 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1208 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1209 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1210 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1211 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1212 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1213 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))
1214 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1216 // Write block to history file
1217 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1218 return error("AcceptBlock() : out of disk space");
1219 unsigned int nFile = -1;
1220 unsigned int nBlockPos = 0;
1221 if (!WriteToDisk(nFile, nBlockPos))
1222 return error("AcceptBlock() : WriteToDisk failed");
1223 if (!AddToBlockIndex(nFile, nBlockPos))
1224 return error("AcceptBlock() : AddToBlockIndex failed");
1226 // Relay inventory, but don't relay old inventory during initial block download
1227 if (hashBestChain == hash)
1228 CRITICAL_BLOCK(cs_vNodes)
1229 BOOST_FOREACH(CNode* pnode, vNodes)
1230 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
1231 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1236 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1238 // Check for duplicate
1239 uint256 hash = pblock->GetHash();
1240 if (mapBlockIndex.count(hash))
1241 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1242 if (mapOrphanBlocks.count(hash))
1243 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1245 // Preliminary checks
1246 if (!pblock->CheckBlock())
1247 return error("ProcessBlock() : CheckBlock FAILED");
1249 // If don't already have its previous block, shunt it off to holding area until we get it
1250 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1252 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1253 CBlock* pblock2 = new CBlock(*pblock);
1254 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1255 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1257 // Ask this guy to fill in what we're missing
1259 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1264 if (!pblock->AcceptBlock())
1265 return error("ProcessBlock() : AcceptBlock FAILED");
1267 // Recursively process any orphan blocks that depended on this one
1268 vector<uint256> vWorkQueue;
1269 vWorkQueue.push_back(hash);
1270 for (int i = 0; i < vWorkQueue.size(); i++)
1272 uint256 hashPrev = vWorkQueue[i];
1273 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1274 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1277 CBlock* pblockOrphan = (*mi).second;
1278 if (pblockOrphan->AcceptBlock())
1279 vWorkQueue.push_back(pblockOrphan->GetHash());
1280 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1281 delete pblockOrphan;
1283 mapOrphanBlocksByPrev.erase(hashPrev);
1286 printf("ProcessBlock: ACCEPTED\n");
1297 template<typename Stream>
1298 bool ScanMessageStart(Stream& s)
1300 // Scan ahead to the next pchMessageStart, which should normally be immediately
1301 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1303 short prevmask = s.exceptions(0);
1304 const char* p = BEGIN(pchMessageStart);
1314 s.exceptions(prevmask);
1318 p = BEGIN(pchMessageStart);
1321 if (++p == END(pchMessageStart))
1324 s.exceptions(prevmask);
1333 s.exceptions(prevmask);
1338 bool CheckDiskSpace(uint64 nAdditionalBytes)
1340 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1342 // Check for 15MB because database could create another 10MB log file at any time
1343 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1346 string strMessage = _("Warning: Disk space is low ");
1347 strMiscWarning = strMessage;
1348 printf("*** %s\n", strMessage.c_str());
1349 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1350 CreateThread(Shutdown, NULL);
1356 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1360 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1363 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1365 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1374 static unsigned int nCurrentBlockFile = 1;
1376 FILE* AppendBlockFile(unsigned int& nFileRet)
1381 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1384 if (fseek(file, 0, SEEK_END) != 0)
1386 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1387 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1389 nFileRet = nCurrentBlockFile;
1393 nCurrentBlockFile++;
1397 bool LoadBlockIndex(bool fAllowNew)
1401 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1402 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1403 pchMessageStart[0] = 0xfa;
1404 pchMessageStart[1] = 0xbf;
1405 pchMessageStart[2] = 0xb5;
1406 pchMessageStart[3] = 0xda;
1413 if (!txdb.LoadBlockIndex())
1418 // Init with genesis block
1420 if (mapBlockIndex.empty())
1426 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1427 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1428 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1429 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1430 // vMerkleTree: 4a5e1e
1433 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1435 txNew.vin.resize(1);
1436 txNew.vout.resize(1);
1437 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1438 txNew.vout[0].nValue = 50 * COIN;
1439 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1441 block.vtx.push_back(txNew);
1442 block.hashPrevBlock = 0;
1443 block.hashMerkleRoot = block.BuildMerkleTree();
1445 block.nTime = 1231006505;
1446 block.nBits = 0x1d00ffff;
1447 block.nNonce = 2083236893;
1451 block.nTime = 1296688602;
1452 block.nBits = 0x1d07fff8;
1453 block.nNonce = 384568319;
1457 printf("%s\n", block.GetHash().ToString().c_str());
1458 printf("%s\n", hashGenesisBlock.ToString().c_str());
1459 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1460 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1462 assert(block.GetHash() == hashGenesisBlock);
1464 // Start new block file
1466 unsigned int nBlockPos;
1467 if (!block.WriteToDisk(nFile, nBlockPos))
1468 return error("LoadBlockIndex() : writing genesis block to disk failed");
1469 if (!block.AddToBlockIndex(nFile, nBlockPos))
1470 return error("LoadBlockIndex() : genesis block not accepted");
1478 void PrintBlockTree()
1480 // precompute tree structure
1481 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1482 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1484 CBlockIndex* pindex = (*mi).second;
1485 mapNext[pindex->pprev].push_back(pindex);
1487 //while (rand() % 3 == 0)
1488 // mapNext[pindex->pprev].push_back(pindex);
1491 vector<pair<int, CBlockIndex*> > vStack;
1492 vStack.push_back(make_pair(0, pindexGenesisBlock));
1495 while (!vStack.empty())
1497 int nCol = vStack.back().first;
1498 CBlockIndex* pindex = vStack.back().second;
1501 // print split or gap
1502 if (nCol > nPrevCol)
1504 for (int i = 0; i < nCol-1; i++)
1508 else if (nCol < nPrevCol)
1510 for (int i = 0; i < nCol; i++)
1517 for (int i = 0; i < nCol; i++)
1522 block.ReadFromDisk(pindex);
1523 printf("%d (%u,%u) %s %s tx %d",
1527 block.GetHash().ToString().substr(0,20).c_str(),
1528 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1531 CRITICAL_BLOCK(cs_mapWallet)
1533 if (mapWallet.count(block.vtx[0].GetHash()))
1535 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1536 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1542 // put the main timechain first
1543 vector<CBlockIndex*>& vNext = mapNext[pindex];
1544 for (int i = 0; i < vNext.size(); i++)
1546 if (vNext[i]->pnext)
1548 swap(vNext[0], vNext[i]);
1554 for (int i = 0; i < vNext.size(); i++)
1555 vStack.push_back(make_pair(nCol+i, vNext[i]));
1568 //////////////////////////////////////////////////////////////////////////////
1573 map<uint256, CAlert> mapAlerts;
1574 CCriticalSection cs_mapAlerts;
1576 string GetWarnings(string strFor)
1579 string strStatusBar;
1581 if (GetBoolArg("-testsafemode"))
1584 // Misc warnings like out of disk space and clock is wrong
1585 if (strMiscWarning != "")
1588 strStatusBar = strMiscWarning;
1591 // Longer invalid proof-of-work chain
1592 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1595 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1599 CRITICAL_BLOCK(cs_mapAlerts)
1601 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1603 const CAlert& alert = item.second;
1604 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1606 nPriority = alert.nPriority;
1607 strStatusBar = alert.strStatusBar;
1612 if (strFor == "statusbar")
1613 return strStatusBar;
1614 else if (strFor == "rpc")
1616 assert(("GetWarnings() : invalid parameter", false));
1620 bool CAlert::ProcessAlert()
1622 if (!CheckSignature())
1627 CRITICAL_BLOCK(cs_mapAlerts)
1629 // Cancel previous alerts
1630 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1632 const CAlert& alert = (*mi).second;
1635 printf("cancelling alert %d\n", alert.nID);
1636 mapAlerts.erase(mi++);
1638 else if (!alert.IsInEffect())
1640 printf("expiring alert %d\n", alert.nID);
1641 mapAlerts.erase(mi++);
1647 // Check if this alert has been cancelled
1648 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1650 const CAlert& alert = item.second;
1651 if (alert.Cancels(*this))
1653 printf("alert already cancelled by %d\n", alert.nID);
1659 mapAlerts.insert(make_pair(GetHash(), *this));
1662 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1674 //////////////////////////////////////////////////////////////////////////////
1680 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1684 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1685 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1687 // Don't know what it is, just say we already got one
1694 // The message start string is designed to be unlikely to occur in normal data.
1695 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1696 // a large 4-byte int at any alignment.
1697 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1700 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1702 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1703 RandAddSeedPerfmon();
1705 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1706 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1707 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1709 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1717 if (strCommand == "version")
1719 // Each connection can only send one version message
1720 if (pfrom->nVersion != 0)
1727 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1728 if (pfrom->nVersion == 10300)
1729 pfrom->nVersion = 300;
1730 if (pfrom->nVersion >= 106 && !vRecv.empty())
1731 vRecv >> addrFrom >> nNonce;
1732 if (pfrom->nVersion >= 106 && !vRecv.empty())
1733 vRecv >> pfrom->strSubVer;
1734 if (pfrom->nVersion >= 209 && !vRecv.empty())
1735 vRecv >> pfrom->nStartingHeight;
1737 if (pfrom->nVersion == 0)
1740 // Disconnect if we connected to ourself
1741 if (nNonce == nLocalHostNonce && nNonce > 1)
1743 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1744 pfrom->fDisconnect = true;
1748 // Be shy and don't send version until we hear
1749 if (pfrom->fInbound)
1750 pfrom->PushVersion();
1752 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1754 AddTimeData(pfrom->addr.ip, nTime);
1757 if (pfrom->nVersion >= 209)
1758 pfrom->PushMessage("verack");
1759 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1760 if (pfrom->nVersion < 209)
1761 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1763 if (!pfrom->fInbound)
1765 // Advertise our address
1766 if (addrLocalHost.IsRoutable() && !fUseProxy)
1768 CAddress addr(addrLocalHost);
1769 addr.nTime = GetAdjustedTime();
1770 pfrom->PushAddress(addr);
1773 // Get recent addresses
1774 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1776 pfrom->PushMessage("getaddr");
1777 pfrom->fGetAddr = true;
1781 // Ask the first connected node for block updates
1782 static int nAskedForBlocks;
1783 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1786 pfrom->PushGetBlocks(pindexBest, uint256(0));
1790 CRITICAL_BLOCK(cs_mapAlerts)
1791 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1792 item.second.RelayTo(pfrom);
1794 pfrom->fSuccessfullyConnected = true;
1796 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1800 else if (pfrom->nVersion == 0)
1802 // Must have a version message before anything else
1807 else if (strCommand == "verack")
1809 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1813 else if (strCommand == "addr")
1815 vector<CAddress> vAddr;
1818 // Don't want addr from older versions unless seeding
1819 if (pfrom->nVersion < 209)
1821 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1823 if (vAddr.size() > 1000)
1824 return error("message addr size() = %d", vAddr.size());
1826 // Store the new addresses
1827 int64 nNow = GetAdjustedTime();
1828 int64 nSince = nNow - 10 * 60;
1829 BOOST_FOREACH(CAddress& addr, vAddr)
1833 // ignore IPv6 for now, since it isn't implemented anyway
1836 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1837 addr.nTime = nNow - 5 * 24 * 60 * 60;
1838 AddAddress(addr, 2 * 60 * 60);
1839 pfrom->AddAddressKnown(addr);
1840 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1842 // Relay to a limited number of other nodes
1843 CRITICAL_BLOCK(cs_vNodes)
1845 // Use deterministic randomness to send to the same nodes for 24 hours
1846 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1847 static uint256 hashSalt;
1849 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1850 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1851 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1852 multimap<uint256, CNode*> mapMix;
1853 BOOST_FOREACH(CNode* pnode, vNodes)
1855 if (pnode->nVersion < 31402)
1857 unsigned int nPointer;
1858 memcpy(&nPointer, &pnode, sizeof(nPointer));
1859 uint256 hashKey = hashRand ^ nPointer;
1860 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1861 mapMix.insert(make_pair(hashKey, pnode));
1863 int nRelayNodes = 2;
1864 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1865 ((*mi).second)->PushAddress(addr);
1869 if (vAddr.size() < 1000)
1870 pfrom->fGetAddr = false;
1874 else if (strCommand == "inv")
1878 if (vInv.size() > 50000)
1879 return error("message inv size() = %d", vInv.size());
1882 BOOST_FOREACH(const CInv& inv, vInv)
1886 pfrom->AddInventoryKnown(inv);
1888 bool fAlreadyHave = AlreadyHave(txdb, inv);
1889 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1893 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
1894 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
1896 // Track requests for our stuff
1897 CRITICAL_BLOCK(cs_mapRequestCount)
1899 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
1900 if (mi != mapRequestCount.end())
1907 else if (strCommand == "getdata")
1911 if (vInv.size() > 50000)
1912 return error("message getdata size() = %d", vInv.size());
1914 BOOST_FOREACH(const CInv& inv, vInv)
1918 printf("received getdata for: %s\n", inv.ToString().c_str());
1920 if (inv.type == MSG_BLOCK)
1922 // Send block from disk
1923 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
1924 if (mi != mapBlockIndex.end())
1927 block.ReadFromDisk((*mi).second);
1928 pfrom->PushMessage("block", block);
1930 // Trigger them to send a getblocks request for the next batch of inventory
1931 if (inv.hash == pfrom->hashContinue)
1933 // Bypass PushInventory, this must send even if redundant,
1934 // and we want it right after the last block so they don't
1935 // wait for other stuff first.
1937 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
1938 pfrom->PushMessage("inv", vInv);
1939 pfrom->hashContinue = 0;
1943 else if (inv.IsKnownType())
1945 // Send stream from relay memory
1946 CRITICAL_BLOCK(cs_mapRelay)
1948 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
1949 if (mi != mapRelay.end())
1950 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
1954 // Track requests for our stuff
1955 CRITICAL_BLOCK(cs_mapRequestCount)
1957 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
1958 if (mi != mapRequestCount.end())
1965 else if (strCommand == "getblocks")
1967 CBlockLocator locator;
1969 vRecv >> locator >> hashStop;
1971 // Find the last block the caller has in the main chain
1972 CBlockIndex* pindex = locator.GetBlockIndex();
1974 // Send the rest of the chain
1976 pindex = pindex->pnext;
1977 int nLimit = 500 + locator.GetDistanceBack();
1978 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
1979 for (; pindex; pindex = pindex->pnext)
1981 if (pindex->GetBlockHash() == hashStop)
1983 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
1986 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1989 // When this block is requested, we'll send an inv that'll make them
1990 // getblocks the next batch of inventory.
1991 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
1992 pfrom->hashContinue = pindex->GetBlockHash();
1999 else if (strCommand == "getheaders")
2001 CBlockLocator locator;
2003 vRecv >> locator >> hashStop;
2005 CBlockIndex* pindex = NULL;
2006 if (locator.IsNull())
2008 // If locator is null, return the hashStop block
2009 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2010 if (mi == mapBlockIndex.end())
2012 pindex = (*mi).second;
2016 // Find the last block the caller has in the main chain
2017 pindex = locator.GetBlockIndex();
2019 pindex = pindex->pnext;
2022 vector<CBlock> vHeaders;
2023 int nLimit = 2000 + locator.GetDistanceBack();
2024 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2025 for (; pindex; pindex = pindex->pnext)
2027 vHeaders.push_back(pindex->GetBlockHeader());
2028 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2031 pfrom->PushMessage("headers", vHeaders);
2035 else if (strCommand == "tx")
2037 vector<uint256> vWorkQueue;
2038 CDataStream vMsg(vRecv);
2042 CInv inv(MSG_TX, tx.GetHash());
2043 pfrom->AddInventoryKnown(inv);
2045 bool fMissingInputs = false;
2046 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2048 AddToWalletIfInvolvingMe(tx, NULL, true);
2049 RelayMessage(inv, vMsg);
2050 mapAlreadyAskedFor.erase(inv);
2051 vWorkQueue.push_back(inv.hash);
2053 // Recursively process any orphan transactions that depended on this one
2054 for (int i = 0; i < vWorkQueue.size(); i++)
2056 uint256 hashPrev = vWorkQueue[i];
2057 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2058 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2061 const CDataStream& vMsg = *((*mi).second);
2063 CDataStream(vMsg) >> tx;
2064 CInv inv(MSG_TX, tx.GetHash());
2066 if (tx.AcceptToMemoryPool(true))
2068 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2069 AddToWalletIfInvolvingMe(tx, NULL, true);
2070 RelayMessage(inv, vMsg);
2071 mapAlreadyAskedFor.erase(inv);
2072 vWorkQueue.push_back(inv.hash);
2077 BOOST_FOREACH(uint256 hash, vWorkQueue)
2078 EraseOrphanTx(hash);
2080 else if (fMissingInputs)
2082 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2088 else if (strCommand == "block")
2093 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2096 CInv inv(MSG_BLOCK, block.GetHash());
2097 pfrom->AddInventoryKnown(inv);
2099 if (ProcessBlock(pfrom, &block))
2100 mapAlreadyAskedFor.erase(inv);
2104 else if (strCommand == "getaddr")
2106 // Nodes rebroadcast an addr every 24 hours
2107 pfrom->vAddrToSend.clear();
2108 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2109 CRITICAL_BLOCK(cs_mapAddresses)
2111 unsigned int nCount = 0;
2112 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2114 const CAddress& addr = item.second;
2115 if (addr.nTime > nSince)
2118 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2120 const CAddress& addr = item.second;
2121 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2122 pfrom->PushAddress(addr);
2128 else if (strCommand == "checkorder")
2133 if (!GetBoolArg("-allowreceivebyip"))
2135 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2142 /// we have a chance to check the order here
2144 // Keep giving the same key to the same ip until they use it
2145 if (!mapReuseKey.count(pfrom->addr.ip))
2146 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2148 // Send back approval of order and pubkey to use
2149 CScript scriptPubKey;
2150 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2151 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2155 else if (strCommand == "submitorder")
2160 if (!GetBoolArg("-allowreceivebyip"))
2162 pfrom->PushMessage("reply", hashReply, (int)2);
2168 wtxNew.fFromMe = false;
2171 if (!wtxNew.AcceptWalletTransaction())
2173 pfrom->PushMessage("reply", hashReply, (int)1);
2174 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2176 wtxNew.fTimeReceivedIsTxTime = true;
2177 AddToWallet(wtxNew);
2178 wtxNew.RelayWalletTransaction();
2179 mapReuseKey.erase(pfrom->addr.ip);
2181 // Send back confirmation
2182 pfrom->PushMessage("reply", hashReply, (int)0);
2186 else if (strCommand == "reply")
2191 CRequestTracker tracker;
2192 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2194 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2195 if (mi != pfrom->mapRequests.end())
2197 tracker = (*mi).second;
2198 pfrom->mapRequests.erase(mi);
2201 if (!tracker.IsNull())
2202 tracker.fn(tracker.param1, vRecv);
2206 else if (strCommand == "ping")
2211 else if (strCommand == "alert")
2216 if (alert.ProcessAlert())
2219 pfrom->setKnown.insert(alert.GetHash());
2220 CRITICAL_BLOCK(cs_vNodes)
2221 BOOST_FOREACH(CNode* pnode, vNodes)
2222 alert.RelayTo(pnode);
2229 // Ignore unknown commands for extensibility
2233 // Update the last seen time for this node's address
2234 if (pfrom->fNetworkNode)
2235 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2236 AddressCurrentlyConnected(pfrom->addr);
2243 bool ProcessMessages(CNode* pfrom)
2245 CDataStream& vRecv = pfrom->vRecv;
2249 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2253 // (4) message start
2262 // Scan for message start
2263 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2264 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2265 if (vRecv.end() - pstart < nHeaderSize)
2267 if (vRecv.size() > nHeaderSize)
2269 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2270 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2274 if (pstart - vRecv.begin() > 0)
2275 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2276 vRecv.erase(vRecv.begin(), pstart);
2279 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2284 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2287 string strCommand = hdr.GetCommand();
2290 unsigned int nMessageSize = hdr.nMessageSize;
2291 if (nMessageSize > MAX_SIZE)
2293 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2296 if (nMessageSize > vRecv.size())
2298 // Rewind and wait for rest of message
2299 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2304 if (vRecv.GetVersion() >= 209)
2306 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2307 unsigned int nChecksum = 0;
2308 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2309 if (nChecksum != hdr.nChecksum)
2311 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2312 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2317 // Copy message to its own buffer
2318 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2319 vRecv.ignore(nMessageSize);
2325 CRITICAL_BLOCK(cs_main)
2326 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2330 catch (std::ios_base::failure& e)
2332 if (strstr(e.what(), "end of data"))
2334 // Allow exceptions from underlength message on vRecv
2335 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());
2337 else if (strstr(e.what(), "size too large"))
2339 // Allow exceptions from overlong size
2340 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2344 PrintExceptionContinue(&e, "ProcessMessage()");
2347 catch (std::exception& e) {
2348 PrintExceptionContinue(&e, "ProcessMessage()");
2350 PrintExceptionContinue(NULL, "ProcessMessage()");
2354 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2364 bool SendMessages(CNode* pto, bool fSendTrickle)
2366 CRITICAL_BLOCK(cs_main)
2368 // Don't send anything until we get their version message
2369 if (pto->nVersion == 0)
2373 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2374 pto->PushMessage("ping");
2376 // Resend wallet transactions that haven't gotten in a block yet
2377 ResendWalletTransactions();
2379 // Address refresh broadcast
2380 static int64 nLastRebroadcast;
2381 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2383 nLastRebroadcast = GetTime();
2384 CRITICAL_BLOCK(cs_vNodes)
2386 BOOST_FOREACH(CNode* pnode, vNodes)
2388 // Periodically clear setAddrKnown to allow refresh broadcasts
2389 pnode->setAddrKnown.clear();
2391 // Rebroadcast our address
2392 if (addrLocalHost.IsRoutable() && !fUseProxy)
2394 CAddress addr(addrLocalHost);
2395 addr.nTime = GetAdjustedTime();
2396 pnode->PushAddress(addr);
2402 // Clear out old addresses periodically so it's not too much work at once
2403 static int64 nLastClear;
2404 if (nLastClear == 0)
2405 nLastClear = GetTime();
2406 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2408 nLastClear = GetTime();
2409 CRITICAL_BLOCK(cs_mapAddresses)
2412 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2413 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2414 mi != mapAddresses.end();)
2416 const CAddress& addr = (*mi).second;
2417 if (addr.nTime < nSince)
2419 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2421 addrdb.EraseAddress(addr);
2422 mapAddresses.erase(mi++);
2436 vector<CAddress> vAddr;
2437 vAddr.reserve(pto->vAddrToSend.size());
2438 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2440 // returns true if wasn't already contained in the set
2441 if (pto->setAddrKnown.insert(addr).second)
2443 vAddr.push_back(addr);
2444 // receiver rejects addr messages larger than 1000
2445 if (vAddr.size() >= 1000)
2447 pto->PushMessage("addr", vAddr);
2452 pto->vAddrToSend.clear();
2454 pto->PushMessage("addr", vAddr);
2459 // Message: inventory
2462 vector<CInv> vInvWait;
2463 CRITICAL_BLOCK(pto->cs_inventory)
2465 vInv.reserve(pto->vInventoryToSend.size());
2466 vInvWait.reserve(pto->vInventoryToSend.size());
2467 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2469 if (pto->setInventoryKnown.count(inv))
2472 // trickle out tx inv to protect privacy
2473 if (inv.type == MSG_TX && !fSendTrickle)
2475 // 1/4 of tx invs blast to all immediately
2476 static uint256 hashSalt;
2478 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2479 uint256 hashRand = inv.hash ^ hashSalt;
2480 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2481 bool fTrickleWait = ((hashRand & 3) != 0);
2483 // always trickle our own transactions
2486 TRY_CRITICAL_BLOCK(cs_mapWallet)
2488 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2489 if (mi != mapWallet.end())
2491 CWalletTx& wtx = (*mi).second;
2493 fTrickleWait = true;
2500 vInvWait.push_back(inv);
2505 // returns true if wasn't already contained in the set
2506 if (pto->setInventoryKnown.insert(inv).second)
2508 vInv.push_back(inv);
2509 if (vInv.size() >= 1000)
2511 pto->PushMessage("inv", vInv);
2516 pto->vInventoryToSend = vInvWait;
2519 pto->PushMessage("inv", vInv);
2525 vector<CInv> vGetData;
2526 int64 nNow = GetTime() * 1000000;
2528 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2530 const CInv& inv = (*pto->mapAskFor.begin()).second;
2531 if (!AlreadyHave(txdb, inv))
2533 printf("sending getdata: %s\n", inv.ToString().c_str());
2534 vGetData.push_back(inv);
2535 if (vGetData.size() >= 1000)
2537 pto->PushMessage("getdata", vGetData);
2541 pto->mapAskFor.erase(pto->mapAskFor.begin());
2543 if (!vGetData.empty())
2544 pto->PushMessage("getdata", vGetData);
2563 //////////////////////////////////////////////////////////////////////////////
2568 int FormatHashBlocks(void* pbuffer, unsigned int len)
2570 unsigned char* pdata = (unsigned char*)pbuffer;
2571 unsigned int blocks = 1 + ((len + 8) / 64);
2572 unsigned char* pend = pdata + 64 * blocks;
2573 memset(pdata + len, 0, 64 * blocks - len);
2575 unsigned int bits = len * 8;
2576 pend[-1] = (bits >> 0) & 0xff;
2577 pend[-2] = (bits >> 8) & 0xff;
2578 pend[-3] = (bits >> 16) & 0xff;
2579 pend[-4] = (bits >> 24) & 0xff;
2583 using CryptoPP::ByteReverse;
2585 static const unsigned int pSHA256InitState[8] =
2586 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2588 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2590 memcpy(pstate, pinit, 32);
2591 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2595 // ScanHash scans nonces looking for a hash with at least some zero bits.
2596 // It operates on big endian data. Caller does the byte reversing.
2597 // All input buffers are 16-byte aligned. nNonce is usually preserved
2598 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2599 // the block is rebuilt and nNonce starts over at zero.
2601 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2603 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2607 // Hash pdata using pmidstate as the starting state into
2608 // preformatted buffer phash1, then hash phash1 into phash
2610 SHA256Transform(phash1, pdata, pmidstate);
2611 SHA256Transform(phash, phash1, pSHA256InitState);
2613 // Return the nonce if the hash has at least some zero bits,
2614 // caller will check if it has enough to reach the target
2615 if (((unsigned short*)phash)[14] == 0)
2618 // If nothing found after trying for a while, return -1
2619 if ((nNonce & 0xffff) == 0)
2621 nHashesDone = 0xffff+1;
2632 set<uint256> setDependsOn;
2635 COrphan(CTransaction* ptxIn)
2643 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2644 BOOST_FOREACH(uint256 hash, setDependsOn)
2645 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2650 CBlock* CreateNewBlock(CReserveKey& reservekey)
2652 CBlockIndex* pindexPrev = pindexBest;
2655 auto_ptr<CBlock> pblock(new CBlock());
2659 // Create coinbase tx
2661 txNew.vin.resize(1);
2662 txNew.vin[0].prevout.SetNull();
2663 txNew.vout.resize(1);
2664 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2666 // Add our coinbase tx as first transaction
2667 pblock->vtx.push_back(txNew);
2669 // Collect memory pool transactions into the block
2671 CRITICAL_BLOCK(cs_main)
2672 CRITICAL_BLOCK(cs_mapTransactions)
2676 // Priority order to process transactions
2677 list<COrphan> vOrphan; // list memory doesn't move
2678 map<uint256, vector<COrphan*> > mapDependers;
2679 multimap<double, CTransaction*> mapPriority;
2680 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2682 CTransaction& tx = (*mi).second;
2683 if (tx.IsCoinBase() || !tx.IsFinal())
2686 COrphan* porphan = NULL;
2687 double dPriority = 0;
2688 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2690 // Read prev transaction
2691 CTransaction txPrev;
2693 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2695 // Has to wait for dependencies
2698 // Use list for automatic deletion
2699 vOrphan.push_back(COrphan(&tx));
2700 porphan = &vOrphan.back();
2702 mapDependers[txin.prevout.hash].push_back(porphan);
2703 porphan->setDependsOn.insert(txin.prevout.hash);
2706 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2708 // Read block header
2709 int nConf = txindex.GetDepthInMainChain();
2711 dPriority += (double)nValueIn * nConf;
2713 if (fDebug && GetBoolArg("-printpriority"))
2714 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2717 // Priority is sum(valuein * age) / txsize
2718 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2721 porphan->dPriority = dPriority;
2723 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2725 if (fDebug && GetBoolArg("-printpriority"))
2727 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2734 // Collect transactions into block
2735 map<uint256, CTxIndex> mapTestPool;
2736 uint64 nBlockSize = 1000;
2737 int nBlockSigOps = 100;
2738 while (!mapPriority.empty())
2740 // Take highest priority transaction off priority queue
2741 double dPriority = -(*mapPriority.begin()).first;
2742 CTransaction& tx = *(*mapPriority.begin()).second;
2743 mapPriority.erase(mapPriority.begin());
2746 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2747 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2749 int nTxSigOps = tx.GetSigOpCount();
2750 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2753 // Transaction fee required depends on block size
2754 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2755 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
2757 // Connecting shouldn't fail due to dependency on other memory pool transactions
2758 // because we're already processing them in order of dependency
2759 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2760 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2762 swap(mapTestPool, mapTestPoolTmp);
2765 pblock->vtx.push_back(tx);
2766 nBlockSize += nTxSize;
2767 nBlockSigOps += nTxSigOps;
2769 // Add transactions that depend on this one to the priority queue
2770 uint256 hash = tx.GetHash();
2771 if (mapDependers.count(hash))
2773 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2775 if (!porphan->setDependsOn.empty())
2777 porphan->setDependsOn.erase(hash);
2778 if (porphan->setDependsOn.empty())
2779 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2785 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2788 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2789 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2790 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2791 pblock->nBits = GetNextWorkRequired(pindexPrev);
2794 return pblock.release();
2798 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
2800 // Update nExtraNonce
2801 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2802 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
2807 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
2808 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2812 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2815 // Prebuild hash buffers
2822 uint256 hashPrevBlock;
2823 uint256 hashMerkleRoot;
2826 unsigned int nNonce;
2829 unsigned char pchPadding0[64];
2831 unsigned char pchPadding1[64];
2834 memset(&tmp, 0, sizeof(tmp));
2836 tmp.block.nVersion = pblock->nVersion;
2837 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2838 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2839 tmp.block.nTime = pblock->nTime;
2840 tmp.block.nBits = pblock->nBits;
2841 tmp.block.nNonce = pblock->nNonce;
2843 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2844 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2846 // Byte swap all the input buffer
2847 for (int i = 0; i < sizeof(tmp)/4; i++)
2848 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2850 // Precalc the first half of the first hash, which stays constant
2851 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2853 memcpy(pdata, &tmp.block, 128);
2854 memcpy(phash1, &tmp.hash1, 64);
2858 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
2860 uint256 hash = pblock->GetHash();
2861 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2863 if (hash > hashTarget)
2867 printf("BitcoinMiner:\n");
2868 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2870 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2871 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2874 CRITICAL_BLOCK(cs_main)
2876 if (pblock->hashPrevBlock != hashBestChain)
2877 return error("BitcoinMiner : generated block is stale");
2879 // Remove key from key pool
2880 reservekey.KeepKey();
2882 // Track how many getdata requests this block gets
2883 CRITICAL_BLOCK(cs_mapRequestCount)
2884 mapRequestCount[pblock->GetHash()] = 0;
2886 // Process this block the same as if we had received it from another node
2887 if (!ProcessBlock(NULL, pblock))
2888 return error("BitcoinMiner : ProcessBlock, block not accepted");
2897 printf("BitcoinMiner started\n");
2898 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2900 // Each thread has its own key and counter
2901 CReserveKey reservekey;
2902 unsigned int nExtraNonce = 0;
2903 int64 nPrevTime = 0;
2905 while (fGenerateBitcoins)
2907 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2911 while (vNodes.empty() || IsInitialBlockDownload())
2916 if (!fGenerateBitcoins)
2924 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2925 CBlockIndex* pindexPrev = pindexBest;
2927 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2930 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
2932 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2936 // Prebuild hash buffers
2938 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
2939 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
2940 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
2942 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
2944 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
2945 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
2951 int64 nStart = GetTime();
2952 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2954 uint256& hash = *alignup<16>(hashbuf);
2957 unsigned int nHashesDone = 0;
2958 unsigned int nNonceFound;
2961 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
2962 (char*)&hash, nHashesDone);
2964 // Check if something found
2965 if (nNonceFound != -1)
2967 for (int i = 0; i < sizeof(hash)/4; i++)
2968 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
2970 if (hash <= hashTarget)
2973 pblock->nNonce = ByteReverse(nNonceFound);
2974 assert(hash == pblock->GetHash());
2976 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2977 CheckWork(pblock.get(), reservekey);
2978 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2984 static int64 nHashCounter;
2985 if (nHPSTimerStart == 0)
2987 nHPSTimerStart = GetTimeMillis();
2991 nHashCounter += nHashesDone;
2992 if (GetTimeMillis() - nHPSTimerStart > 4000)
2994 static CCriticalSection cs;
2997 if (GetTimeMillis() - nHPSTimerStart > 4000)
2999 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3000 nHPSTimerStart = GetTimeMillis();
3002 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3003 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3004 static int64 nLogTime;
3005 if (GetTime() - nLogTime > 30 * 60)
3007 nLogTime = GetTime();
3008 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3009 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3015 // Check for stop or if block needs to be rebuilt
3018 if (!fGenerateBitcoins)
3020 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3024 if (nBlockNonce >= 0xffff0000)
3026 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3028 if (pindexPrev != pindexBest)
3031 // Update nTime every few seconds
3032 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3033 nBlockTime = ByteReverse(pblock->nTime);
3038 void ThreadBitcoinMiner(void* parg)
3042 vnThreadsRunning[3]++;
3044 vnThreadsRunning[3]--;
3046 catch (std::exception& e) {
3047 vnThreadsRunning[3]--;
3048 PrintException(&e, "ThreadBitcoinMiner()");
3050 vnThreadsRunning[3]--;
3051 PrintException(NULL, "ThreadBitcoinMiner()");
3053 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3055 if (vnThreadsRunning[3] == 0)
3057 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3061 void GenerateBitcoins(bool fGenerate)
3063 if (fGenerateBitcoins != fGenerate)
3065 fGenerateBitcoins = fGenerate;
3066 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3069 if (fGenerateBitcoins)
3071 int nProcessors = boost::thread::hardware_concurrency();
3072 printf("%d processors\n", nProcessors);
3073 if (nProcessors < 1)
3075 if (fLimitProcessors && nProcessors > nLimitProcessors)
3076 nProcessors = nLimitProcessors;
3077 int nAddThreads = nProcessors - vnThreadsRunning[3];
3078 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3079 for (int i = 0; i < nAddThreads; i++)
3081 if (!CreateThread(ThreadBitcoinMiner, NULL))
3082 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");