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.
6 #include "cryptopp/sha.h"
16 CCriticalSection cs_main;
18 map<uint256, CTransaction> mapTransactions;
19 CCriticalSection cs_mapTransactions;
20 unsigned int nTransactionsUpdated = 0;
21 map<COutPoint, CInPoint> mapNextTx;
23 map<uint256, CBlockIndex*> mapBlockIndex;
24 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
25 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
26 CBlockIndex* pindexGenesisBlock = NULL;
28 CBigNum bnBestChainWork = 0;
29 CBigNum bnBestInvalidWork = 0;
30 uint256 hashBestChain = 0;
31 CBlockIndex* pindexBest = NULL;
32 int64 nTimeBestReceived = 0;
34 map<uint256, CBlock*> mapOrphanBlocks;
35 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
37 map<uint256, CDataStream*> mapOrphanTransactions;
38 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
40 map<uint256, CWalletTx> mapWallet;
41 vector<uint256> vWalletUpdated;
42 CCriticalSection cs_mapWallet;
44 map<vector<unsigned char>, CPrivKey> mapKeys;
45 map<uint160, vector<unsigned char> > mapPubKeys;
46 CCriticalSection cs_mapKeys;
49 map<uint256, int> mapRequestCount;
50 CCriticalSection cs_mapRequestCount;
52 map<string, string> mapAddressBook;
53 CCriticalSection cs_mapAddressBook;
55 vector<unsigned char> vchDefaultKey;
61 int fGenerateBitcoins = false;
62 int64 nTransactionFee = 0;
63 CAddress addrIncoming;
64 int fLimitProcessors = false;
65 int nLimitProcessors = 1;
66 int fMinimizeToTray = true;
67 int fMinimizeOnClose = true;
74 //////////////////////////////////////////////////////////////////////////////
79 bool AddKey(const CKey& key)
81 CRITICAL_BLOCK(cs_mapKeys)
83 mapKeys[key.GetPubKey()] = key.GetPrivKey();
84 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
86 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
89 vector<unsigned char> GenerateNewKey()
95 throw runtime_error("GenerateNewKey() : AddKey failed");
96 return key.GetPubKey();
102 //////////////////////////////////////////////////////////////////////////////
107 bool AddToWallet(const CWalletTx& wtxIn)
109 uint256 hash = wtxIn.GetHash();
110 CRITICAL_BLOCK(cs_mapWallet)
112 // Inserts only if not already there, returns tx inserted or tx found
113 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
114 CWalletTx& wtx = (*ret.first).second;
115 bool fInsertedNew = ret.second;
117 wtx.nTimeReceived = GetAdjustedTime();
119 bool fUpdated = false;
123 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
125 wtx.hashBlock = wtxIn.hashBlock;
128 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
130 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
131 wtx.nIndex = wtxIn.nIndex;
134 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
136 wtx.fFromMe = wtxIn.fFromMe;
139 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
141 wtx.fSpent = wtxIn.fSpent;
147 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
150 if (fInsertedNew || fUpdated)
151 if (!wtx.WriteToDisk())
154 // If default receiving address gets used, replace it with a new one
155 CScript scriptDefaultKey;
156 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
157 foreach(const CTxOut& txout, wtx.vout)
159 if (txout.scriptPubKey == scriptDefaultKey)
162 vchDefaultKey = GetKeyFromKeyPool();
163 walletdb.WriteDefaultKey(vchDefaultKey);
164 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
169 vWalletUpdated.push_back(hash);
177 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
179 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
182 // Get merkle branch if transaction was found in a block
184 wtx.SetMerkleBranch(pblock);
185 return AddToWallet(wtx);
190 bool EraseFromWallet(uint256 hash)
192 CRITICAL_BLOCK(cs_mapWallet)
194 if (mapWallet.erase(hash))
195 CWalletDB().EraseTx(hash);
200 void WalletUpdateSpent(const COutPoint& prevout)
202 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
203 // Update the wallet spent flag if it doesn't know due to wallet.dat being
204 // restored from backup or the user making copies of wallet.dat.
205 CRITICAL_BLOCK(cs_mapWallet)
207 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
208 if (mi != mapWallet.end())
210 CWalletTx& wtx = (*mi).second;
211 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
213 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
216 vWalletUpdated.push_back(prevout.hash);
229 //////////////////////////////////////////////////////////////////////////////
231 // mapOrphanTransactions
234 void AddOrphanTx(const CDataStream& vMsg)
237 CDataStream(vMsg) >> tx;
238 uint256 hash = tx.GetHash();
239 if (mapOrphanTransactions.count(hash))
241 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
242 foreach(const CTxIn& txin, tx.vin)
243 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
246 void EraseOrphanTx(uint256 hash)
248 if (!mapOrphanTransactions.count(hash))
250 const CDataStream* pvMsg = mapOrphanTransactions[hash];
252 CDataStream(*pvMsg) >> tx;
253 foreach(const CTxIn& txin, tx.vin)
255 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
256 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
258 if ((*mi).second == pvMsg)
259 mapOrphanTransactionsByPrev.erase(mi++);
265 mapOrphanTransactions.erase(hash);
275 //////////////////////////////////////////////////////////////////////////////
280 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
283 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
285 if (!ReadFromDisk(txindexRet.pos))
287 if (prevout.n >= vout.size())
295 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
298 return ReadFromDisk(txdb, prevout, txindex);
301 bool CTransaction::ReadFromDisk(COutPoint prevout)
305 return ReadFromDisk(txdb, prevout, txindex);
308 bool CTxIn::IsMine() const
310 CRITICAL_BLOCK(cs_mapWallet)
312 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
313 if (mi != mapWallet.end())
315 const CWalletTx& prev = (*mi).second;
316 if (prevout.n < prev.vout.size())
317 if (prev.vout[prevout.n].IsMine())
324 int64 CTxIn::GetDebit() const
326 CRITICAL_BLOCK(cs_mapWallet)
328 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
329 if (mi != mapWallet.end())
331 const CWalletTx& prev = (*mi).second;
332 if (prevout.n < prev.vout.size())
333 if (prev.vout[prevout.n].IsMine())
334 return prev.vout[prevout.n].nValue;
340 int64 CWalletTx::GetTxTime() const
342 if (!fTimeReceivedIsTxTime && hashBlock != 0)
344 // If we did not receive the transaction directly, we rely on the block's
345 // time to figure out when it happened. We use the median over a range
346 // of blocks to try to filter out inaccurate block times.
347 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
348 if (mi != mapBlockIndex.end())
350 CBlockIndex* pindex = (*mi).second;
352 return pindex->GetMedianTime();
355 return nTimeReceived;
358 int CWalletTx::GetRequestCount() const
360 // Returns -1 if it wasn't being tracked
362 CRITICAL_BLOCK(cs_mapRequestCount)
369 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
370 if (mi != mapRequestCount.end())
371 nRequests = (*mi).second;
376 // Did anyone request this transaction?
377 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
378 if (mi != mapRequestCount.end())
380 nRequests = (*mi).second;
382 // How about the block it's in?
383 if (nRequests == 0 && hashBlock != 0)
385 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
386 if (mi != mapRequestCount.end())
387 nRequests = (*mi).second;
389 nRequests = 1; // If it's in someone else's block it must have got out
400 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
412 // Load the block this tx is in
414 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
416 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
421 // Update the tx's hashBlock
422 hashBlock = pblock->GetHash();
424 // Locate the transaction
425 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
426 if (pblock->vtx[nIndex] == *(CTransaction*)this)
428 if (nIndex == pblock->vtx.size())
430 vMerkleBranch.clear();
432 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
436 // Fill in merkle branch
437 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
440 // Is the tx in a block that's in the main chain
441 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
442 if (mi == mapBlockIndex.end())
444 CBlockIndex* pindex = (*mi).second;
445 if (!pindex || !pindex->IsInMainChain())
448 return pindexBest->nHeight - pindex->nHeight + 1;
453 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
457 const int COPY_DEPTH = 3;
458 if (SetMerkleBranch() < COPY_DEPTH)
460 vector<uint256> vWorkQueue;
461 foreach(const CTxIn& txin, vin)
462 vWorkQueue.push_back(txin.prevout.hash);
464 // This critsect is OK because txdb is already open
465 CRITICAL_BLOCK(cs_mapWallet)
467 map<uint256, const CMerkleTx*> mapWalletPrev;
468 set<uint256> setAlreadyDone;
469 for (int i = 0; i < vWorkQueue.size(); i++)
471 uint256 hash = vWorkQueue[i];
472 if (setAlreadyDone.count(hash))
474 setAlreadyDone.insert(hash);
477 if (mapWallet.count(hash))
479 tx = mapWallet[hash];
480 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
481 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
483 else if (mapWalletPrev.count(hash))
485 tx = *mapWalletPrev[hash];
487 else if (!fClient && txdb.ReadDiskTx(hash, tx))
493 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
497 int nDepth = tx.SetMerkleBranch();
498 vtxPrev.push_back(tx);
500 if (nDepth < COPY_DEPTH)
501 foreach(const CTxIn& txin, tx.vin)
502 vWorkQueue.push_back(txin.prevout.hash);
507 reverse(vtxPrev.begin(), vtxPrev.end());
520 bool CTransaction::CheckTransaction() const
522 // Basic checks that don't depend on any context
523 if (vin.empty() || vout.empty())
524 return error("CTransaction::CheckTransaction() : vin or vout empty");
527 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
528 return error("CTransaction::CheckTransaction() : size limits failed");
530 // Check for negative or overflow output values
532 foreach(const CTxOut& txout, vout)
534 if (txout.nValue < 0)
535 return error("CTransaction::CheckTransaction() : txout.nValue negative");
536 if (txout.nValue > MAX_MONEY)
537 return error("CTransaction::CheckTransaction() : txout.nValue too high");
538 nValueOut += txout.nValue;
539 if (!MoneyRange(nValueOut))
540 return error("CTransaction::CheckTransaction() : txout total out of range");
545 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
546 return error("CTransaction::CheckTransaction() : coinbase script size");
550 foreach(const CTxIn& txin, vin)
551 if (txin.prevout.IsNull())
552 return error("CTransaction::CheckTransaction() : prevout is null");
558 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
561 *pfMissingInputs = false;
563 if (!CheckTransaction())
564 return error("AcceptToMemoryPool() : CheckTransaction failed");
566 // Coinbase is only valid in a block, not as a loose transaction
568 return error("AcceptToMemoryPool() : coinbase as individual tx");
570 // To help v0.1.5 clients who would see it as a negative number
571 if ((int64)nLockTime > INT_MAX)
572 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
575 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
576 if (GetSigOpCount() > 2 || nSize < 100)
577 return error("AcceptToMemoryPool() : nonstandard transaction");
579 // Rather not work on nonstandard transactions
581 return error("AcceptToMemoryPool() : nonstandard transaction type");
583 // Do we already have it?
584 uint256 hash = GetHash();
585 CRITICAL_BLOCK(cs_mapTransactions)
586 if (mapTransactions.count(hash))
589 if (txdb.ContainsTx(hash))
592 // Check for conflicts with in-memory transactions
593 CTransaction* ptxOld = NULL;
594 for (int i = 0; i < vin.size(); i++)
596 COutPoint outpoint = vin[i].prevout;
597 if (mapNextTx.count(outpoint))
599 // Disable replacement feature for now
602 // Allow replacing with a newer version of the same transaction
605 ptxOld = mapNextTx[outpoint].ptx;
606 if (ptxOld->IsFinal())
608 if (!IsNewerThan(*ptxOld))
610 for (int i = 0; i < vin.size(); i++)
612 COutPoint outpoint = vin[i].prevout;
613 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
622 // Check against previous transactions
623 map<uint256, CTxIndex> mapUnused;
625 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
628 *pfMissingInputs = true;
629 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
632 // Don't accept it if it can't get into a block
633 if (nFees < GetMinFee(1000))
634 return error("AcceptToMemoryPool() : not enough fees");
636 // Limit free transactions per 10 minutes
637 if (nFees < CENT && GetBoolArg("-limitfreerelay"))
639 static int64 nNextReset;
640 static int64 nFreeCount;
641 if (GetTime() > nNextReset)
643 nNextReset = GetTime() + 10 * 60;
646 if (nFreeCount > 150000 && !IsFromMe())
647 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
652 // Store transaction in memory
653 CRITICAL_BLOCK(cs_mapTransactions)
657 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
658 ptxOld->RemoveFromMemoryPool();
660 AddToMemoryPoolUnchecked();
663 ///// are we sure this is ok when loading transactions or restoring block txes
664 // If updated, erase old tx from wallet
666 EraseFromWallet(ptxOld->GetHash());
668 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
673 bool CTransaction::AddToMemoryPoolUnchecked()
675 // Add to memory pool without checking anything. Don't call this directly,
676 // call AcceptToMemoryPool to properly check the transaction first.
677 CRITICAL_BLOCK(cs_mapTransactions)
679 uint256 hash = GetHash();
680 mapTransactions[hash] = *this;
681 for (int i = 0; i < vin.size(); i++)
682 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
683 nTransactionsUpdated++;
689 bool CTransaction::RemoveFromMemoryPool()
691 // Remove transaction from memory pool
692 CRITICAL_BLOCK(cs_mapTransactions)
694 foreach(const CTxIn& txin, vin)
695 mapNextTx.erase(txin.prevout);
696 mapTransactions.erase(GetHash());
697 nTransactionsUpdated++;
707 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
709 if (hashBlock == 0 || nIndex == -1)
712 // Find the block it claims to be in
713 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
714 if (mi == mapBlockIndex.end())
716 CBlockIndex* pindex = (*mi).second;
717 if (!pindex || !pindex->IsInMainChain())
720 // Make sure the merkle branch connects to this block
721 if (!fMerkleVerified)
723 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
725 fMerkleVerified = true;
728 nHeightRet = pindex->nHeight;
729 return pindexBest->nHeight - pindex->nHeight + 1;
733 int CMerkleTx::GetBlocksToMaturity() const
737 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
741 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
745 if (!IsInMainChain() && !ClientConnectInputs())
747 return CTransaction::AcceptToMemoryPool(txdb, false);
751 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
757 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
759 CRITICAL_BLOCK(cs_mapTransactions)
761 // Add previous supporting transactions first
762 foreach(CMerkleTx& tx, vtxPrev)
764 if (!tx.IsCoinBase())
766 uint256 hash = tx.GetHash();
767 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
768 tx.AcceptToMemoryPool(txdb, fCheckInputs);
771 return AcceptToMemoryPool(txdb, fCheckInputs);
776 void ReacceptWalletTransactions()
779 CRITICAL_BLOCK(cs_mapWallet)
781 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
783 CWalletTx& wtx = item.second;
784 if (wtx.fSpent && wtx.IsCoinBase())
788 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
790 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
793 if (txindex.vSpent.size() != wtx.vout.size())
795 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
798 for (int i = 0; i < txindex.vSpent.size(); i++)
800 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
802 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
812 // Reaccept any txes of ours that aren't already in a block
813 if (!wtx.IsCoinBase())
814 wtx.AcceptWalletTransaction(txdb, false);
821 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
823 foreach(const CMerkleTx& tx, vtxPrev)
825 if (!tx.IsCoinBase())
827 uint256 hash = tx.GetHash();
828 if (!txdb.ContainsTx(hash))
829 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
834 uint256 hash = GetHash();
835 if (!txdb.ContainsTx(hash))
837 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
838 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
843 void ResendWalletTransactions()
845 // Do this infrequently and randomly to avoid giving away
846 // that these are our transactions.
847 static int64 nNextTime;
848 if (GetTime() < nNextTime)
850 bool fFirst = (nNextTime == 0);
851 nNextTime = GetTime() + GetRand(30 * 60);
855 // Only do it if there's been a new block since last time
856 static int64 nLastTime;
857 if (nTimeBestReceived < nLastTime)
859 nLastTime = GetTime();
861 // Rebroadcast any of our txes that aren't in a block yet
862 printf("ResendWalletTransactions()\n");
864 CRITICAL_BLOCK(cs_mapWallet)
866 // Sort them in chronological order
867 multimap<unsigned int, CWalletTx*> mapSorted;
868 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
870 CWalletTx& wtx = item.second;
871 // Don't rebroadcast until it's had plenty of time that
872 // it should have gotten in already by now.
873 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
874 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
876 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
878 CWalletTx& wtx = *item.second;
879 wtx.RelayWalletTransaction(txdb);
893 //////////////////////////////////////////////////////////////////////////////
895 // CBlock and CBlockIndex
898 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
900 if (!fReadTransactions)
902 *this = pindex->GetBlockHeader();
905 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
907 if (GetHash() != pindex->GetBlockHash())
908 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
912 uint256 GetOrphanRoot(const CBlock* pblock)
914 // Work back to the first block in the orphan chain
915 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
916 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
917 return pblock->GetHash();
920 int64 GetBlockValue(int nHeight, int64 nFees)
922 int64 nSubsidy = 50 * COIN;
924 // Subsidy is cut in half every 4 years
925 nSubsidy >>= (nHeight / 210000);
927 return nSubsidy + nFees;
930 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
932 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
933 const int64 nTargetSpacing = 10 * 60;
934 const int64 nInterval = nTargetTimespan / nTargetSpacing;
937 if (pindexLast == NULL)
938 return bnProofOfWorkLimit.GetCompact();
940 // Only change once per interval
941 if ((pindexLast->nHeight+1) % nInterval != 0)
942 return pindexLast->nBits;
944 // Go back by what we want to be 14 days worth of blocks
945 const CBlockIndex* pindexFirst = pindexLast;
946 for (int i = 0; pindexFirst && i < nInterval-1; i++)
947 pindexFirst = pindexFirst->pprev;
950 // Limit adjustment step
951 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
952 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
953 if (nActualTimespan < nTargetTimespan/4)
954 nActualTimespan = nTargetTimespan/4;
955 if (nActualTimespan > nTargetTimespan*4)
956 nActualTimespan = nTargetTimespan*4;
960 bnNew.SetCompact(pindexLast->nBits);
961 bnNew *= nActualTimespan;
962 bnNew /= nTargetTimespan;
964 if (bnNew > bnProofOfWorkLimit)
965 bnNew = bnProofOfWorkLimit;
968 printf("GetNextWorkRequired RETARGET\n");
969 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
970 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
971 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
973 return bnNew.GetCompact();
976 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
979 bnTarget.SetCompact(nBits);
982 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
983 return error("CheckProofOfWork() : nBits below minimum work");
985 // Check proof of work matches claimed amount
986 if (hash > bnTarget.getuint256())
987 return error("CheckProofOfWork() : hash doesn't match nBits");
992 bool IsInitialBlockDownload()
994 if (pindexBest == NULL || (!fTestNet && nBestHeight < 74000))
996 static int64 nLastUpdate;
997 static CBlockIndex* pindexLastBest;
998 if (pindexBest != pindexLastBest)
1000 pindexLastBest = pindexBest;
1001 nLastUpdate = GetTime();
1003 return (GetTime() - nLastUpdate < 10 &&
1004 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1007 void InvalidChainFound(CBlockIndex* pindexNew)
1009 if (pindexNew->bnChainWork > bnBestInvalidWork)
1011 bnBestInvalidWork = pindexNew->bnChainWork;
1012 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1015 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());
1016 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1017 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1018 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1031 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1033 // Relinquish previous transactions' spent pointers
1036 foreach(const CTxIn& txin, vin)
1038 COutPoint prevout = txin.prevout;
1040 // Get prev txindex from disk
1042 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1043 return error("DisconnectInputs() : ReadTxIndex failed");
1045 if (prevout.n >= txindex.vSpent.size())
1046 return error("DisconnectInputs() : prevout.n out of range");
1048 // Mark outpoint as not spent
1049 txindex.vSpent[prevout.n].SetNull();
1052 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1053 return error("DisconnectInputs() : UpdateTxIndex failed");
1057 // Remove transaction from index
1058 if (!txdb.EraseTxIndex(*this))
1059 return error("DisconnectInputs() : EraseTxPos failed");
1065 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1066 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1068 // Take over previous transactions' spent pointers
1072 for (int i = 0; i < vin.size(); i++)
1074 COutPoint prevout = vin[i].prevout;
1079 if (fMiner && mapTestPool.count(prevout.hash))
1081 // Get txindex from current proposed changes
1082 txindex = mapTestPool[prevout.hash];
1086 // Read txindex from txdb
1087 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1089 if (!fFound && (fBlock || fMiner))
1090 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());
1093 CTransaction txPrev;
1094 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1096 // Get prev tx from single transactions in memory
1097 CRITICAL_BLOCK(cs_mapTransactions)
1099 if (!mapTransactions.count(prevout.hash))
1100 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1101 txPrev = mapTransactions[prevout.hash];
1104 txindex.vSpent.resize(txPrev.vout.size());
1108 // Get prev tx from disk
1109 if (!txPrev.ReadFromDisk(txindex.pos))
1110 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1113 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1114 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());
1116 // If prev is coinbase, check that it's matured
1117 if (txPrev.IsCoinBase())
1118 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1119 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1120 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1123 if (!VerifySignature(txPrev, *this, i))
1124 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1126 // Check for conflicts
1127 if (!txindex.vSpent[prevout.n].IsNull())
1128 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());
1130 // Check for negative or overflow input values
1131 nValueIn += txPrev.vout[prevout.n].nValue;
1132 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1133 return error("ConnectInputs() : txin values out of range");
1135 // Mark outpoints as spent
1136 txindex.vSpent[prevout.n] = posThisTx;
1141 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1142 return error("ConnectInputs() : UpdateTxIndex failed");
1146 mapTestPool[prevout.hash] = txindex;
1150 if (nValueIn < GetValueOut())
1151 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1153 // Tally transaction fees
1154 int64 nTxFee = nValueIn - GetValueOut();
1156 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1157 if (nTxFee < nMinFee)
1160 if (!MoneyRange(nFees))
1161 return error("ConnectInputs() : nFees out of range");
1166 // Add transaction to disk index
1167 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1168 return error("ConnectInputs() : AddTxPos failed");
1172 // Add transaction to test pool
1173 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1180 bool CTransaction::ClientConnectInputs()
1185 // Take over previous transactions' spent pointers
1186 CRITICAL_BLOCK(cs_mapTransactions)
1189 for (int i = 0; i < vin.size(); i++)
1191 // Get prev tx from single transactions in memory
1192 COutPoint prevout = vin[i].prevout;
1193 if (!mapTransactions.count(prevout.hash))
1195 CTransaction& txPrev = mapTransactions[prevout.hash];
1197 if (prevout.n >= txPrev.vout.size())
1201 if (!VerifySignature(txPrev, *this, i))
1202 return error("ConnectInputs() : VerifySignature failed");
1204 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1205 ///// this has to go away now that posNext is gone
1206 // // Check for conflicts
1207 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1208 // return error("ConnectInputs() : prev tx already used");
1210 // // Flag outpoints as used
1211 // txPrev.vout[prevout.n].posNext = posThisTx;
1213 nValueIn += txPrev.vout[prevout.n].nValue;
1215 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1216 return error("ClientConnectInputs() : txin values out of range");
1218 if (GetValueOut() > nValueIn)
1228 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1230 // Disconnect in reverse order
1231 for (int i = vtx.size()-1; i >= 0; i--)
1232 if (!vtx[i].DisconnectInputs(txdb))
1235 // Update block index on disk without changing it in memory.
1236 // The memory index structure will be changed after the db commits.
1239 CDiskBlockIndex blockindexPrev(pindex->pprev);
1240 blockindexPrev.hashNext = 0;
1241 if (!txdb.WriteBlockIndex(blockindexPrev))
1242 return error("DisconnectBlock() : WriteBlockIndex failed");
1248 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1250 // Check it again in case a previous version let a bad block in
1254 //// issue here: it doesn't know the version
1255 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1257 map<uint256, CTxIndex> mapUnused;
1259 foreach(CTransaction& tx, vtx)
1261 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1262 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1264 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1268 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1271 // Update block index on disk without changing it in memory.
1272 // The memory index structure will be changed after the db commits.
1275 CDiskBlockIndex blockindexPrev(pindex->pprev);
1276 blockindexPrev.hashNext = pindex->GetBlockHash();
1277 if (!txdb.WriteBlockIndex(blockindexPrev))
1278 return error("ConnectBlock() : WriteBlockIndex failed");
1281 // Watch for transactions paying to me
1282 foreach(CTransaction& tx, vtx)
1283 AddToWalletIfMine(tx, this);
1290 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1292 printf("REORGANIZE\n");
1295 CBlockIndex* pfork = pindexBest;
1296 CBlockIndex* plonger = pindexNew;
1297 while (pfork != plonger)
1299 while (plonger->nHeight > pfork->nHeight)
1300 if (!(plonger = plonger->pprev))
1301 return error("Reorganize() : plonger->pprev is null");
1302 if (pfork == plonger)
1304 if (!(pfork = pfork->pprev))
1305 return error("Reorganize() : pfork->pprev is null");
1308 // List of what to disconnect
1309 vector<CBlockIndex*> vDisconnect;
1310 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1311 vDisconnect.push_back(pindex);
1313 // List of what to connect
1314 vector<CBlockIndex*> vConnect;
1315 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1316 vConnect.push_back(pindex);
1317 reverse(vConnect.begin(), vConnect.end());
1319 // Disconnect shorter branch
1320 vector<CTransaction> vResurrect;
1321 foreach(CBlockIndex* pindex, vDisconnect)
1324 if (!block.ReadFromDisk(pindex))
1325 return error("Reorganize() : ReadFromDisk for disconnect failed");
1326 if (!block.DisconnectBlock(txdb, pindex))
1327 return error("Reorganize() : DisconnectBlock failed");
1329 // Queue memory transactions to resurrect
1330 foreach(const CTransaction& tx, block.vtx)
1331 if (!tx.IsCoinBase())
1332 vResurrect.push_back(tx);
1335 // Connect longer branch
1336 vector<CTransaction> vDelete;
1337 for (int i = 0; i < vConnect.size(); i++)
1339 CBlockIndex* pindex = vConnect[i];
1341 if (!block.ReadFromDisk(pindex))
1342 return error("Reorganize() : ReadFromDisk for connect failed");
1343 if (!block.ConnectBlock(txdb, pindex))
1347 return error("Reorganize() : ConnectBlock failed");
1350 // Queue memory transactions to delete
1351 foreach(const CTransaction& tx, block.vtx)
1352 vDelete.push_back(tx);
1354 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1355 return error("Reorganize() : WriteHashBestChain failed");
1357 // Make sure it's successfully written to disk before changing memory structure
1358 if (!txdb.TxnCommit())
1359 return error("Reorganize() : TxnCommit failed");
1361 // Disconnect shorter branch
1362 foreach(CBlockIndex* pindex, vDisconnect)
1364 pindex->pprev->pnext = NULL;
1366 // Connect longer branch
1367 foreach(CBlockIndex* pindex, vConnect)
1369 pindex->pprev->pnext = pindex;
1371 // Resurrect memory transactions that were in the disconnected branch
1372 foreach(CTransaction& tx, vResurrect)
1373 tx.AcceptToMemoryPool(txdb, false);
1375 // Delete redundant memory transactions that are in the connected branch
1376 foreach(CTransaction& tx, vDelete)
1377 tx.RemoveFromMemoryPool();
1383 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1385 uint256 hash = GetHash();
1388 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1390 txdb.WriteHashBestChain(hash);
1391 if (!txdb.TxnCommit())
1392 return error("SetBestChain() : TxnCommit failed");
1393 pindexGenesisBlock = pindexNew;
1395 else if (hashPrevBlock == hashBestChain)
1397 // Adding to current best branch
1398 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1401 InvalidChainFound(pindexNew);
1402 return error("SetBestChain() : ConnectBlock failed");
1404 if (!txdb.TxnCommit())
1405 return error("SetBestChain() : TxnCommit failed");
1407 // Add to current best branch
1408 pindexNew->pprev->pnext = pindexNew;
1410 // Delete redundant memory transactions
1411 foreach(CTransaction& tx, vtx)
1412 tx.RemoveFromMemoryPool();
1417 if (!Reorganize(txdb, pindexNew))
1420 InvalidChainFound(pindexNew);
1421 return error("SetBestChain() : Reorganize failed");
1426 hashBestChain = hash;
1427 pindexBest = pindexNew;
1428 nBestHeight = pindexBest->nHeight;
1429 bnBestChainWork = pindexNew->bnChainWork;
1430 nTimeBestReceived = GetTime();
1431 nTransactionsUpdated++;
1432 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1438 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1440 // Check for duplicate
1441 uint256 hash = GetHash();
1442 if (mapBlockIndex.count(hash))
1443 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1445 // Construct new block index object
1446 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1448 return error("AddToBlockIndex() : new CBlockIndex failed");
1449 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1450 pindexNew->phashBlock = &((*mi).first);
1451 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1452 if (miPrev != mapBlockIndex.end())
1454 pindexNew->pprev = (*miPrev).second;
1455 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1457 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1461 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1462 if (!txdb.TxnCommit())
1466 if (pindexNew->bnChainWork > bnBestChainWork)
1467 if (!SetBestChain(txdb, pindexNew))
1472 if (pindexNew == pindexBest)
1474 // Notify UI to display prev block's coinbase if it was ours
1475 static uint256 hashPrevBestCoinBase;
1476 CRITICAL_BLOCK(cs_mapWallet)
1477 vWalletUpdated.push_back(hashPrevBestCoinBase);
1478 hashPrevBestCoinBase = vtx[0].GetHash();
1488 bool CBlock::CheckBlock() const
1490 // These are checks that are independent of context
1491 // that can be verified before saving an orphan block.
1494 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1495 return error("CheckBlock() : size limits failed");
1497 // Check proof of work matches claimed amount
1498 if (!CheckProofOfWork(GetHash(), nBits))
1499 return error("CheckBlock() : proof of work failed");
1502 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1503 return error("CheckBlock() : block timestamp too far in the future");
1505 // First transaction must be coinbase, the rest must not be
1506 if (vtx.empty() || !vtx[0].IsCoinBase())
1507 return error("CheckBlock() : first tx is not coinbase");
1508 for (int i = 1; i < vtx.size(); i++)
1509 if (vtx[i].IsCoinBase())
1510 return error("CheckBlock() : more than one coinbase");
1512 // Check transactions
1513 foreach(const CTransaction& tx, vtx)
1514 if (!tx.CheckTransaction())
1515 return error("CheckBlock() : CheckTransaction failed");
1517 // Check that it's not full of nonstandard transactions
1518 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1519 return error("CheckBlock() : too many nonstandard transactions");
1522 if (hashMerkleRoot != BuildMerkleTree())
1523 return error("CheckBlock() : hashMerkleRoot mismatch");
1528 bool CBlock::AcceptBlock()
1530 // Check for duplicate
1531 uint256 hash = GetHash();
1532 if (mapBlockIndex.count(hash))
1533 return error("AcceptBlock() : block already in mapBlockIndex");
1535 // Get prev block index
1536 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1537 if (mi == mapBlockIndex.end())
1538 return error("AcceptBlock() : prev block not found");
1539 CBlockIndex* pindexPrev = (*mi).second;
1540 int nHeight = pindexPrev->nHeight+1;
1542 // Check proof of work
1543 if (nBits != GetNextWorkRequired(pindexPrev))
1544 return error("AcceptBlock() : incorrect proof of work");
1546 // Check timestamp against prev
1547 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1548 return error("AcceptBlock() : block's timestamp is too early");
1550 // Check that all transactions are finalized
1551 foreach(const CTransaction& tx, vtx)
1552 if (!tx.IsFinal(nHeight, GetBlockTime()))
1553 return error("AcceptBlock() : contains a non-final transaction");
1555 // Check that the block chain matches the known block chain up to a checkpoint
1557 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1558 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1559 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1560 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1561 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1562 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1564 // Write block to history file
1565 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1566 return error("AcceptBlock() : out of disk space");
1567 unsigned int nFile = -1;
1568 unsigned int nBlockPos = 0;
1569 if (!WriteToDisk(nFile, nBlockPos))
1570 return error("AcceptBlock() : WriteToDisk failed");
1571 if (!AddToBlockIndex(nFile, nBlockPos))
1572 return error("AcceptBlock() : AddToBlockIndex failed");
1574 // Relay inventory, but don't relay old inventory during initial block download
1575 if (hashBestChain == hash)
1576 CRITICAL_BLOCK(cs_vNodes)
1577 foreach(CNode* pnode, vNodes)
1578 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1579 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1584 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1586 // Check for duplicate
1587 uint256 hash = pblock->GetHash();
1588 if (mapBlockIndex.count(hash))
1589 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1590 if (mapOrphanBlocks.count(hash))
1591 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1593 // Preliminary checks
1594 if (!pblock->CheckBlock())
1595 return error("ProcessBlock() : CheckBlock FAILED");
1597 // If don't already have its previous block, shunt it off to holding area until we get it
1598 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1600 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1601 CBlock* pblock2 = new CBlock(*pblock);
1602 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1603 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1605 // Ask this guy to fill in what we're missing
1607 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1612 if (!pblock->AcceptBlock())
1613 return error("ProcessBlock() : AcceptBlock FAILED");
1615 // Recursively process any orphan blocks that depended on this one
1616 vector<uint256> vWorkQueue;
1617 vWorkQueue.push_back(hash);
1618 for (int i = 0; i < vWorkQueue.size(); i++)
1620 uint256 hashPrev = vWorkQueue[i];
1621 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1622 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1625 CBlock* pblockOrphan = (*mi).second;
1626 if (pblockOrphan->AcceptBlock())
1627 vWorkQueue.push_back(pblockOrphan->GetHash());
1628 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1629 delete pblockOrphan;
1631 mapOrphanBlocksByPrev.erase(hashPrev);
1634 printf("ProcessBlock: ACCEPTED\n");
1645 template<typename Stream>
1646 bool ScanMessageStart(Stream& s)
1648 // Scan ahead to the next pchMessageStart, which should normally be immediately
1649 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1651 short prevmask = s.exceptions(0);
1652 const char* p = BEGIN(pchMessageStart);
1662 s.exceptions(prevmask);
1666 p = BEGIN(pchMessageStart);
1669 if (++p == END(pchMessageStart))
1672 s.exceptions(prevmask);
1681 s.exceptions(prevmask);
1686 bool CheckDiskSpace(uint64 nAdditionalBytes)
1688 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1690 // Check for 15MB because database could create another 10MB log file at any time
1691 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1694 string strMessage = _("Warning: Disk space is low ");
1695 strMiscWarning = strMessage;
1696 printf("*** %s\n", strMessage.c_str());
1697 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1698 CreateThread(Shutdown, NULL);
1704 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1708 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1711 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1713 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1722 static unsigned int nCurrentBlockFile = 1;
1724 FILE* AppendBlockFile(unsigned int& nFileRet)
1729 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1732 if (fseek(file, 0, SEEK_END) != 0)
1734 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1735 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1737 nFileRet = nCurrentBlockFile;
1741 nCurrentBlockFile++;
1745 bool LoadBlockIndex(bool fAllowNew)
1749 hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");
1750 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1751 pchMessageStart[0] = 0xfa;
1752 pchMessageStart[1] = 0xbf;
1753 pchMessageStart[2] = 0xb5;
1754 pchMessageStart[3] = 0xda;
1761 if (!txdb.LoadBlockIndex())
1766 // Init with genesis block
1768 if (mapBlockIndex.empty())
1774 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1775 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1776 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1777 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1778 // vMerkleTree: 4a5e1e
1781 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1783 txNew.vin.resize(1);
1784 txNew.vout.resize(1);
1785 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1786 txNew.vout[0].nValue = 50 * COIN;
1787 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1789 block.vtx.push_back(txNew);
1790 block.hashPrevBlock = 0;
1791 block.hashMerkleRoot = block.BuildMerkleTree();
1793 block.nTime = 1231006505;
1794 block.nBits = 0x1d00ffff;
1795 block.nNonce = 2083236893;
1799 block.nTime = 1279232055;
1800 block.nBits = 0x1d07fff8;
1801 block.nNonce = 81622180;
1805 printf("%s\n", block.GetHash().ToString().c_str());
1806 printf("%s\n", hashGenesisBlock.ToString().c_str());
1807 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1808 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1810 assert(block.GetHash() == hashGenesisBlock);
1812 // Start new block file
1814 unsigned int nBlockPos;
1815 if (!block.WriteToDisk(nFile, nBlockPos))
1816 return error("LoadBlockIndex() : writing genesis block to disk failed");
1817 if (!block.AddToBlockIndex(nFile, nBlockPos))
1818 return error("LoadBlockIndex() : genesis block not accepted");
1826 void PrintBlockTree()
1828 // precompute tree structure
1829 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1830 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1832 CBlockIndex* pindex = (*mi).second;
1833 mapNext[pindex->pprev].push_back(pindex);
1835 //while (rand() % 3 == 0)
1836 // mapNext[pindex->pprev].push_back(pindex);
1839 vector<pair<int, CBlockIndex*> > vStack;
1840 vStack.push_back(make_pair(0, pindexGenesisBlock));
1843 while (!vStack.empty())
1845 int nCol = vStack.back().first;
1846 CBlockIndex* pindex = vStack.back().second;
1849 // print split or gap
1850 if (nCol > nPrevCol)
1852 for (int i = 0; i < nCol-1; i++)
1856 else if (nCol < nPrevCol)
1858 for (int i = 0; i < nCol; i++)
1865 for (int i = 0; i < nCol; i++)
1870 block.ReadFromDisk(pindex);
1871 printf("%d (%u,%u) %s %s tx %d",
1875 block.GetHash().ToString().substr(0,20).c_str(),
1876 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1879 CRITICAL_BLOCK(cs_mapWallet)
1881 if (mapWallet.count(block.vtx[0].GetHash()))
1883 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1884 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1890 // put the main timechain first
1891 vector<CBlockIndex*>& vNext = mapNext[pindex];
1892 for (int i = 0; i < vNext.size(); i++)
1894 if (vNext[i]->pnext)
1896 swap(vNext[0], vNext[i]);
1902 for (int i = 0; i < vNext.size(); i++)
1903 vStack.push_back(make_pair(nCol+i, vNext[i]));
1916 //////////////////////////////////////////////////////////////////////////////
1921 map<uint256, CAlert> mapAlerts;
1922 CCriticalSection cs_mapAlerts;
1924 string GetWarnings(string strFor)
1927 string strStatusBar;
1929 if (GetBoolArg("-testsafemode"))
1932 // Misc warnings like out of disk space and clock is wrong
1933 if (strMiscWarning != "")
1936 strStatusBar = strMiscWarning;
1939 // Longer invalid proof-of-work chain
1940 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1943 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1947 CRITICAL_BLOCK(cs_mapAlerts)
1949 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1951 const CAlert& alert = item.second;
1952 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1954 nPriority = alert.nPriority;
1955 strStatusBar = alert.strStatusBar;
1956 strRPC = alert.strRPCError;
1961 if (strFor == "statusbar")
1962 return strStatusBar;
1963 else if (strFor == "rpc")
1965 assert(("GetWarnings() : invalid parameter", false));
1969 bool CAlert::ProcessAlert()
1971 if (!CheckSignature())
1976 CRITICAL_BLOCK(cs_mapAlerts)
1978 // Cancel previous alerts
1979 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1981 const CAlert& alert = (*mi).second;
1984 printf("cancelling alert %d\n", alert.nID);
1985 mapAlerts.erase(mi++);
1987 else if (!alert.IsInEffect())
1989 printf("expiring alert %d\n", alert.nID);
1990 mapAlerts.erase(mi++);
1996 // Check if this alert has been cancelled
1997 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1999 const CAlert& alert = item.second;
2000 if (alert.Cancels(*this))
2002 printf("alert already cancelled by %d\n", alert.nID);
2008 mapAlerts.insert(make_pair(GetHash(), *this));
2011 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2023 //////////////////////////////////////////////////////////////////////////////
2029 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2033 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2034 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2036 // Don't know what it is, just say we already got one
2043 // The message start string is designed to be unlikely to occur in normal data.
2044 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2045 // a large 4-byte int at any alignment.
2046 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2049 bool ProcessMessages(CNode* pfrom)
2051 CDataStream& vRecv = pfrom->vRecv;
2055 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2059 // (4) message start
2068 // Scan for message start
2069 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2070 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2071 if (vRecv.end() - pstart < nHeaderSize)
2073 if (vRecv.size() > nHeaderSize)
2075 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2076 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2080 if (pstart - vRecv.begin() > 0)
2081 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2082 vRecv.erase(vRecv.begin(), pstart);
2085 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2090 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2093 string strCommand = hdr.GetCommand();
2096 unsigned int nMessageSize = hdr.nMessageSize;
2097 if (nMessageSize > MAX_SIZE)
2099 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2102 if (nMessageSize > vRecv.size())
2104 // Rewind and wait for rest of message
2105 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2110 if (vRecv.GetVersion() >= 209)
2112 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2113 unsigned int nChecksum = 0;
2114 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2115 if (nChecksum != hdr.nChecksum)
2117 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2118 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2123 // Copy message to its own buffer
2124 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2125 vRecv.ignore(nMessageSize);
2131 CRITICAL_BLOCK(cs_main)
2132 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2136 catch (std::ios_base::failure& e)
2138 if (strstr(e.what(), "end of data"))
2140 // Allow exceptions from underlength message on vRecv
2141 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());
2143 else if (strstr(e.what(), "size too large"))
2145 // Allow exceptions from overlong size
2146 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2150 PrintExceptionContinue(&e, "ProcessMessage()");
2153 catch (std::exception& e) {
2154 PrintExceptionContinue(&e, "ProcessMessage()");
2156 PrintExceptionContinue(NULL, "ProcessMessage()");
2160 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2170 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2172 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2173 RandAddSeedPerfmon();
2175 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2176 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2177 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2179 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2187 if (strCommand == "version")
2189 // Each connection can only send one version message
2190 if (pfrom->nVersion != 0)
2197 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2198 if (pfrom->nVersion == 10300)
2199 pfrom->nVersion = 300;
2200 if (pfrom->nVersion >= 106 && !vRecv.empty())
2201 vRecv >> addrFrom >> nNonce;
2202 if (pfrom->nVersion >= 106 && !vRecv.empty())
2203 vRecv >> pfrom->strSubVer;
2204 if (pfrom->nVersion >= 209 && !vRecv.empty())
2205 vRecv >> pfrom->nStartingHeight;
2207 if (pfrom->nVersion == 0)
2210 // Disconnect if we connected to ourself
2211 if (nNonce == nLocalHostNonce && nNonce > 1)
2213 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2214 pfrom->fDisconnect = true;
2218 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2220 AddTimeData(pfrom->addr.ip, nTime);
2223 if (pfrom->nVersion >= 209)
2224 pfrom->PushMessage("verack");
2225 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2226 if (pfrom->nVersion < 209)
2227 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2229 if (!pfrom->fInbound)
2231 // Advertise our address
2232 if (addrLocalHost.IsRoutable() && !fUseProxy)
2234 CAddress addr(addrLocalHost);
2235 addr.nTime = GetAdjustedTime();
2236 pfrom->PushAddress(addr);
2239 // Get recent addresses
2240 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2242 pfrom->PushMessage("getaddr");
2243 pfrom->fGetAddr = true;
2247 // Ask the first connected node for block updates
2248 static int nAskedForBlocks;
2249 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2252 pfrom->PushGetBlocks(pindexBest, uint256(0));
2256 CRITICAL_BLOCK(cs_mapAlerts)
2257 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2258 item.second.RelayTo(pfrom);
2260 pfrom->fSuccessfullyConnected = true;
2262 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2266 else if (pfrom->nVersion == 0)
2268 // Must have a version message before anything else
2273 else if (strCommand == "verack")
2275 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2279 else if (strCommand == "addr")
2281 vector<CAddress> vAddr;
2284 // Don't want addr from older versions unless seeding
2285 if (pfrom->nVersion < 209)
2287 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2289 if (vAddr.size() > 1000)
2290 return error("message addr size() = %d", vAddr.size());
2292 // Store the new addresses
2293 int64 nNow = GetAdjustedTime();
2294 int64 nSince = nNow - 10 * 60;
2295 foreach(CAddress& addr, vAddr)
2299 // ignore IPv6 for now, since it isn't implemented anyway
2302 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2303 addr.nTime = nNow - 5 * 24 * 60 * 60;
2304 AddAddress(addr, 2 * 60 * 60);
2305 pfrom->AddAddressKnown(addr);
2306 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2308 // Relay to a limited number of other nodes
2309 CRITICAL_BLOCK(cs_vNodes)
2311 // Use deterministic randomness to send to the same nodes for 24 hours
2312 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2313 static uint256 hashSalt;
2315 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2316 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2317 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2318 multimap<uint256, CNode*> mapMix;
2319 foreach(CNode* pnode, vNodes)
2321 if (pnode->nVersion < 31402)
2323 unsigned int nPointer;
2324 memcpy(&nPointer, &pnode, sizeof(nPointer));
2325 uint256 hashKey = hashRand ^ nPointer;
2326 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2327 mapMix.insert(make_pair(hashKey, pnode));
2329 int nRelayNodes = 2;
2330 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2331 ((*mi).second)->PushAddress(addr);
2335 if (vAddr.size() < 1000)
2336 pfrom->fGetAddr = false;
2340 else if (strCommand == "inv")
2344 if (vInv.size() > 50000)
2345 return error("message inv size() = %d", vInv.size());
2348 foreach(const CInv& inv, vInv)
2352 pfrom->AddInventoryKnown(inv);
2354 bool fAlreadyHave = AlreadyHave(txdb, inv);
2355 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2359 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2360 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2362 // Track requests for our stuff
2363 CRITICAL_BLOCK(cs_mapRequestCount)
2365 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2366 if (mi != mapRequestCount.end())
2373 else if (strCommand == "getdata")
2377 if (vInv.size() > 50000)
2378 return error("message getdata size() = %d", vInv.size());
2380 foreach(const CInv& inv, vInv)
2384 printf("received getdata for: %s\n", inv.ToString().c_str());
2386 if (inv.type == MSG_BLOCK)
2388 // Send block from disk
2389 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2390 if (mi != mapBlockIndex.end())
2393 block.ReadFromDisk((*mi).second);
2394 pfrom->PushMessage("block", block);
2396 // Trigger them to send a getblocks request for the next batch of inventory
2397 if (inv.hash == pfrom->hashContinue)
2399 // Bypass PushInventory, this must send even if redundant,
2400 // and we want it right after the last block so they don't
2401 // wait for other stuff first.
2403 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2404 pfrom->PushMessage("inv", vInv);
2405 pfrom->hashContinue = 0;
2409 else if (inv.IsKnownType())
2411 // Send stream from relay memory
2412 CRITICAL_BLOCK(cs_mapRelay)
2414 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2415 if (mi != mapRelay.end())
2416 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2420 // Track requests for our stuff
2421 CRITICAL_BLOCK(cs_mapRequestCount)
2423 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2424 if (mi != mapRequestCount.end())
2431 else if (strCommand == "getblocks")
2433 CBlockLocator locator;
2435 vRecv >> locator >> hashStop;
2437 // Find the last block the caller has in the main chain
2438 CBlockIndex* pindex = locator.GetBlockIndex();
2440 // Send the rest of the chain
2442 pindex = pindex->pnext;
2443 int nLimit = 500 + locator.GetDistanceBack();
2444 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2445 for (; pindex; pindex = pindex->pnext)
2447 if (pindex->GetBlockHash() == hashStop)
2449 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2452 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2455 // When this block is requested, we'll send an inv that'll make them
2456 // getblocks the next batch of inventory.
2457 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2458 pfrom->hashContinue = pindex->GetBlockHash();
2465 else if (strCommand == "getheaders")
2467 CBlockLocator locator;
2469 vRecv >> locator >> hashStop;
2471 CBlockIndex* pindex = NULL;
2472 if (locator.IsNull())
2474 // If locator is null, return the hashStop block
2475 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2476 if (mi == mapBlockIndex.end())
2478 pindex = (*mi).second;
2482 // Find the last block the caller has in the main chain
2483 pindex = locator.GetBlockIndex();
2485 pindex = pindex->pnext;
2488 vector<CBlock> vHeaders;
2489 int nLimit = 2000 + locator.GetDistanceBack();
2490 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2491 for (; pindex; pindex = pindex->pnext)
2493 vHeaders.push_back(pindex->GetBlockHeader());
2494 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2497 pfrom->PushMessage("headers", vHeaders);
2501 else if (strCommand == "tx")
2503 vector<uint256> vWorkQueue;
2504 CDataStream vMsg(vRecv);
2508 CInv inv(MSG_TX, tx.GetHash());
2509 pfrom->AddInventoryKnown(inv);
2511 bool fMissingInputs = false;
2512 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2514 AddToWalletIfMine(tx, NULL);
2515 RelayMessage(inv, vMsg);
2516 mapAlreadyAskedFor.erase(inv);
2517 vWorkQueue.push_back(inv.hash);
2519 // Recursively process any orphan transactions that depended on this one
2520 for (int i = 0; i < vWorkQueue.size(); i++)
2522 uint256 hashPrev = vWorkQueue[i];
2523 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2524 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2527 const CDataStream& vMsg = *((*mi).second);
2529 CDataStream(vMsg) >> tx;
2530 CInv inv(MSG_TX, tx.GetHash());
2532 if (tx.AcceptToMemoryPool(true))
2534 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2535 AddToWalletIfMine(tx, NULL);
2536 RelayMessage(inv, vMsg);
2537 mapAlreadyAskedFor.erase(inv);
2538 vWorkQueue.push_back(inv.hash);
2543 foreach(uint256 hash, vWorkQueue)
2544 EraseOrphanTx(hash);
2546 else if (fMissingInputs)
2548 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2554 else if (strCommand == "block")
2559 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2562 CInv inv(MSG_BLOCK, block.GetHash());
2563 pfrom->AddInventoryKnown(inv);
2565 if (ProcessBlock(pfrom, &block))
2566 mapAlreadyAskedFor.erase(inv);
2570 else if (strCommand == "getaddr")
2572 // Nodes rebroadcast an addr every 24 hours
2573 pfrom->vAddrToSend.clear();
2574 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2575 CRITICAL_BLOCK(cs_mapAddresses)
2577 unsigned int nCount = 0;
2578 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2580 const CAddress& addr = item.second;
2581 if (addr.nTime > nSince)
2584 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2586 const CAddress& addr = item.second;
2587 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2588 pfrom->PushAddress(addr);
2594 else if (strCommand == "checkorder")
2599 if (!GetBoolArg("-allowreceivebyip"))
2601 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2608 /// we have a chance to check the order here
2610 // Keep giving the same key to the same ip until they use it
2611 if (!mapReuseKey.count(pfrom->addr.ip))
2612 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2614 // Send back approval of order and pubkey to use
2615 CScript scriptPubKey;
2616 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2617 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2621 else if (strCommand == "submitorder")
2626 if (!GetBoolArg("-allowreceivebyip"))
2628 pfrom->PushMessage("reply", hashReply, (int)2);
2634 wtxNew.fFromMe = false;
2637 if (!wtxNew.AcceptWalletTransaction())
2639 pfrom->PushMessage("reply", hashReply, (int)1);
2640 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2642 wtxNew.fTimeReceivedIsTxTime = true;
2643 AddToWallet(wtxNew);
2644 wtxNew.RelayWalletTransaction();
2645 mapReuseKey.erase(pfrom->addr.ip);
2647 // Send back confirmation
2648 pfrom->PushMessage("reply", hashReply, (int)0);
2652 else if (strCommand == "reply")
2657 CRequestTracker tracker;
2658 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2660 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2661 if (mi != pfrom->mapRequests.end())
2663 tracker = (*mi).second;
2664 pfrom->mapRequests.erase(mi);
2667 if (!tracker.IsNull())
2668 tracker.fn(tracker.param1, vRecv);
2672 else if (strCommand == "ping")
2677 else if (strCommand == "alert")
2682 if (alert.ProcessAlert())
2685 pfrom->setKnown.insert(alert.GetHash());
2686 CRITICAL_BLOCK(cs_vNodes)
2687 foreach(CNode* pnode, vNodes)
2688 alert.RelayTo(pnode);
2695 // Ignore unknown commands for extensibility
2699 // Update the last seen time for this node's address
2700 if (pfrom->fNetworkNode)
2701 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2702 AddressCurrentlyConnected(pfrom->addr);
2716 bool SendMessages(CNode* pto, bool fSendTrickle)
2718 CRITICAL_BLOCK(cs_main)
2720 // Don't send anything until we get their version message
2721 if (pto->nVersion == 0)
2725 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2726 pto->PushMessage("ping");
2728 // Resend wallet transactions that haven't gotten in a block yet
2729 ResendWalletTransactions();
2731 // Address refresh broadcast
2732 static int64 nLastRebroadcast;
2733 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2735 nLastRebroadcast = GetTime();
2736 CRITICAL_BLOCK(cs_vNodes)
2738 foreach(CNode* pnode, vNodes)
2740 // Periodically clear setAddrKnown to allow refresh broadcasts
2741 pnode->setAddrKnown.clear();
2743 // Rebroadcast our address
2744 if (addrLocalHost.IsRoutable() && !fUseProxy)
2746 CAddress addr(addrLocalHost);
2747 addr.nTime = GetAdjustedTime();
2748 pnode->PushAddress(addr);
2754 // Clear out old addresses periodically so it's not too much work at once
2755 static int64 nLastClear;
2756 if (nLastClear == 0)
2757 nLastClear = GetTime();
2758 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2760 nLastClear = GetTime();
2761 CRITICAL_BLOCK(cs_mapAddresses)
2764 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2765 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2766 mi != mapAddresses.end();)
2768 const CAddress& addr = (*mi).second;
2769 if (addr.nTime < nSince)
2771 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2773 addrdb.EraseAddress(addr);
2774 mapAddresses.erase(mi++);
2788 vector<CAddress> vAddr;
2789 vAddr.reserve(pto->vAddrToSend.size());
2790 foreach(const CAddress& addr, pto->vAddrToSend)
2792 // returns true if wasn't already contained in the set
2793 if (pto->setAddrKnown.insert(addr).second)
2795 vAddr.push_back(addr);
2796 // receiver rejects addr messages larger than 1000
2797 if (vAddr.size() >= 1000)
2799 pto->PushMessage("addr", vAddr);
2804 pto->vAddrToSend.clear();
2806 pto->PushMessage("addr", vAddr);
2811 // Message: inventory
2814 vector<CInv> vInvWait;
2815 CRITICAL_BLOCK(pto->cs_inventory)
2817 vInv.reserve(pto->vInventoryToSend.size());
2818 vInvWait.reserve(pto->vInventoryToSend.size());
2819 foreach(const CInv& inv, pto->vInventoryToSend)
2821 if (pto->setInventoryKnown.count(inv))
2824 // trickle out tx inv to protect privacy
2825 if (inv.type == MSG_TX && !fSendTrickle)
2827 // 1/4 of tx invs blast to all immediately
2828 static uint256 hashSalt;
2830 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2831 uint256 hashRand = inv.hash ^ hashSalt;
2832 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2833 bool fTrickleWait = ((hashRand & 3) != 0);
2835 // always trickle our own transactions
2838 TRY_CRITICAL_BLOCK(cs_mapWallet)
2840 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2841 if (mi != mapWallet.end())
2843 CWalletTx& wtx = (*mi).second;
2845 fTrickleWait = true;
2852 vInvWait.push_back(inv);
2857 // returns true if wasn't already contained in the set
2858 if (pto->setInventoryKnown.insert(inv).second)
2860 vInv.push_back(inv);
2861 if (vInv.size() >= 1000)
2863 pto->PushMessage("inv", vInv);
2868 pto->vInventoryToSend = vInvWait;
2871 pto->PushMessage("inv", vInv);
2877 vector<CInv> vGetData;
2878 int64 nNow = GetTime() * 1000000;
2880 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2882 const CInv& inv = (*pto->mapAskFor.begin()).second;
2883 if (!AlreadyHave(txdb, inv))
2885 printf("sending getdata: %s\n", inv.ToString().c_str());
2886 vGetData.push_back(inv);
2887 if (vGetData.size() >= 1000)
2889 pto->PushMessage("getdata", vGetData);
2893 pto->mapAskFor.erase(pto->mapAskFor.begin());
2895 if (!vGetData.empty())
2896 pto->PushMessage("getdata", vGetData);
2915 //////////////////////////////////////////////////////////////////////////////
2920 void GenerateBitcoins(bool fGenerate)
2922 if (fGenerateBitcoins != fGenerate)
2924 fGenerateBitcoins = fGenerate;
2925 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2928 if (fGenerateBitcoins)
2930 int nProcessors = boost::thread::hardware_concurrency();
2931 printf("%d processors\n", nProcessors);
2932 if (nProcessors < 1)
2934 if (fLimitProcessors && nProcessors > nLimitProcessors)
2935 nProcessors = nLimitProcessors;
2936 int nAddThreads = nProcessors - vnThreadsRunning[3];
2937 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2938 for (int i = 0; i < nAddThreads; i++)
2940 if (!CreateThread(ThreadBitcoinMiner, NULL))
2941 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2947 void ThreadBitcoinMiner(void* parg)
2951 vnThreadsRunning[3]++;
2953 vnThreadsRunning[3]--;
2955 catch (std::exception& e) {
2956 vnThreadsRunning[3]--;
2957 PrintException(&e, "ThreadBitcoinMiner()");
2959 vnThreadsRunning[3]--;
2960 PrintException(NULL, "ThreadBitcoinMiner()");
2962 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
2964 if (vnThreadsRunning[3] == 0)
2966 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2969 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2970 void CallCPUID(int in, int& aret, int& cret)
2974 "mov %2, %%eax; " // in into eax
2976 "mov %%eax, %0;" // eax into a
2977 "mov %%ecx, %1;" // ecx into c
2978 :"=r"(a),"=r"(c) /* output */
2979 :"r"(in) /* input */
2980 :"%eax","%ecx" /* clobbered register */
2986 bool Detect128BitSSE2()
2989 CallCPUID(0, a, nBrand);
2990 bool fIntel = (nBrand == 0x6c65746e); // ntel
2991 bool fAMD = (nBrand == 0x444d4163); // cAMD
2995 unsigned int nStepping : 4;
2996 unsigned int nModel : 4;
2997 unsigned int nFamily : 4;
2998 unsigned int nProcessorType : 2;
2999 unsigned int nUnused : 2;
3000 unsigned int nExtendedModel : 4;
3001 unsigned int nExtendedFamily : 8;
3005 memcpy(&cpu, &a, sizeof(cpu));
3006 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
3007 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
3009 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
3010 // Nehalem = i3/i5/i7 and some Xeon
3011 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
3012 // Intel Core i5 family 6, model 26 or 30
3013 // Intel Core i7 family 6, model 26 or 30
3014 // Intel Core i3 family 6, model 37
3015 // AMD Phenom family 16, model 10
3016 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
3017 (fAMD && nFamily * 10000 + nModel >= 160010));
3019 // AMD reports a lower model number in 64-bit mode
3020 if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
3023 static bool fPrinted;
3027 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
3032 bool Detect128BitSSE2() { return false; }
3035 int FormatHashBlocks(void* pbuffer, unsigned int len)
3037 unsigned char* pdata = (unsigned char*)pbuffer;
3038 unsigned int blocks = 1 + ((len + 8) / 64);
3039 unsigned char* pend = pdata + 64 * blocks;
3040 memset(pdata + len, 0, 64 * blocks - len);
3042 unsigned int bits = len * 8;
3043 pend[-1] = (bits >> 0) & 0xff;
3044 pend[-2] = (bits >> 8) & 0xff;
3045 pend[-3] = (bits >> 16) & 0xff;
3046 pend[-4] = (bits >> 24) & 0xff;
3050 using CryptoPP::ByteReverse;
3052 static const unsigned int pSHA256InitState[8] =
3053 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3055 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3057 memcpy(pstate, pinit, 32);
3058 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3062 // ScanHash scans nonces looking for a hash with at least some zero bits.
3063 // It operates on big endian data. Caller does the byte reversing.
3064 // All input buffers are 16-byte aligned. nNonce is usually preserved
3065 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3066 // the block is rebuilt and nNonce starts over at zero.
3068 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3070 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3074 // Hash pdata using pmidstate as the starting state into
3075 // preformatted buffer phash1, then hash phash1 into phash
3077 SHA256Transform(phash1, pdata, pmidstate);
3078 SHA256Transform(phash, phash1, pSHA256InitState);
3080 // Return the nonce if the hash has at least some zero bits,
3081 // caller will check if it has enough to reach the target
3082 if (((unsigned short*)phash)[14] == 0)
3085 // If nothing found after trying for a while, return -1
3086 if ((nNonce & 0xffff) == 0)
3088 nHashesDone = 0xffff+1;
3094 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
3102 set<uint256> setDependsOn;
3105 COrphan(CTransaction* ptxIn)
3113 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3114 foreach(uint256 hash, setDependsOn)
3115 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3120 CBlock* CreateNewBlock(CReserveKey& reservekey)
3122 CBlockIndex* pindexPrev = pindexBest;
3125 auto_ptr<CBlock> pblock(new CBlock());
3129 // Create coinbase tx
3131 txNew.vin.resize(1);
3132 txNew.vin[0].prevout.SetNull();
3133 txNew.vout.resize(1);
3134 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3136 // Add our coinbase tx as first transaction
3137 pblock->vtx.push_back(txNew);
3139 // Collect memory pool transactions into the block
3141 CRITICAL_BLOCK(cs_main)
3142 CRITICAL_BLOCK(cs_mapTransactions)
3146 // Priority order to process transactions
3147 list<COrphan> vOrphan; // list memory doesn't move
3148 map<uint256, vector<COrphan*> > mapDependers;
3149 multimap<double, CTransaction*> mapPriority;
3150 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3152 CTransaction& tx = (*mi).second;
3153 if (tx.IsCoinBase() || !tx.IsFinal())
3156 COrphan* porphan = NULL;
3157 double dPriority = 0;
3158 foreach(const CTxIn& txin, tx.vin)
3160 // Read prev transaction
3161 CTransaction txPrev;
3163 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3165 // Has to wait for dependencies
3168 // Use list for automatic deletion
3169 vOrphan.push_back(COrphan(&tx));
3170 porphan = &vOrphan.back();
3172 mapDependers[txin.prevout.hash].push_back(porphan);
3173 porphan->setDependsOn.insert(txin.prevout.hash);
3176 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3178 // Read block header
3181 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
3183 map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());
3184 if (it != mapBlockIndex.end())
3186 CBlockIndex* pindex = (*it).second;
3187 if (pindex->IsInMainChain())
3188 nConf = 1 + nBestHeight - pindex->nHeight;
3192 dPriority += (double)nValueIn * nConf;
3194 if (fDebug && GetBoolArg("-printpriority"))
3195 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3198 // Priority is sum(valuein * age) / txsize
3199 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3202 porphan->dPriority = dPriority;
3204 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3206 if (fDebug && GetBoolArg("-printpriority"))
3208 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3215 // Collect transactions into block
3216 map<uint256, CTxIndex> mapTestPool;
3217 uint64 nBlockSize = 1000;
3218 int nBlockSigOps = 100;
3219 while (!mapPriority.empty())
3221 // Take highest priority transaction off priority queue
3222 double dPriority = -(*mapPriority.begin()).first;
3223 CTransaction& tx = *(*mapPriority.begin()).second;
3224 mapPriority.erase(mapPriority.begin());
3227 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3228 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3230 int nTxSigOps = tx.GetSigOpCount();
3231 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3234 // Transaction fee required depends on block size
3235 bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);
3236 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3238 // Connecting shouldn't fail due to dependency on other memory pool transactions
3239 // because we're already processing them in order of dependency
3240 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3241 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3243 swap(mapTestPool, mapTestPoolTmp);
3246 pblock->vtx.push_back(tx);
3247 nBlockSize += nTxSize;
3248 nBlockSigOps += nTxSigOps;
3250 // Add transactions that depend on this one to the priority queue
3251 uint256 hash = tx.GetHash();
3252 if (mapDependers.count(hash))
3254 foreach(COrphan* porphan, mapDependers[hash])
3256 if (!porphan->setDependsOn.empty())
3258 porphan->setDependsOn.erase(hash);
3259 if (porphan->setDependsOn.empty())
3260 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3266 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3269 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3270 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3271 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3272 pblock->nBits = GetNextWorkRequired(pindexPrev);
3275 return pblock.release();
3279 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3281 // Update nExtraNonce
3282 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3283 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3288 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3289 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3293 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3296 // Prebuild hash buffers
3303 uint256 hashPrevBlock;
3304 uint256 hashMerkleRoot;
3307 unsigned int nNonce;
3310 unsigned char pchPadding0[64];
3312 unsigned char pchPadding1[64];
3315 memset(&tmp, 0, sizeof(tmp));
3317 tmp.block.nVersion = pblock->nVersion;
3318 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3319 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3320 tmp.block.nTime = pblock->nTime;
3321 tmp.block.nBits = pblock->nBits;
3322 tmp.block.nNonce = pblock->nNonce;
3324 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3325 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3327 // Byte swap all the input buffer
3328 for (int i = 0; i < sizeof(tmp)/4; i++)
3329 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3331 // Precalc the first half of the first hash, which stays constant
3332 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3334 memcpy(pdata, &tmp.block, 128);
3335 memcpy(phash1, &tmp.hash1, 64);
3339 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3341 uint256 hash = pblock->GetHash();
3342 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3344 if (hash > hashTarget)
3348 printf("BitcoinMiner:\n");
3349 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3351 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3352 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3355 CRITICAL_BLOCK(cs_main)
3357 if (pblock->hashPrevBlock != hashBestChain)
3358 return error("BitcoinMiner : generated block is stale");
3360 // Remove key from key pool
3361 reservekey.KeepKey();
3363 // Track how many getdata requests this block gets
3364 CRITICAL_BLOCK(cs_mapRequestCount)
3365 mapRequestCount[pblock->GetHash()] = 0;
3367 // Process this block the same as if we had received it from another node
3368 if (!ProcessBlock(NULL, pblock))
3369 return error("BitcoinMiner : ProcessBlock, block not accepted");
3379 printf("BitcoinMiner started\n");
3380 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3381 bool f4WaySSE2 = Detect128BitSSE2();
3382 if (mapArgs.count("-4way"))
3383 f4WaySSE2 = GetBoolArg(mapArgs["-4way"]);
3385 // Each thread has its own key and counter
3386 CReserveKey reservekey;
3387 unsigned int nExtraNonce = 0;
3388 int64 nPrevTime = 0;
3390 while (fGenerateBitcoins)
3392 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3396 while (vNodes.empty() || IsInitialBlockDownload())
3401 if (!fGenerateBitcoins)
3409 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3410 CBlockIndex* pindexPrev = pindexBest;
3412 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3415 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3417 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3421 // Prebuild hash buffers
3423 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3424 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3425 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3427 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3429 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3430 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3436 int64 nStart = GetTime();
3437 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3439 uint256& hash = *alignup<16>(hashbuf);
3442 unsigned int nHashesDone = 0;
3443 unsigned int nNonceFound;
3447 // tcatm's 4-way 128-bit SSE2 SHA-256
3448 nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3452 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3454 // Check if something found
3455 if (nNonceFound != -1)
3457 for (int i = 0; i < sizeof(hash)/4; i++)
3458 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3460 if (hash <= hashTarget)
3463 pblock->nNonce = ByteReverse(nNonceFound);
3464 assert(hash == pblock->GetHash());
3466 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3467 CheckWork(pblock.get(), reservekey);
3468 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3474 static int64 nHashCounter;
3475 if (nHPSTimerStart == 0)
3477 nHPSTimerStart = GetTimeMillis();
3481 nHashCounter += nHashesDone;
3482 if (GetTimeMillis() - nHPSTimerStart > 4000)
3484 static CCriticalSection cs;
3487 if (GetTimeMillis() - nHPSTimerStart > 4000)
3489 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3490 nHPSTimerStart = GetTimeMillis();
3492 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3493 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3494 static int64 nLogTime;
3495 if (GetTime() - nLogTime > 30 * 60)
3497 nLogTime = GetTime();
3498 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3499 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3505 // Check for stop or if block needs to be rebuilt
3508 if (!fGenerateBitcoins)
3510 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3514 if (nBlockNonce >= 0xffff0000)
3516 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3518 if (pindexPrev != pindexBest)
3521 // Update nTime every few seconds
3522 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3523 nBlockTime = ByteReverse(pblock->nTime);
3545 //////////////////////////////////////////////////////////////////////////////
3553 int64 nStart = GetTimeMillis();
3556 CRITICAL_BLOCK(cs_mapWallet)
3558 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3560 CWalletTx* pcoin = &(*it).second;
3561 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3563 nTotal += pcoin->GetCredit();
3567 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3572 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)
3574 setCoinsRet.clear();
3576 // List of values less than target
3577 int64 nLowestLarger = INT64_MAX;
3578 CWalletTx* pcoinLowestLarger = NULL;
3579 vector<pair<int64, CWalletTx*> > vValue;
3580 int64 nTotalLower = 0;
3582 CRITICAL_BLOCK(cs_mapWallet)
3584 vector<CWalletTx*> vCoins;
3585 vCoins.reserve(mapWallet.size());
3586 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3587 vCoins.push_back(&(*it).second);
3588 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3590 foreach(CWalletTx* pcoin, vCoins)
3592 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3595 int nDepth = pcoin->GetDepthInMainChain();
3596 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3599 int64 n = pcoin->GetCredit();
3602 if (n < nTargetValue)
3604 vValue.push_back(make_pair(n, pcoin));
3607 else if (n == nTargetValue)
3609 setCoinsRet.insert(pcoin);
3612 else if (n < nLowestLarger)
3615 pcoinLowestLarger = pcoin;
3620 if (nTotalLower < nTargetValue)
3622 if (pcoinLowestLarger == NULL)
3624 setCoinsRet.insert(pcoinLowestLarger);
3628 // Solve subset sum by stochastic approximation
3629 sort(vValue.rbegin(), vValue.rend());
3630 vector<char> vfIncluded;
3631 vector<char> vfBest(vValue.size(), true);
3632 int64 nBest = nTotalLower;
3634 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3636 vfIncluded.assign(vValue.size(), false);
3638 bool fReachedTarget = false;
3639 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3641 for (int i = 0; i < vValue.size(); i++)
3643 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3645 nTotal += vValue[i].first;
3646 vfIncluded[i] = true;
3647 if (nTotal >= nTargetValue)
3649 fReachedTarget = true;
3653 vfBest = vfIncluded;
3655 nTotal -= vValue[i].first;
3656 vfIncluded[i] = false;
3663 // If the next larger is still closer, return it
3664 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3665 setCoinsRet.insert(pcoinLowestLarger);
3668 for (int i = 0; i < vValue.size(); i++)
3670 setCoinsRet.insert(vValue[i].second);
3673 printf("SelectCoins() best subset: ");
3674 for (int i = 0; i < vValue.size(); i++)
3676 printf("%s ", FormatMoney(vValue[i].first).c_str());
3677 printf("total %s\n", FormatMoney(nBest).c_str());
3683 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3685 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||
3686 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||
3687 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));
3693 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3695 CRITICAL_BLOCK(cs_main)
3697 // txdb must be opened before the mapWallet lock
3699 CRITICAL_BLOCK(cs_mapWallet)
3701 nFeeRet = nTransactionFee;
3705 wtxNew.vout.clear();
3706 wtxNew.fFromMe = true;
3709 int64 nValueOut = nValue;
3710 int64 nTotalValue = nValue + nFeeRet;
3712 // Choose coins to use
3713 set<CWalletTx*> setCoins;
3714 if (!SelectCoins(nTotalValue, setCoins))
3717 foreach(CWalletTx* pcoin, setCoins)
3718 nValueIn += pcoin->GetCredit();
3720 // Fill a vout to the payee
3721 bool fChangeFirst = GetRand(2);
3723 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3725 // Fill a vout back to self with any change
3726 int64 nChange = nValueIn - nTotalValue;
3727 if (nChange >= CENT)
3729 // Note: We use a new key here to keep it from being obvious which side is the change.
3730 // The drawback is that by not reusing a previous key, the change may be lost if a
3731 // backup is restored, if the backup doesn't have the new private key for the change.
3732 // If we reused the old key, it would be possible to add code to look for and
3733 // rediscover unknown transactions that were written with keys of ours to recover
3734 // post-backup change.
3736 // Reserve a new key pair from key pool
3737 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3738 assert(mapKeys.count(vchPubKey));
3740 // Fill a vout to ourself, using same address type as the payment
3741 CScript scriptChange;
3742 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3743 scriptChange.SetBitcoinAddress(vchPubKey);
3745 scriptChange << vchPubKey << OP_CHECKSIG;
3746 wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3749 reservekey.ReturnKey();
3751 // Fill a vout to the payee
3753 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3756 foreach(CWalletTx* pcoin, setCoins)
3757 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3758 if (pcoin->vout[nOut].IsMine())
3759 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3763 foreach(CWalletTx* pcoin, setCoins)
3764 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3765 if (pcoin->vout[nOut].IsMine())
3766 if (!SignSignature(*pcoin, wtxNew, nIn++))
3770 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3771 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3774 // Check that enough fee is included
3775 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3776 int64 nMinFee = wtxNew.GetMinFee();
3777 if (nFeeRet < max(nPayFee, nMinFee))
3779 nFeeRet = max(nPayFee, nMinFee);
3783 // Fill vtxPrev by copying from previous transactions vtxPrev
3784 wtxNew.AddSupportingTransactions(txdb);
3785 wtxNew.fTimeReceivedIsTxTime = true;
3794 // Call after CreateTransaction unless you want to abort
3795 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3797 CRITICAL_BLOCK(cs_main)
3799 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3800 CRITICAL_BLOCK(cs_mapWallet)
3802 // This is only to keep the database open to defeat the auto-flush for the
3803 // duration of this scope. This is the only place where this optimization
3804 // maybe makes sense; please don't do it anywhere else.
3805 CWalletDB walletdb("r");
3807 // Take key pair from key pool so it won't be used again
3808 reservekey.KeepKey();
3810 // Add tx to wallet, because if it has change it's also ours,
3811 // otherwise just for transaction history.
3812 AddToWallet(wtxNew);
3814 // Mark old coins as spent
3815 set<CWalletTx*> setCoins;
3816 foreach(const CTxIn& txin, wtxNew.vin)
3817 setCoins.insert(&mapWallet[txin.prevout.hash]);
3818 foreach(CWalletTx* pcoin, setCoins)
3820 pcoin->fSpent = true;
3821 pcoin->WriteToDisk();
3822 vWalletUpdated.push_back(pcoin->GetHash());
3826 // Track how many getdata requests our transaction gets
3827 CRITICAL_BLOCK(cs_mapRequestCount)
3828 mapRequestCount[wtxNew.GetHash()] = 0;
3831 if (!wtxNew.AcceptToMemoryPool())
3833 // This must not fail. The transaction has already been signed and recorded.
3834 printf("CommitTransaction() : Error: Transaction not valid");
3837 wtxNew.RelayWalletTransaction();
3846 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3848 CRITICAL_BLOCK(cs_main)
3850 CReserveKey reservekey;
3852 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3855 if (nValue + nFeeRequired > GetBalance())
3856 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3858 strError = _("Error: Transaction creation failed ");
3859 printf("SendMoney() : %s", strError.c_str());
3863 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3866 if (!CommitTransaction(wtxNew, reservekey))
3867 return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
3875 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3879 return _("Invalid amount");
3880 if (nValue + nTransactionFee > GetBalance())
3881 return _("Insufficient funds");
3883 // Parse bitcoin address
3884 CScript scriptPubKey;
3885 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3886 return _("Invalid bitcoin address");
3888 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);