1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "checkpoints.h"
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
14 using namespace boost;
20 CCriticalSection cs_setpwalletRegistered;
21 set<CWallet*> setpwalletRegistered;
23 CCriticalSection cs_main;
25 static map<uint256, CTransaction> mapTransactions;
26 CCriticalSection cs_mapTransactions;
27 unsigned int nTransactionsUpdated = 0;
28 map<COutPoint, CInPoint> mapNextTx;
30 map<uint256, CBlockIndex*> mapBlockIndex;
31 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
32 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
33 CBlockIndex* pindexGenesisBlock = NULL;
35 CBigNum bnBestChainWork = 0;
36 CBigNum bnBestInvalidWork = 0;
37 uint256 hashBestChain = 0;
38 CBlockIndex* pindexBest = NULL;
39 int64 nTimeBestReceived = 0;
41 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
43 map<uint256, CBlock*> mapOrphanBlocks;
44 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
46 map<uint256, CDataStream*> mapOrphanTransactions;
47 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
54 int fGenerateBitcoins = false;
55 int64 nTransactionFee = 0;
56 int fLimitProcessors = false;
57 int nLimitProcessors = 1;
58 int fMinimizeToTray = true;
59 int fMinimizeOnClose = true;
67 //////////////////////////////////////////////////////////////////////////////
69 // dispatching functions
72 // These functions dispatch to one or all registered wallets
75 void RegisterWallet(CWallet* pwalletIn)
77 CRITICAL_BLOCK(cs_setpwalletRegistered)
79 setpwalletRegistered.insert(pwalletIn);
83 void UnregisterWallet(CWallet* pwalletIn)
85 CRITICAL_BLOCK(cs_setpwalletRegistered)
87 setpwalletRegistered.erase(pwalletIn);
91 // check whether the passed transaction is from us
92 bool static IsFromMe(CTransaction& tx)
94 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
95 if (pwallet->IsFromMe(tx))
100 // get the wallet transaction with the given hash (if it exists)
101 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
103 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
104 if (pwallet->GetTransaction(hashTx,wtx))
109 // erases transaction with the given hash from all wallets
110 void static EraseFromWallets(uint256 hash)
112 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
113 pwallet->EraseFromWallet(hash);
116 // make sure all wallets know about the given transaction, in the given block
117 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
119 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
120 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
123 // notify wallets about a new best chain
124 void static SetBestChain(const CBlockLocator& loc)
126 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
127 pwallet->SetBestChain(loc);
130 // notify wallets about an updated transaction
131 void static UpdatedTransaction(const uint256& hashTx)
133 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
134 pwallet->UpdatedTransaction(hashTx);
138 void static PrintWallets(const CBlock& block)
140 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
141 pwallet->PrintWallet(block);
144 // notify wallets about an incoming inventory (for request counts)
145 void static Inventory(const uint256& hash)
147 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
148 pwallet->Inventory(hash);
151 // ask wallets to resend their transactions
152 void static ResendWalletTransactions()
154 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155 pwallet->ResendWalletTransactions();
164 //////////////////////////////////////////////////////////////////////////////
166 // mapOrphanTransactions
169 void static AddOrphanTx(const CDataStream& vMsg)
172 CDataStream(vMsg) >> tx;
173 uint256 hash = tx.GetHash();
174 if (mapOrphanTransactions.count(hash))
176 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
177 BOOST_FOREACH(const CTxIn& txin, tx.vin)
178 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
181 void static EraseOrphanTx(uint256 hash)
183 if (!mapOrphanTransactions.count(hash))
185 const CDataStream* pvMsg = mapOrphanTransactions[hash];
187 CDataStream(*pvMsg) >> tx;
188 BOOST_FOREACH(const CTxIn& txin, tx.vin)
190 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
191 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
193 if ((*mi).second == pvMsg)
194 mapOrphanTransactionsByPrev.erase(mi++);
200 mapOrphanTransactions.erase(hash);
210 //////////////////////////////////////////////////////////////////////////////
212 // CTransaction and CTxIndex
215 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
218 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
220 if (!ReadFromDisk(txindexRet.pos))
222 if (prevout.n >= vout.size())
230 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
233 return ReadFromDisk(txdb, prevout, txindex);
236 bool CTransaction::ReadFromDisk(COutPoint prevout)
240 return ReadFromDisk(txdb, prevout, txindex);
245 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
257 // Load the block this tx is in
259 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
261 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
266 // Update the tx's hashBlock
267 hashBlock = pblock->GetHash();
269 // Locate the transaction
270 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
271 if (pblock->vtx[nIndex] == *(CTransaction*)this)
273 if (nIndex == pblock->vtx.size())
275 vMerkleBranch.clear();
277 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
281 // Fill in merkle branch
282 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
285 // Is the tx in a block that's in the main chain
286 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
287 if (mi == mapBlockIndex.end())
289 CBlockIndex* pindex = (*mi).second;
290 if (!pindex || !pindex->IsInMainChain())
293 return pindexBest->nHeight - pindex->nHeight + 1;
302 bool CTransaction::CheckTransaction() const
304 // Basic checks that don't depend on any context
306 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
308 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
310 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
311 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
313 // Check for negative or overflow output values
315 BOOST_FOREACH(const CTxOut& txout, vout)
317 if (txout.nValue < 0)
318 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
319 if (txout.nValue > MAX_MONEY)
320 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
321 nValueOut += txout.nValue;
322 if (!MoneyRange(nValueOut))
323 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
326 // Check for duplicate inputs
327 set<COutPoint> vInOutPoints;
328 BOOST_FOREACH(const CTxIn& txin, vin)
330 if (vInOutPoints.count(txin.prevout))
332 vInOutPoints.insert(txin.prevout);
337 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
338 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
342 BOOST_FOREACH(const CTxIn& txin, vin)
343 if (txin.prevout.IsNull())
344 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
350 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
353 *pfMissingInputs = false;
355 if (!CheckTransaction())
356 return error("AcceptToMemoryPool() : CheckTransaction failed");
358 // Coinbase is only valid in a block, not as a loose transaction
360 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
362 // To help v0.1.5 clients who would see it as a negative number
363 if ((int64)nLockTime > INT_MAX)
364 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
367 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
368 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
369 // attacks disallow transactions with more than one SigOp per 34 bytes.
370 // 34 bytes because a TxOut is:
371 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
372 if (GetSigOpCount() > nSize / 34 || nSize < 100)
373 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
375 // Rather not work on nonstandard transactions (unless -testnet)
376 if (!fTestNet && !IsStandard())
377 return error("AcceptToMemoryPool() : nonstandard transaction type");
379 // Do we already have it?
380 uint256 hash = GetHash();
381 CRITICAL_BLOCK(cs_mapTransactions)
382 if (mapTransactions.count(hash))
385 if (txdb.ContainsTx(hash))
388 // Check for conflicts with in-memory transactions
389 CTransaction* ptxOld = NULL;
390 for (int i = 0; i < vin.size(); i++)
392 COutPoint outpoint = vin[i].prevout;
393 if (mapNextTx.count(outpoint))
395 // Disable replacement feature for now
398 // Allow replacing with a newer version of the same transaction
401 ptxOld = mapNextTx[outpoint].ptx;
402 if (ptxOld->IsFinal())
404 if (!IsNewerThan(*ptxOld))
406 for (int i = 0; i < vin.size(); i++)
408 COutPoint outpoint = vin[i].prevout;
409 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
418 // Check against previous transactions
419 map<uint256, CTxIndex> mapUnused;
421 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
424 *pfMissingInputs = true;
425 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
428 // Don't accept it if it can't get into a block
429 if (nFees < GetMinFee(1000, true, true))
430 return error("AcceptToMemoryPool() : not enough fees");
432 // Continuously rate-limit free transactions
433 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
434 // be annoying or make other's transactions take longer to confirm.
435 if (nFees < MIN_RELAY_TX_FEE)
437 static CCriticalSection cs;
438 static double dFreeCount;
439 static int64 nLastTime;
440 int64 nNow = GetTime();
444 // Use an exponentially decaying ~10-minute window:
445 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
447 // -limitfreerelay unit is thousand-bytes-per-minute
448 // At default rate it would take over a month to fill 1GB
449 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
450 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
452 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
458 // Store transaction in memory
459 CRITICAL_BLOCK(cs_mapTransactions)
463 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
464 ptxOld->RemoveFromMemoryPool();
466 AddToMemoryPoolUnchecked();
469 ///// are we sure this is ok when loading transactions or restoring block txes
470 // If updated, erase old tx from wallet
472 EraseFromWallets(ptxOld->GetHash());
474 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
478 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
481 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
484 bool CTransaction::AddToMemoryPoolUnchecked()
486 // Add to memory pool without checking anything. Don't call this directly,
487 // call AcceptToMemoryPool to properly check the transaction first.
488 CRITICAL_BLOCK(cs_mapTransactions)
490 uint256 hash = GetHash();
491 mapTransactions[hash] = *this;
492 for (int i = 0; i < vin.size(); i++)
493 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
494 nTransactionsUpdated++;
500 bool CTransaction::RemoveFromMemoryPool()
502 // Remove transaction from memory pool
503 CRITICAL_BLOCK(cs_mapTransactions)
505 BOOST_FOREACH(const CTxIn& txin, vin)
506 mapNextTx.erase(txin.prevout);
507 mapTransactions.erase(GetHash());
508 nTransactionsUpdated++;
518 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
520 if (hashBlock == 0 || nIndex == -1)
523 // Find the block it claims to be in
524 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
525 if (mi == mapBlockIndex.end())
527 CBlockIndex* pindex = (*mi).second;
528 if (!pindex || !pindex->IsInMainChain())
531 // Make sure the merkle branch connects to this block
532 if (!fMerkleVerified)
534 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
536 fMerkleVerified = true;
539 nHeightRet = pindex->nHeight;
540 return pindexBest->nHeight - pindex->nHeight + 1;
544 int CMerkleTx::GetBlocksToMaturity() const
548 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
552 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
556 if (!IsInMainChain() && !ClientConnectInputs())
558 return CTransaction::AcceptToMemoryPool(txdb, false);
562 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
566 bool CMerkleTx::AcceptToMemoryPool()
569 return AcceptToMemoryPool(txdb);
574 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
576 CRITICAL_BLOCK(cs_mapTransactions)
578 // Add previous supporting transactions first
579 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
581 if (!tx.IsCoinBase())
583 uint256 hash = tx.GetHash();
584 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
585 tx.AcceptToMemoryPool(txdb, fCheckInputs);
588 return AcceptToMemoryPool(txdb, fCheckInputs);
593 bool CWalletTx::AcceptWalletTransaction()
596 return AcceptWalletTransaction(txdb);
599 int CTxIndex::GetDepthInMainChain() const
603 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
605 // Find the block in the index
606 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
607 if (mi == mapBlockIndex.end())
609 CBlockIndex* pindex = (*mi).second;
610 if (!pindex || !pindex->IsInMainChain())
612 return 1 + nBestHeight - pindex->nHeight;
624 //////////////////////////////////////////////////////////////////////////////
626 // CBlock and CBlockIndex
629 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
631 if (!fReadTransactions)
633 *this = pindex->GetBlockHeader();
636 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
638 if (GetHash() != pindex->GetBlockHash())
639 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
643 uint256 static GetOrphanRoot(const CBlock* pblock)
645 // Work back to the first block in the orphan chain
646 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
647 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
648 return pblock->GetHash();
651 int64 static GetBlockValue(int nHeight, int64 nFees)
653 int64 nSubsidy = 50 * COIN;
655 // Subsidy is cut in half every 4 years
656 nSubsidy >>= (nHeight / 210000);
658 return nSubsidy + nFees;
661 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
662 static const int64 nTargetSpacing = 10 * 60;
663 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
666 // minimum amount of work that could possibly be required nTime after
667 // minimum work required was nBase
669 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
672 bnResult.SetCompact(nBase);
673 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
675 // Maximum 400% adjustment...
677 // ... in best-case exactly 4-times-normal target time
678 nTime -= nTargetTimespan*4;
680 if (bnResult > bnProofOfWorkLimit)
681 bnResult = bnProofOfWorkLimit;
682 return bnResult.GetCompact();
685 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
689 if (pindexLast == NULL)
690 return bnProofOfWorkLimit.GetCompact();
692 // Only change once per interval
693 if ((pindexLast->nHeight+1) % nInterval != 0)
694 return pindexLast->nBits;
696 // Go back by what we want to be 14 days worth of blocks
697 const CBlockIndex* pindexFirst = pindexLast;
698 for (int i = 0; pindexFirst && i < nInterval-1; i++)
699 pindexFirst = pindexFirst->pprev;
702 // Limit adjustment step
703 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
704 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
705 if (nActualTimespan < nTargetTimespan/4)
706 nActualTimespan = nTargetTimespan/4;
707 if (nActualTimespan > nTargetTimespan*4)
708 nActualTimespan = nTargetTimespan*4;
712 bnNew.SetCompact(pindexLast->nBits);
713 bnNew *= nActualTimespan;
714 bnNew /= nTargetTimespan;
716 if (bnNew > bnProofOfWorkLimit)
717 bnNew = bnProofOfWorkLimit;
720 printf("GetNextWorkRequired RETARGET\n");
721 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
722 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
723 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
725 return bnNew.GetCompact();
728 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
731 bnTarget.SetCompact(nBits);
734 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
735 return error("CheckProofOfWork() : nBits below minimum work");
737 // Check proof of work matches claimed amount
738 if (hash > bnTarget.getuint256())
739 return error("CheckProofOfWork() : hash doesn't match nBits");
744 // Return maximum amount of blocks that other nodes claim to have
745 int GetNumBlocksOfPeers()
747 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
750 bool IsInitialBlockDownload()
752 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
754 static int64 nLastUpdate;
755 static CBlockIndex* pindexLastBest;
756 if (pindexBest != pindexLastBest)
758 pindexLastBest = pindexBest;
759 nLastUpdate = GetTime();
761 return (GetTime() - nLastUpdate < 10 &&
762 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
765 void static InvalidChainFound(CBlockIndex* pindexNew)
767 if (pindexNew->bnChainWork > bnBestInvalidWork)
769 bnBestInvalidWork = pindexNew->bnChainWork;
770 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
773 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());
774 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
775 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
776 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
789 bool CTransaction::DisconnectInputs(CTxDB& txdb)
791 // Relinquish previous transactions' spent pointers
794 BOOST_FOREACH(const CTxIn& txin, vin)
796 COutPoint prevout = txin.prevout;
798 // Get prev txindex from disk
800 if (!txdb.ReadTxIndex(prevout.hash, txindex))
801 return error("DisconnectInputs() : ReadTxIndex failed");
803 if (prevout.n >= txindex.vSpent.size())
804 return error("DisconnectInputs() : prevout.n out of range");
806 // Mark outpoint as not spent
807 txindex.vSpent[prevout.n].SetNull();
810 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
811 return error("DisconnectInputs() : UpdateTxIndex failed");
815 // Remove transaction from index
816 if (!txdb.EraseTxIndex(*this))
817 return error("DisconnectInputs() : EraseTxPos failed");
823 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
824 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
826 // Take over previous transactions' spent pointers
827 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
828 // fMiner is true when called from the internal bitcoin miner
829 // ... both are false when called from CTransaction::AcceptToMemoryPool
833 for (int i = 0; i < vin.size(); i++)
835 COutPoint prevout = vin[i].prevout;
840 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
842 // Get txindex from current proposed changes
843 txindex = mapTestPool[prevout.hash];
847 // Read txindex from txdb
848 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
850 if (!fFound && (fBlock || fMiner))
851 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());
855 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
857 // Get prev tx from single transactions in memory
858 CRITICAL_BLOCK(cs_mapTransactions)
860 if (!mapTransactions.count(prevout.hash))
861 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
862 txPrev = mapTransactions[prevout.hash];
865 txindex.vSpent.resize(txPrev.vout.size());
869 // Get prev tx from disk
870 if (!txPrev.ReadFromDisk(txindex.pos))
871 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
874 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
875 return DoS(100, 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()));
877 // If prev is coinbase, check that it's matured
878 if (txPrev.IsCoinBase())
879 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
880 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
881 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
883 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
884 // before the last blockchain checkpoint. This is safe because block merkle hashes are
885 // still computed and checked, and any change will be caught at the next checkpoint.
886 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
888 if (!VerifySignature(txPrev, *this, i))
889 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
891 // Check for conflicts (double-spend)
892 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
893 // for an attacker to attempt to split the network.
894 if (!txindex.vSpent[prevout.n].IsNull())
895 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());
897 // Check for negative or overflow input values
898 nValueIn += txPrev.vout[prevout.n].nValue;
899 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
900 return DoS(100, error("ConnectInputs() : txin values out of range"));
902 // Mark outpoints as spent
903 txindex.vSpent[prevout.n] = posThisTx;
906 if (fBlock || fMiner)
908 mapTestPool[prevout.hash] = txindex;
912 if (nValueIn < GetValueOut())
913 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
915 // Tally transaction fees
916 int64 nTxFee = nValueIn - GetValueOut();
918 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
919 if (nTxFee < nMinFee)
922 if (!MoneyRange(nFees))
923 return DoS(100, error("ConnectInputs() : nFees out of range"));
928 // Add transaction to changes
929 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
933 // Add transaction to test pool
934 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
941 bool CTransaction::ClientConnectInputs()
946 // Take over previous transactions' spent pointers
947 CRITICAL_BLOCK(cs_mapTransactions)
950 for (int i = 0; i < vin.size(); i++)
952 // Get prev tx from single transactions in memory
953 COutPoint prevout = vin[i].prevout;
954 if (!mapTransactions.count(prevout.hash))
956 CTransaction& txPrev = mapTransactions[prevout.hash];
958 if (prevout.n >= txPrev.vout.size())
962 if (!VerifySignature(txPrev, *this, i))
963 return error("ConnectInputs() : VerifySignature failed");
965 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
966 ///// this has to go away now that posNext is gone
967 // // Check for conflicts
968 // if (!txPrev.vout[prevout.n].posNext.IsNull())
969 // return error("ConnectInputs() : prev tx already used");
971 // // Flag outpoints as used
972 // txPrev.vout[prevout.n].posNext = posThisTx;
974 nValueIn += txPrev.vout[prevout.n].nValue;
976 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
977 return error("ClientConnectInputs() : txin values out of range");
979 if (GetValueOut() > nValueIn)
989 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
991 // Disconnect in reverse order
992 for (int i = vtx.size()-1; i >= 0; i--)
993 if (!vtx[i].DisconnectInputs(txdb))
996 // Update block index on disk without changing it in memory.
997 // The memory index structure will be changed after the db commits.
1000 CDiskBlockIndex blockindexPrev(pindex->pprev);
1001 blockindexPrev.hashNext = 0;
1002 if (!txdb.WriteBlockIndex(blockindexPrev))
1003 return error("DisconnectBlock() : WriteBlockIndex failed");
1009 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1011 // Check it again in case a previous version let a bad block in
1015 //// issue here: it doesn't know the version
1016 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1018 map<uint256, CTxIndex> mapQueuedChanges;
1020 BOOST_FOREACH(CTransaction& tx, vtx)
1022 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1023 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1025 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false))
1028 // Write queued txindex changes
1029 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1031 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1032 return error("ConnectBlock() : UpdateTxIndex failed");
1035 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1038 // Update block index on disk without changing it in memory.
1039 // The memory index structure will be changed after the db commits.
1042 CDiskBlockIndex blockindexPrev(pindex->pprev);
1043 blockindexPrev.hashNext = pindex->GetBlockHash();
1044 if (!txdb.WriteBlockIndex(blockindexPrev))
1045 return error("ConnectBlock() : WriteBlockIndex failed");
1048 // Watch for transactions paying to me
1049 BOOST_FOREACH(CTransaction& tx, vtx)
1050 SyncWithWallets(tx, this, true);
1055 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1057 printf("REORGANIZE\n");
1060 CBlockIndex* pfork = pindexBest;
1061 CBlockIndex* plonger = pindexNew;
1062 while (pfork != plonger)
1064 while (plonger->nHeight > pfork->nHeight)
1065 if (!(plonger = plonger->pprev))
1066 return error("Reorganize() : plonger->pprev is null");
1067 if (pfork == plonger)
1069 if (!(pfork = pfork->pprev))
1070 return error("Reorganize() : pfork->pprev is null");
1073 // List of what to disconnect
1074 vector<CBlockIndex*> vDisconnect;
1075 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1076 vDisconnect.push_back(pindex);
1078 // List of what to connect
1079 vector<CBlockIndex*> vConnect;
1080 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1081 vConnect.push_back(pindex);
1082 reverse(vConnect.begin(), vConnect.end());
1084 // Disconnect shorter branch
1085 vector<CTransaction> vResurrect;
1086 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1089 if (!block.ReadFromDisk(pindex))
1090 return error("Reorganize() : ReadFromDisk for disconnect failed");
1091 if (!block.DisconnectBlock(txdb, pindex))
1092 return error("Reorganize() : DisconnectBlock failed");
1094 // Queue memory transactions to resurrect
1095 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1096 if (!tx.IsCoinBase())
1097 vResurrect.push_back(tx);
1100 // Connect longer branch
1101 vector<CTransaction> vDelete;
1102 for (int i = 0; i < vConnect.size(); i++)
1104 CBlockIndex* pindex = vConnect[i];
1106 if (!block.ReadFromDisk(pindex))
1107 return error("Reorganize() : ReadFromDisk for connect failed");
1108 if (!block.ConnectBlock(txdb, pindex))
1112 return error("Reorganize() : ConnectBlock failed");
1115 // Queue memory transactions to delete
1116 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1117 vDelete.push_back(tx);
1119 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1120 return error("Reorganize() : WriteHashBestChain failed");
1122 // Make sure it's successfully written to disk before changing memory structure
1123 if (!txdb.TxnCommit())
1124 return error("Reorganize() : TxnCommit failed");
1126 // Disconnect shorter branch
1127 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1129 pindex->pprev->pnext = NULL;
1131 // Connect longer branch
1132 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1134 pindex->pprev->pnext = pindex;
1136 // Resurrect memory transactions that were in the disconnected branch
1137 BOOST_FOREACH(CTransaction& tx, vResurrect)
1138 tx.AcceptToMemoryPool(txdb, false);
1140 // Delete redundant memory transactions that are in the connected branch
1141 BOOST_FOREACH(CTransaction& tx, vDelete)
1142 tx.RemoveFromMemoryPool();
1148 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1150 uint256 hash = GetHash();
1153 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1155 txdb.WriteHashBestChain(hash);
1156 if (!txdb.TxnCommit())
1157 return error("SetBestChain() : TxnCommit failed");
1158 pindexGenesisBlock = pindexNew;
1160 else if (hashPrevBlock == hashBestChain)
1162 // Adding to current best branch
1163 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1166 InvalidChainFound(pindexNew);
1167 return error("SetBestChain() : ConnectBlock failed");
1169 if (!txdb.TxnCommit())
1170 return error("SetBestChain() : TxnCommit failed");
1172 // Add to current best branch
1173 pindexNew->pprev->pnext = pindexNew;
1175 // Delete redundant memory transactions
1176 BOOST_FOREACH(CTransaction& tx, vtx)
1177 tx.RemoveFromMemoryPool();
1182 if (!Reorganize(txdb, pindexNew))
1185 InvalidChainFound(pindexNew);
1186 return error("SetBestChain() : Reorganize failed");
1190 // Update best block in wallet (so we can detect restored wallets)
1191 if (!IsInitialBlockDownload())
1193 const CBlockLocator locator(pindexNew);
1194 ::SetBestChain(locator);
1198 hashBestChain = hash;
1199 pindexBest = pindexNew;
1200 nBestHeight = pindexBest->nHeight;
1201 bnBestChainWork = pindexNew->bnChainWork;
1202 nTimeBestReceived = GetTime();
1203 nTransactionsUpdated++;
1204 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1210 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1212 // Check for duplicate
1213 uint256 hash = GetHash();
1214 if (mapBlockIndex.count(hash))
1215 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1217 // Construct new block index object
1218 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1220 return error("AddToBlockIndex() : new CBlockIndex failed");
1221 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1222 pindexNew->phashBlock = &((*mi).first);
1223 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1224 if (miPrev != mapBlockIndex.end())
1226 pindexNew->pprev = (*miPrev).second;
1227 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1229 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1233 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1234 if (!txdb.TxnCommit())
1238 if (pindexNew->bnChainWork > bnBestChainWork)
1239 if (!SetBestChain(txdb, pindexNew))
1244 if (pindexNew == pindexBest)
1246 // Notify UI to display prev block's coinbase if it was ours
1247 static uint256 hashPrevBestCoinBase;
1248 UpdatedTransaction(hashPrevBestCoinBase);
1249 hashPrevBestCoinBase = vtx[0].GetHash();
1259 bool CBlock::CheckBlock() const
1261 // These are checks that are independent of context
1262 // that can be verified before saving an orphan block.
1265 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1266 return DoS(100, error("CheckBlock() : size limits failed"));
1268 // Check proof of work matches claimed amount
1269 if (!CheckProofOfWork(GetHash(), nBits))
1270 return DoS(50, error("CheckBlock() : proof of work failed"));
1273 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1274 return error("CheckBlock() : block timestamp too far in the future");
1276 // First transaction must be coinbase, the rest must not be
1277 if (vtx.empty() || !vtx[0].IsCoinBase())
1278 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1279 for (int i = 1; i < vtx.size(); i++)
1280 if (vtx[i].IsCoinBase())
1281 return DoS(100, error("CheckBlock() : more than one coinbase"));
1283 // Check transactions
1284 BOOST_FOREACH(const CTransaction& tx, vtx)
1285 if (!tx.CheckTransaction())
1286 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1288 // Check that it's not full of nonstandard transactions
1289 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1290 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1293 if (hashMerkleRoot != BuildMerkleTree())
1294 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1299 bool CBlock::AcceptBlock()
1301 // Check for duplicate
1302 uint256 hash = GetHash();
1303 if (mapBlockIndex.count(hash))
1304 return error("AcceptBlock() : block already in mapBlockIndex");
1306 // Get prev block index
1307 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1308 if (mi == mapBlockIndex.end())
1309 return DoS(10, error("AcceptBlock() : prev block not found"));
1310 CBlockIndex* pindexPrev = (*mi).second;
1311 int nHeight = pindexPrev->nHeight+1;
1313 // Check proof of work
1314 if (nBits != GetNextWorkRequired(pindexPrev))
1315 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1317 // Check timestamp against prev
1318 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1319 return error("AcceptBlock() : block's timestamp is too early");
1321 // Check that all transactions are finalized
1322 BOOST_FOREACH(const CTransaction& tx, vtx)
1323 if (!tx.IsFinal(nHeight, GetBlockTime()))
1324 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1326 // Check that the block chain matches the known block chain up to a checkpoint
1327 if (!Checkpoints::CheckBlock(nHeight, hash))
1328 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1330 // Write block to history file
1331 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1332 return error("AcceptBlock() : out of disk space");
1333 unsigned int nFile = -1;
1334 unsigned int nBlockPos = 0;
1335 if (!WriteToDisk(nFile, nBlockPos))
1336 return error("AcceptBlock() : WriteToDisk failed");
1337 if (!AddToBlockIndex(nFile, nBlockPos))
1338 return error("AcceptBlock() : AddToBlockIndex failed");
1340 // Relay inventory, but don't relay old inventory during initial block download
1341 if (hashBestChain == hash)
1342 CRITICAL_BLOCK(cs_vNodes)
1343 BOOST_FOREACH(CNode* pnode, vNodes)
1344 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1345 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1350 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1352 // Check for duplicate
1353 uint256 hash = pblock->GetHash();
1354 if (mapBlockIndex.count(hash))
1355 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1356 if (mapOrphanBlocks.count(hash))
1357 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1359 // Preliminary checks
1360 if (!pblock->CheckBlock())
1361 return error("ProcessBlock() : CheckBlock FAILED");
1363 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1364 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1366 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1367 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1370 pfrom->Misbehaving(100);
1371 return error("ProcessBlock() : block with timestamp before last checkpoint");
1374 bnNewBlock.SetCompact(pblock->nBits);
1376 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1377 if (bnNewBlock > bnRequired)
1379 pfrom->Misbehaving(100);
1380 return error("ProcessBlock() : block with too little proof-of-work");
1385 // If don't already have its previous block, shunt it off to holding area until we get it
1386 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1388 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1389 CBlock* pblock2 = new CBlock(*pblock);
1390 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1391 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1393 // Ask this guy to fill in what we're missing
1395 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1400 if (!pblock->AcceptBlock())
1401 return error("ProcessBlock() : AcceptBlock FAILED");
1403 // Recursively process any orphan blocks that depended on this one
1404 vector<uint256> vWorkQueue;
1405 vWorkQueue.push_back(hash);
1406 for (int i = 0; i < vWorkQueue.size(); i++)
1408 uint256 hashPrev = vWorkQueue[i];
1409 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1410 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1413 CBlock* pblockOrphan = (*mi).second;
1414 if (pblockOrphan->AcceptBlock())
1415 vWorkQueue.push_back(pblockOrphan->GetHash());
1416 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1417 delete pblockOrphan;
1419 mapOrphanBlocksByPrev.erase(hashPrev);
1422 printf("ProcessBlock: ACCEPTED\n");
1433 bool CheckDiskSpace(uint64 nAdditionalBytes)
1435 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1437 // Check for 15MB because database could create another 10MB log file at any time
1438 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1441 string strMessage = _("Warning: Disk space is low ");
1442 strMiscWarning = strMessage;
1443 printf("*** %s\n", strMessage.c_str());
1444 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1445 CreateThread(Shutdown, NULL);
1451 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1455 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1458 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1460 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1469 static unsigned int nCurrentBlockFile = 1;
1471 FILE* AppendBlockFile(unsigned int& nFileRet)
1476 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1479 if (fseek(file, 0, SEEK_END) != 0)
1481 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1482 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1484 nFileRet = nCurrentBlockFile;
1488 nCurrentBlockFile++;
1492 bool LoadBlockIndex(bool fAllowNew)
1496 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1497 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1498 pchMessageStart[0] = 0xfa;
1499 pchMessageStart[1] = 0xbf;
1500 pchMessageStart[2] = 0xb5;
1501 pchMessageStart[3] = 0xda;
1508 if (!txdb.LoadBlockIndex())
1513 // Init with genesis block
1515 if (mapBlockIndex.empty())
1521 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1522 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1523 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1524 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1525 // vMerkleTree: 4a5e1e
1528 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1530 txNew.vin.resize(1);
1531 txNew.vout.resize(1);
1532 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1533 txNew.vout[0].nValue = 50 * COIN;
1534 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1536 block.vtx.push_back(txNew);
1537 block.hashPrevBlock = 0;
1538 block.hashMerkleRoot = block.BuildMerkleTree();
1540 block.nTime = 1231006505;
1541 block.nBits = 0x1d00ffff;
1542 block.nNonce = 2083236893;
1546 block.nTime = 1296688602;
1547 block.nBits = 0x1d07fff8;
1548 block.nNonce = 384568319;
1552 printf("%s\n", block.GetHash().ToString().c_str());
1553 printf("%s\n", hashGenesisBlock.ToString().c_str());
1554 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1555 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1557 assert(block.GetHash() == hashGenesisBlock);
1559 // Start new block file
1561 unsigned int nBlockPos;
1562 if (!block.WriteToDisk(nFile, nBlockPos))
1563 return error("LoadBlockIndex() : writing genesis block to disk failed");
1564 if (!block.AddToBlockIndex(nFile, nBlockPos))
1565 return error("LoadBlockIndex() : genesis block not accepted");
1573 void PrintBlockTree()
1575 // precompute tree structure
1576 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1577 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1579 CBlockIndex* pindex = (*mi).second;
1580 mapNext[pindex->pprev].push_back(pindex);
1582 //while (rand() % 3 == 0)
1583 // mapNext[pindex->pprev].push_back(pindex);
1586 vector<pair<int, CBlockIndex*> > vStack;
1587 vStack.push_back(make_pair(0, pindexGenesisBlock));
1590 while (!vStack.empty())
1592 int nCol = vStack.back().first;
1593 CBlockIndex* pindex = vStack.back().second;
1596 // print split or gap
1597 if (nCol > nPrevCol)
1599 for (int i = 0; i < nCol-1; i++)
1603 else if (nCol < nPrevCol)
1605 for (int i = 0; i < nCol; i++)
1612 for (int i = 0; i < nCol; i++)
1617 block.ReadFromDisk(pindex);
1618 printf("%d (%u,%u) %s %s tx %d",
1622 block.GetHash().ToString().substr(0,20).c_str(),
1623 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1626 PrintWallets(block);
1628 // put the main timechain first
1629 vector<CBlockIndex*>& vNext = mapNext[pindex];
1630 for (int i = 0; i < vNext.size(); i++)
1632 if (vNext[i]->pnext)
1634 swap(vNext[0], vNext[i]);
1640 for (int i = 0; i < vNext.size(); i++)
1641 vStack.push_back(make_pair(nCol+i, vNext[i]));
1654 //////////////////////////////////////////////////////////////////////////////
1659 map<uint256, CAlert> mapAlerts;
1660 CCriticalSection cs_mapAlerts;
1662 string GetWarnings(string strFor)
1665 string strStatusBar;
1667 if (GetBoolArg("-testsafemode"))
1670 // Misc warnings like out of disk space and clock is wrong
1671 if (strMiscWarning != "")
1674 strStatusBar = strMiscWarning;
1677 // Longer invalid proof-of-work chain
1678 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1681 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1685 CRITICAL_BLOCK(cs_mapAlerts)
1687 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1689 const CAlert& alert = item.second;
1690 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1692 nPriority = alert.nPriority;
1693 strStatusBar = alert.strStatusBar;
1698 if (strFor == "statusbar")
1699 return strStatusBar;
1700 else if (strFor == "rpc")
1702 assert(!"GetWarnings() : invalid parameter");
1706 bool CAlert::ProcessAlert()
1708 if (!CheckSignature())
1713 CRITICAL_BLOCK(cs_mapAlerts)
1715 // Cancel previous alerts
1716 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1718 const CAlert& alert = (*mi).second;
1721 printf("cancelling alert %d\n", alert.nID);
1722 mapAlerts.erase(mi++);
1724 else if (!alert.IsInEffect())
1726 printf("expiring alert %d\n", alert.nID);
1727 mapAlerts.erase(mi++);
1733 // Check if this alert has been cancelled
1734 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1736 const CAlert& alert = item.second;
1737 if (alert.Cancels(*this))
1739 printf("alert already cancelled by %d\n", alert.nID);
1745 mapAlerts.insert(make_pair(GetHash(), *this));
1748 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1760 //////////////////////////////////////////////////////////////////////////////
1766 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1770 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1771 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1773 // Don't know what it is, just say we already got one
1780 // The message start string is designed to be unlikely to occur in normal data.
1781 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1782 // a large 4-byte int at any alignment.
1783 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1786 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1788 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1789 RandAddSeedPerfmon();
1791 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1792 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1794 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1796 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1804 if (strCommand == "version")
1806 // Each connection can only send one version message
1807 if (pfrom->nVersion != 0)
1809 pfrom->Misbehaving(1);
1817 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1818 if (pfrom->nVersion == 10300)
1819 pfrom->nVersion = 300;
1820 if (pfrom->nVersion >= 106 && !vRecv.empty())
1821 vRecv >> addrFrom >> nNonce;
1822 if (pfrom->nVersion >= 106 && !vRecv.empty())
1823 vRecv >> pfrom->strSubVer;
1824 if (pfrom->nVersion >= 209 && !vRecv.empty())
1825 vRecv >> pfrom->nStartingHeight;
1827 if (pfrom->nVersion == 0)
1830 // Disconnect if we connected to ourself
1831 if (nNonce == nLocalHostNonce && nNonce > 1)
1833 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1834 pfrom->fDisconnect = true;
1838 // Be shy and don't send version until we hear
1839 if (pfrom->fInbound)
1840 pfrom->PushVersion();
1842 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1844 AddTimeData(pfrom->addr.ip, nTime);
1847 if (pfrom->nVersion >= 209)
1848 pfrom->PushMessage("verack");
1849 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1850 if (pfrom->nVersion < 209)
1851 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1853 if (!pfrom->fInbound)
1855 // Advertise our address
1856 if (addrLocalHost.IsRoutable() && !fUseProxy)
1858 CAddress addr(addrLocalHost);
1859 addr.nTime = GetAdjustedTime();
1860 pfrom->PushAddress(addr);
1863 // Get recent addresses
1864 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1866 pfrom->PushMessage("getaddr");
1867 pfrom->fGetAddr = true;
1871 // Ask the first connected node for block updates
1872 static int nAskedForBlocks;
1873 if (!pfrom->fClient &&
1874 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
1875 (nAskedForBlocks < 1 || vNodes.size() <= 1))
1878 pfrom->PushGetBlocks(pindexBest, uint256(0));
1882 CRITICAL_BLOCK(cs_mapAlerts)
1883 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1884 item.second.RelayTo(pfrom);
1886 pfrom->fSuccessfullyConnected = true;
1888 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1890 cPeerBlockCounts.input(pfrom->nStartingHeight);
1894 else if (pfrom->nVersion == 0)
1896 // Must have a version message before anything else
1897 pfrom->Misbehaving(1);
1902 else if (strCommand == "verack")
1904 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1908 else if (strCommand == "addr")
1910 vector<CAddress> vAddr;
1913 // Don't want addr from older versions unless seeding
1914 if (pfrom->nVersion < 209)
1916 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1918 if (vAddr.size() > 1000)
1920 pfrom->Misbehaving(20);
1921 return error("message addr size() = %d", vAddr.size());
1924 // Store the new addresses
1927 int64 nNow = GetAdjustedTime();
1928 int64 nSince = nNow - 10 * 60;
1929 BOOST_FOREACH(CAddress& addr, vAddr)
1933 // ignore IPv6 for now, since it isn't implemented anyway
1936 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1937 addr.nTime = nNow - 5 * 24 * 60 * 60;
1938 AddAddress(addr, 2 * 60 * 60, &addrDB);
1939 pfrom->AddAddressKnown(addr);
1940 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1942 // Relay to a limited number of other nodes
1943 CRITICAL_BLOCK(cs_vNodes)
1945 // Use deterministic randomness to send to the same nodes for 24 hours
1946 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1947 static uint256 hashSalt;
1949 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1950 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1951 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1952 multimap<uint256, CNode*> mapMix;
1953 BOOST_FOREACH(CNode* pnode, vNodes)
1955 if (pnode->nVersion < 31402)
1957 unsigned int nPointer;
1958 memcpy(&nPointer, &pnode, sizeof(nPointer));
1959 uint256 hashKey = hashRand ^ nPointer;
1960 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1961 mapMix.insert(make_pair(hashKey, pnode));
1963 int nRelayNodes = 2;
1964 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1965 ((*mi).second)->PushAddress(addr);
1969 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
1970 if (vAddr.size() < 1000)
1971 pfrom->fGetAddr = false;
1975 else if (strCommand == "inv")
1979 if (vInv.size() > 50000)
1981 pfrom->Misbehaving(20);
1982 return error("message inv size() = %d", vInv.size());
1986 BOOST_FOREACH(const CInv& inv, vInv)
1990 pfrom->AddInventoryKnown(inv);
1992 bool fAlreadyHave = AlreadyHave(txdb, inv);
1994 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1998 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
1999 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2001 // Track requests for our stuff
2002 Inventory(inv.hash);
2007 else if (strCommand == "getdata")
2011 if (vInv.size() > 50000)
2013 pfrom->Misbehaving(20);
2014 return error("message getdata size() = %d", vInv.size());
2017 BOOST_FOREACH(const CInv& inv, vInv)
2021 printf("received getdata for: %s\n", inv.ToString().c_str());
2023 if (inv.type == MSG_BLOCK)
2025 // Send block from disk
2026 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2027 if (mi != mapBlockIndex.end())
2030 block.ReadFromDisk((*mi).second);
2031 pfrom->PushMessage("block", block);
2033 // Trigger them to send a getblocks request for the next batch of inventory
2034 if (inv.hash == pfrom->hashContinue)
2036 // Bypass PushInventory, this must send even if redundant,
2037 // and we want it right after the last block so they don't
2038 // wait for other stuff first.
2040 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2041 pfrom->PushMessage("inv", vInv);
2042 pfrom->hashContinue = 0;
2046 else if (inv.IsKnownType())
2048 // Send stream from relay memory
2049 CRITICAL_BLOCK(cs_mapRelay)
2051 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2052 if (mi != mapRelay.end())
2053 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2057 // Track requests for our stuff
2058 Inventory(inv.hash);
2063 else if (strCommand == "getblocks")
2065 CBlockLocator locator;
2067 vRecv >> locator >> hashStop;
2069 // Find the last block the caller has in the main chain
2070 CBlockIndex* pindex = locator.GetBlockIndex();
2072 // Send the rest of the chain
2074 pindex = pindex->pnext;
2075 int nLimit = 500 + locator.GetDistanceBack();
2076 unsigned int nBytes = 0;
2077 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2078 for (; pindex; pindex = pindex->pnext)
2080 if (pindex->GetBlockHash() == hashStop)
2082 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2085 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2087 block.ReadFromDisk(pindex, true);
2088 nBytes += block.GetSerializeSize(SER_NETWORK);
2089 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2091 // When this block is requested, we'll send an inv that'll make them
2092 // getblocks the next batch of inventory.
2093 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2094 pfrom->hashContinue = pindex->GetBlockHash();
2101 else if (strCommand == "getheaders")
2103 CBlockLocator locator;
2105 vRecv >> locator >> hashStop;
2107 CBlockIndex* pindex = NULL;
2108 if (locator.IsNull())
2110 // If locator is null, return the hashStop block
2111 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2112 if (mi == mapBlockIndex.end())
2114 pindex = (*mi).second;
2118 // Find the last block the caller has in the main chain
2119 pindex = locator.GetBlockIndex();
2121 pindex = pindex->pnext;
2124 vector<CBlock> vHeaders;
2125 int nLimit = 2000 + locator.GetDistanceBack();
2126 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2127 for (; pindex; pindex = pindex->pnext)
2129 vHeaders.push_back(pindex->GetBlockHeader());
2130 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2133 pfrom->PushMessage("headers", vHeaders);
2137 else if (strCommand == "tx")
2139 vector<uint256> vWorkQueue;
2140 CDataStream vMsg(vRecv);
2144 CInv inv(MSG_TX, tx.GetHash());
2145 pfrom->AddInventoryKnown(inv);
2147 bool fMissingInputs = false;
2148 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2150 SyncWithWallets(tx, NULL, true);
2151 RelayMessage(inv, vMsg);
2152 mapAlreadyAskedFor.erase(inv);
2153 vWorkQueue.push_back(inv.hash);
2155 // Recursively process any orphan transactions that depended on this one
2156 for (int i = 0; i < vWorkQueue.size(); i++)
2158 uint256 hashPrev = vWorkQueue[i];
2159 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2160 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2163 const CDataStream& vMsg = *((*mi).second);
2165 CDataStream(vMsg) >> tx;
2166 CInv inv(MSG_TX, tx.GetHash());
2168 if (tx.AcceptToMemoryPool(true))
2170 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2171 SyncWithWallets(tx, NULL, true);
2172 RelayMessage(inv, vMsg);
2173 mapAlreadyAskedFor.erase(inv);
2174 vWorkQueue.push_back(inv.hash);
2179 BOOST_FOREACH(uint256 hash, vWorkQueue)
2180 EraseOrphanTx(hash);
2182 else if (fMissingInputs)
2184 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2187 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2191 else if (strCommand == "block")
2196 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2199 CInv inv(MSG_BLOCK, block.GetHash());
2200 pfrom->AddInventoryKnown(inv);
2202 if (ProcessBlock(pfrom, &block))
2203 mapAlreadyAskedFor.erase(inv);
2204 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2208 else if (strCommand == "getaddr")
2210 // Nodes rebroadcast an addr every 24 hours
2211 pfrom->vAddrToSend.clear();
2212 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2213 CRITICAL_BLOCK(cs_mapAddresses)
2215 unsigned int nCount = 0;
2216 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2218 const CAddress& addr = item.second;
2219 if (addr.nTime > nSince)
2222 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2224 const CAddress& addr = item.second;
2225 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2226 pfrom->PushAddress(addr);
2232 else if (strCommand == "checkorder")
2237 if (!GetBoolArg("-allowreceivebyip"))
2239 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2246 /// we have a chance to check the order here
2248 // Keep giving the same key to the same ip until they use it
2249 if (!mapReuseKey.count(pfrom->addr.ip))
2250 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2252 // Send back approval of order and pubkey to use
2253 CScript scriptPubKey;
2254 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2255 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2259 else if (strCommand == "reply")
2264 CRequestTracker tracker;
2265 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2267 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2268 if (mi != pfrom->mapRequests.end())
2270 tracker = (*mi).second;
2271 pfrom->mapRequests.erase(mi);
2274 if (!tracker.IsNull())
2275 tracker.fn(tracker.param1, vRecv);
2279 else if (strCommand == "ping")
2284 else if (strCommand == "alert")
2289 if (alert.ProcessAlert())
2292 pfrom->setKnown.insert(alert.GetHash());
2293 CRITICAL_BLOCK(cs_vNodes)
2294 BOOST_FOREACH(CNode* pnode, vNodes)
2295 alert.RelayTo(pnode);
2302 // Ignore unknown commands for extensibility
2306 // Update the last seen time for this node's address
2307 if (pfrom->fNetworkNode)
2308 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2309 AddressCurrentlyConnected(pfrom->addr);
2315 bool ProcessMessages(CNode* pfrom)
2317 CDataStream& vRecv = pfrom->vRecv;
2321 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2325 // (4) message start
2334 // Scan for message start
2335 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2336 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2337 if (vRecv.end() - pstart < nHeaderSize)
2339 if (vRecv.size() > nHeaderSize)
2341 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2342 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2346 if (pstart - vRecv.begin() > 0)
2347 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2348 vRecv.erase(vRecv.begin(), pstart);
2351 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2356 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2359 string strCommand = hdr.GetCommand();
2362 unsigned int nMessageSize = hdr.nMessageSize;
2363 if (nMessageSize > MAX_SIZE)
2365 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2368 if (nMessageSize > vRecv.size())
2370 // Rewind and wait for rest of message
2371 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2376 if (vRecv.GetVersion() >= 209)
2378 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2379 unsigned int nChecksum = 0;
2380 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2381 if (nChecksum != hdr.nChecksum)
2383 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2384 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2389 // Copy message to its own buffer
2390 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2391 vRecv.ignore(nMessageSize);
2397 CRITICAL_BLOCK(cs_main)
2398 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2402 catch (std::ios_base::failure& e)
2404 if (strstr(e.what(), "end of data"))
2406 // Allow exceptions from underlength message on vRecv
2407 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());
2409 else if (strstr(e.what(), "size too large"))
2411 // Allow exceptions from overlong size
2412 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2416 PrintExceptionContinue(&e, "ProcessMessage()");
2419 catch (std::exception& e) {
2420 PrintExceptionContinue(&e, "ProcessMessage()");
2422 PrintExceptionContinue(NULL, "ProcessMessage()");
2426 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2434 bool SendMessages(CNode* pto, bool fSendTrickle)
2436 CRITICAL_BLOCK(cs_main)
2438 // Don't send anything until we get their version message
2439 if (pto->nVersion == 0)
2443 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2444 pto->PushMessage("ping");
2446 // Resend wallet transactions that haven't gotten in a block yet
2447 ResendWalletTransactions();
2449 // Address refresh broadcast
2450 static int64 nLastRebroadcast;
2451 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2453 nLastRebroadcast = GetTime();
2454 CRITICAL_BLOCK(cs_vNodes)
2456 BOOST_FOREACH(CNode* pnode, vNodes)
2458 // Periodically clear setAddrKnown to allow refresh broadcasts
2459 pnode->setAddrKnown.clear();
2461 // Rebroadcast our address
2462 if (addrLocalHost.IsRoutable() && !fUseProxy)
2464 CAddress addr(addrLocalHost);
2465 addr.nTime = GetAdjustedTime();
2466 pnode->PushAddress(addr);
2472 // Clear out old addresses periodically so it's not too much work at once
2473 static int64 nLastClear;
2474 if (nLastClear == 0)
2475 nLastClear = GetTime();
2476 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2478 nLastClear = GetTime();
2479 CRITICAL_BLOCK(cs_mapAddresses)
2482 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2483 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2484 mi != mapAddresses.end();)
2486 const CAddress& addr = (*mi).second;
2487 if (addr.nTime < nSince)
2489 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2491 addrdb.EraseAddress(addr);
2492 mapAddresses.erase(mi++);
2506 vector<CAddress> vAddr;
2507 vAddr.reserve(pto->vAddrToSend.size());
2508 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2510 // returns true if wasn't already contained in the set
2511 if (pto->setAddrKnown.insert(addr).second)
2513 vAddr.push_back(addr);
2514 // receiver rejects addr messages larger than 1000
2515 if (vAddr.size() >= 1000)
2517 pto->PushMessage("addr", vAddr);
2522 pto->vAddrToSend.clear();
2524 pto->PushMessage("addr", vAddr);
2529 // Message: inventory
2532 vector<CInv> vInvWait;
2533 CRITICAL_BLOCK(pto->cs_inventory)
2535 vInv.reserve(pto->vInventoryToSend.size());
2536 vInvWait.reserve(pto->vInventoryToSend.size());
2537 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2539 if (pto->setInventoryKnown.count(inv))
2542 // trickle out tx inv to protect privacy
2543 if (inv.type == MSG_TX && !fSendTrickle)
2545 // 1/4 of tx invs blast to all immediately
2546 static uint256 hashSalt;
2548 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2549 uint256 hashRand = inv.hash ^ hashSalt;
2550 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2551 bool fTrickleWait = ((hashRand & 3) != 0);
2553 // always trickle our own transactions
2557 if (GetTransaction(inv.hash, wtx))
2559 fTrickleWait = true;
2564 vInvWait.push_back(inv);
2569 // returns true if wasn't already contained in the set
2570 if (pto->setInventoryKnown.insert(inv).second)
2572 vInv.push_back(inv);
2573 if (vInv.size() >= 1000)
2575 pto->PushMessage("inv", vInv);
2580 pto->vInventoryToSend = vInvWait;
2583 pto->PushMessage("inv", vInv);
2589 vector<CInv> vGetData;
2590 int64 nNow = GetTime() * 1000000;
2592 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2594 const CInv& inv = (*pto->mapAskFor.begin()).second;
2595 if (!AlreadyHave(txdb, inv))
2597 printf("sending getdata: %s\n", inv.ToString().c_str());
2598 vGetData.push_back(inv);
2599 if (vGetData.size() >= 1000)
2601 pto->PushMessage("getdata", vGetData);
2605 mapAlreadyAskedFor[inv] = nNow;
2606 pto->mapAskFor.erase(pto->mapAskFor.begin());
2608 if (!vGetData.empty())
2609 pto->PushMessage("getdata", vGetData);
2628 //////////////////////////////////////////////////////////////////////////////
2633 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2635 unsigned char* pdata = (unsigned char*)pbuffer;
2636 unsigned int blocks = 1 + ((len + 8) / 64);
2637 unsigned char* pend = pdata + 64 * blocks;
2638 memset(pdata + len, 0, 64 * blocks - len);
2640 unsigned int bits = len * 8;
2641 pend[-1] = (bits >> 0) & 0xff;
2642 pend[-2] = (bits >> 8) & 0xff;
2643 pend[-3] = (bits >> 16) & 0xff;
2644 pend[-4] = (bits >> 24) & 0xff;
2648 static const unsigned int pSHA256InitState[8] =
2649 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2651 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2654 unsigned char data[64];
2658 for (int i = 0; i < 16; i++)
2659 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2661 for (int i = 0; i < 8; i++)
2662 ctx.h[i] = ((uint32_t*)pinit)[i];
2664 SHA256_Update(&ctx, data, sizeof(data));
2665 for (int i = 0; i < 8; i++)
2666 ((uint32_t*)pstate)[i] = ctx.h[i];
2670 // ScanHash scans nonces looking for a hash with at least some zero bits.
2671 // It operates on big endian data. Caller does the byte reversing.
2672 // All input buffers are 16-byte aligned. nNonce is usually preserved
2673 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2674 // the block is rebuilt and nNonce starts over at zero.
2676 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2678 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2682 // Hash pdata using pmidstate as the starting state into
2683 // preformatted buffer phash1, then hash phash1 into phash
2685 SHA256Transform(phash1, pdata, pmidstate);
2686 SHA256Transform(phash, phash1, pSHA256InitState);
2688 // Return the nonce if the hash has at least some zero bits,
2689 // caller will check if it has enough to reach the target
2690 if (((unsigned short*)phash)[14] == 0)
2693 // If nothing found after trying for a while, return -1
2694 if ((nNonce & 0xffff) == 0)
2696 nHashesDone = 0xffff+1;
2702 // Some explaining would be appreciated
2707 set<uint256> setDependsOn;
2710 COrphan(CTransaction* ptxIn)
2718 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2719 BOOST_FOREACH(uint256 hash, setDependsOn)
2720 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2725 CBlock* CreateNewBlock(CReserveKey& reservekey)
2727 CBlockIndex* pindexPrev = pindexBest;
2730 auto_ptr<CBlock> pblock(new CBlock());
2734 // Create coinbase tx
2736 txNew.vin.resize(1);
2737 txNew.vin[0].prevout.SetNull();
2738 txNew.vout.resize(1);
2739 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2741 // Add our coinbase tx as first transaction
2742 pblock->vtx.push_back(txNew);
2744 // Collect memory pool transactions into the block
2746 CRITICAL_BLOCK(cs_main)
2747 CRITICAL_BLOCK(cs_mapTransactions)
2751 // Priority order to process transactions
2752 list<COrphan> vOrphan; // list memory doesn't move
2753 map<uint256, vector<COrphan*> > mapDependers;
2754 multimap<double, CTransaction*> mapPriority;
2755 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2757 CTransaction& tx = (*mi).second;
2758 if (tx.IsCoinBase() || !tx.IsFinal())
2761 COrphan* porphan = NULL;
2762 double dPriority = 0;
2763 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2765 // Read prev transaction
2766 CTransaction txPrev;
2768 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2770 // Has to wait for dependencies
2773 // Use list for automatic deletion
2774 vOrphan.push_back(COrphan(&tx));
2775 porphan = &vOrphan.back();
2777 mapDependers[txin.prevout.hash].push_back(porphan);
2778 porphan->setDependsOn.insert(txin.prevout.hash);
2781 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2783 // Read block header
2784 int nConf = txindex.GetDepthInMainChain();
2786 dPriority += (double)nValueIn * nConf;
2788 if (fDebug && GetBoolArg("-printpriority"))
2789 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2792 // Priority is sum(valuein * age) / txsize
2793 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2796 porphan->dPriority = dPriority;
2798 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2800 if (fDebug && GetBoolArg("-printpriority"))
2802 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2809 // Collect transactions into block
2810 map<uint256, CTxIndex> mapTestPool;
2811 uint64 nBlockSize = 1000;
2812 int nBlockSigOps = 100;
2813 while (!mapPriority.empty())
2815 // Take highest priority transaction off priority queue
2816 double dPriority = -(*mapPriority.begin()).first;
2817 CTransaction& tx = *(*mapPriority.begin()).second;
2818 mapPriority.erase(mapPriority.begin());
2821 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2822 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2824 int nTxSigOps = tx.GetSigOpCount();
2825 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2828 // Transaction fee required depends on block size
2829 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2830 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
2832 // Connecting shouldn't fail due to dependency on other memory pool transactions
2833 // because we're already processing them in order of dependency
2834 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2835 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2837 swap(mapTestPool, mapTestPoolTmp);
2840 pblock->vtx.push_back(tx);
2841 nBlockSize += nTxSize;
2842 nBlockSigOps += nTxSigOps;
2844 // Add transactions that depend on this one to the priority queue
2845 uint256 hash = tx.GetHash();
2846 if (mapDependers.count(hash))
2848 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2850 if (!porphan->setDependsOn.empty())
2852 porphan->setDependsOn.erase(hash);
2853 if (porphan->setDependsOn.empty())
2854 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2860 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2863 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2864 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2865 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2866 pblock->nBits = GetNextWorkRequired(pindexPrev);
2869 return pblock.release();
2873 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2875 // Update nExtraNonce
2876 static uint256 hashPrevBlock;
2877 if (hashPrevBlock != pblock->hashPrevBlock)
2880 hashPrevBlock = pblock->hashPrevBlock;
2883 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
2884 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2888 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2891 // Prebuild hash buffers
2898 uint256 hashPrevBlock;
2899 uint256 hashMerkleRoot;
2902 unsigned int nNonce;
2905 unsigned char pchPadding0[64];
2907 unsigned char pchPadding1[64];
2910 memset(&tmp, 0, sizeof(tmp));
2912 tmp.block.nVersion = pblock->nVersion;
2913 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2914 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2915 tmp.block.nTime = pblock->nTime;
2916 tmp.block.nBits = pblock->nBits;
2917 tmp.block.nNonce = pblock->nNonce;
2919 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2920 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2922 // Byte swap all the input buffer
2923 for (int i = 0; i < sizeof(tmp)/4; i++)
2924 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2926 // Precalc the first half of the first hash, which stays constant
2927 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2929 memcpy(pdata, &tmp.block, 128);
2930 memcpy(phash1, &tmp.hash1, 64);
2934 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2936 uint256 hash = pblock->GetHash();
2937 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2939 if (hash > hashTarget)
2943 printf("BitcoinMiner:\n");
2944 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2946 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2947 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2950 CRITICAL_BLOCK(cs_main)
2952 if (pblock->hashPrevBlock != hashBestChain)
2953 return error("BitcoinMiner : generated block is stale");
2955 // Remove key from key pool
2956 reservekey.KeepKey();
2958 // Track how many getdata requests this block gets
2959 CRITICAL_BLOCK(wallet.cs_wallet)
2960 wallet.mapRequestCount[pblock->GetHash()] = 0;
2962 // Process this block the same as if we had received it from another node
2963 if (!ProcessBlock(NULL, pblock))
2964 return error("BitcoinMiner : ProcessBlock, block not accepted");
2970 void static ThreadBitcoinMiner(void* parg);
2972 void static BitcoinMiner(CWallet *pwallet)
2974 printf("BitcoinMiner started\n");
2975 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2977 // Each thread has its own key and counter
2978 CReserveKey reservekey(pwallet);
2979 unsigned int nExtraNonce = 0;
2981 while (fGenerateBitcoins)
2983 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2987 while (vNodes.empty() || IsInitialBlockDownload())
2992 if (!fGenerateBitcoins)
3000 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3001 CBlockIndex* pindexPrev = pindexBest;
3003 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3006 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3008 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3012 // Prebuild hash buffers
3014 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3015 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3016 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3018 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3020 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3021 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3027 int64 nStart = GetTime();
3028 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3030 uint256& hash = *alignup<16>(hashbuf);
3033 unsigned int nHashesDone = 0;
3034 unsigned int nNonceFound;
3037 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3038 (char*)&hash, nHashesDone);
3040 // Check if something found
3041 if (nNonceFound != -1)
3043 for (int i = 0; i < sizeof(hash)/4; i++)
3044 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3046 if (hash <= hashTarget)
3049 pblock->nNonce = ByteReverse(nNonceFound);
3050 assert(hash == pblock->GetHash());
3052 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3053 CheckWork(pblock.get(), *pwalletMain, reservekey);
3054 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3060 static int64 nHashCounter;
3061 if (nHPSTimerStart == 0)
3063 nHPSTimerStart = GetTimeMillis();
3067 nHashCounter += nHashesDone;
3068 if (GetTimeMillis() - nHPSTimerStart > 4000)
3070 static CCriticalSection cs;
3073 if (GetTimeMillis() - nHPSTimerStart > 4000)
3075 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3076 nHPSTimerStart = GetTimeMillis();
3078 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3079 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3080 static int64 nLogTime;
3081 if (GetTime() - nLogTime > 30 * 60)
3083 nLogTime = GetTime();
3084 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3085 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3091 // Check for stop or if block needs to be rebuilt
3094 if (!fGenerateBitcoins)
3096 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3100 if (nBlockNonce >= 0xffff0000)
3102 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3104 if (pindexPrev != pindexBest)
3107 // Update nTime every few seconds
3108 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3109 nBlockTime = ByteReverse(pblock->nTime);
3114 void static ThreadBitcoinMiner(void* parg)
3116 CWallet* pwallet = (CWallet*)parg;
3119 vnThreadsRunning[3]++;
3120 BitcoinMiner(pwallet);
3121 vnThreadsRunning[3]--;
3123 catch (std::exception& e) {
3124 vnThreadsRunning[3]--;
3125 PrintException(&e, "ThreadBitcoinMiner()");
3127 vnThreadsRunning[3]--;
3128 PrintException(NULL, "ThreadBitcoinMiner()");
3130 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3132 if (vnThreadsRunning[3] == 0)
3134 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3138 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3140 if (fGenerateBitcoins != fGenerate)
3142 fGenerateBitcoins = fGenerate;
3143 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3146 if (fGenerateBitcoins)
3148 int nProcessors = boost::thread::hardware_concurrency();
3149 printf("%d processors\n", nProcessors);
3150 if (nProcessors < 1)
3152 if (fLimitProcessors && nProcessors > nLimitProcessors)
3153 nProcessors = nLimitProcessors;
3154 int nAddThreads = nProcessors - vnThreadsRunning[3];
3155 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3156 for (int i = 0; i < nAddThreads; i++)
3158 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3159 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");