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.
5 #include "cryptopp/sha.h"
14 CCriticalSection cs_main;
16 map<uint256, CTransaction> mapTransactions;
17 CCriticalSection cs_mapTransactions;
18 unsigned int nTransactionsUpdated = 0;
19 map<COutPoint, CInPoint> mapNextTx;
21 map<uint256, CBlockIndex*> mapBlockIndex;
22 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
23 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
24 CBlockIndex* pindexGenesisBlock = NULL;
26 CBigNum bnBestChainWork = 0;
27 CBigNum bnBestInvalidWork = 0;
28 uint256 hashBestChain = 0;
29 CBlockIndex* pindexBest = NULL;
30 int64 nTimeBestReceived = 0;
32 map<uint256, CBlock*> mapOrphanBlocks;
33 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
35 map<uint256, CDataStream*> mapOrphanTransactions;
36 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
38 map<uint256, CWalletTx> mapWallet;
39 vector<uint256> vWalletUpdated;
40 CCriticalSection cs_mapWallet;
42 map<vector<unsigned char>, CPrivKey> mapKeys;
43 map<uint160, vector<unsigned char> > mapPubKeys;
44 CCriticalSection cs_mapKeys;
47 map<uint256, int> mapRequestCount;
48 CCriticalSection cs_mapRequestCount;
50 map<string, string> mapAddressBook;
51 CCriticalSection cs_mapAddressBook;
53 vector<unsigned char> vchDefaultKey;
59 int fGenerateBitcoins = false;
60 int64 nTransactionFee = 0;
61 CAddress addrIncoming;
62 int fLimitProcessors = false;
63 int nLimitProcessors = 1;
64 int fMinimizeToTray = true;
65 int fMinimizeOnClose = true;
78 //////////////////////////////////////////////////////////////////////////////
83 bool AddKey(const CKey& key)
85 CRITICAL_BLOCK(cs_mapKeys)
87 mapKeys[key.GetPubKey()] = key.GetPrivKey();
88 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
90 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
93 vector<unsigned char> GenerateNewKey()
99 throw runtime_error("GenerateNewKey() : AddKey failed");
100 return key.GetPubKey();
106 //////////////////////////////////////////////////////////////////////////////
111 bool AddToWallet(const CWalletTx& wtxIn)
113 uint256 hash = wtxIn.GetHash();
114 CRITICAL_BLOCK(cs_mapWallet)
116 // Inserts only if not already there, returns tx inserted or tx found
117 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
118 CWalletTx& wtx = (*ret.first).second;
119 bool fInsertedNew = ret.second;
121 wtx.nTimeReceived = GetAdjustedTime();
123 bool fUpdated = false;
127 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
129 wtx.hashBlock = wtxIn.hashBlock;
132 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
134 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
135 wtx.nIndex = wtxIn.nIndex;
138 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
140 wtx.fFromMe = wtxIn.fFromMe;
143 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
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 BOOST_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 AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false)
179 uint256 hash = tx.GetHash();
180 bool fExisted = mapWallet.count(hash);
181 if (fExisted && !fUpdate) return false;
182 if (fExisted || tx.IsMine() || tx.IsFromMe())
185 // Get merkle branch if transaction was found in a block
187 wtx.SetMerkleBranch(pblock);
188 return AddToWallet(wtx);
193 bool EraseFromWallet(uint256 hash)
195 CRITICAL_BLOCK(cs_mapWallet)
197 if (mapWallet.erase(hash))
198 CWalletDB().EraseTx(hash);
203 void WalletUpdateSpent(const COutPoint& prevout)
205 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
206 // Update the wallet spent flag if it doesn't know due to wallet.dat being
207 // restored from backup or the user making copies of wallet.dat.
208 CRITICAL_BLOCK(cs_mapWallet)
210 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
211 if (mi != mapWallet.end())
213 CWalletTx& wtx = (*mi).second;
214 if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())
216 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
217 wtx.MarkSpent(prevout.n);
219 vWalletUpdated.push_back(prevout.hash);
232 //////////////////////////////////////////////////////////////////////////////
234 // mapOrphanTransactions
237 void AddOrphanTx(const CDataStream& vMsg)
240 CDataStream(vMsg) >> tx;
241 uint256 hash = tx.GetHash();
242 if (mapOrphanTransactions.count(hash))
244 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
245 BOOST_FOREACH(const CTxIn& txin, tx.vin)
246 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
249 void EraseOrphanTx(uint256 hash)
251 if (!mapOrphanTransactions.count(hash))
253 const CDataStream* pvMsg = mapOrphanTransactions[hash];
255 CDataStream(*pvMsg) >> tx;
256 BOOST_FOREACH(const CTxIn& txin, tx.vin)
258 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
259 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
261 if ((*mi).second == pvMsg)
262 mapOrphanTransactionsByPrev.erase(mi++);
268 mapOrphanTransactions.erase(hash);
278 //////////////////////////////////////////////////////////////////////////////
280 // CTransaction and CTxIndex
283 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
286 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
288 if (!ReadFromDisk(txindexRet.pos))
290 if (prevout.n >= vout.size())
298 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
301 return ReadFromDisk(txdb, prevout, txindex);
304 bool CTransaction::ReadFromDisk(COutPoint prevout)
308 return ReadFromDisk(txdb, prevout, txindex);
311 bool CTxIn::IsMine() const
313 CRITICAL_BLOCK(cs_mapWallet)
315 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
316 if (mi != mapWallet.end())
318 const CWalletTx& prev = (*mi).second;
319 if (prevout.n < prev.vout.size())
320 if (prev.vout[prevout.n].IsMine())
327 int64 CTxIn::GetDebit() const
329 CRITICAL_BLOCK(cs_mapWallet)
331 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
332 if (mi != mapWallet.end())
334 const CWalletTx& prev = (*mi).second;
335 if (prevout.n < prev.vout.size())
336 if (prev.vout[prevout.n].IsMine())
337 return prev.vout[prevout.n].nValue;
343 int64 CWalletTx::GetTxTime() const
345 if (!fTimeReceivedIsTxTime && hashBlock != 0)
347 // If we did not receive the transaction directly, we rely on the block's
348 // time to figure out when it happened. We use the median over a range
349 // of blocks to try to filter out inaccurate block times.
350 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
351 if (mi != mapBlockIndex.end())
353 CBlockIndex* pindex = (*mi).second;
355 return pindex->GetMedianTime();
358 return nTimeReceived;
361 int CWalletTx::GetRequestCount() const
363 // Returns -1 if it wasn't being tracked
365 CRITICAL_BLOCK(cs_mapRequestCount)
372 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
373 if (mi != mapRequestCount.end())
374 nRequests = (*mi).second;
379 // Did anyone request this transaction?
380 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
381 if (mi != mapRequestCount.end())
383 nRequests = (*mi).second;
385 // How about the block it's in?
386 if (nRequests == 0 && hashBlock != 0)
388 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
389 if (mi != mapRequestCount.end())
390 nRequests = (*mi).second;
392 nRequests = 1; // If it's in someone else's block it must have got out
400 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
401 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
403 nGeneratedImmature = nGeneratedMature = nFee = 0;
404 listReceived.clear();
406 strSentAccount = strFromAccount;
410 if (GetBlocksToMaturity() > 0)
411 nGeneratedImmature = CTransaction::GetCredit();
413 nGeneratedMature = GetCredit();
418 int64 nDebit = GetDebit();
419 if (nDebit > 0) // debit>0 means we signed/sent this transaction
421 int64 nValueOut = GetValueOut();
422 nFee = nDebit - nValueOut;
425 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
426 // but non-standard clients might (so return a list of address/amount pairs)
427 BOOST_FOREACH(const CTxOut& txout, vout)
431 vector<unsigned char> vchPubKey;
432 if (ExtractHash160(txout.scriptPubKey, hash160))
433 address = Hash160ToAddress(hash160);
434 else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))
435 address = PubKeyToAddress(vchPubKey);
438 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
439 this->GetHash().ToString().c_str());
440 address = " unknown ";
443 // Don't report 'change' txouts
444 if (nDebit > 0 && txout.IsChange())
448 listSent.push_back(make_pair(address, txout.nValue));
451 listReceived.push_back(make_pair(address, txout.nValue));
456 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
457 int64& nSent, int64& nFee) const
459 nGenerated = nReceived = nSent = nFee = 0;
461 int64 allGeneratedImmature, allGeneratedMature, allFee;
462 allGeneratedImmature = allGeneratedMature = allFee = 0;
463 string strSentAccount;
464 list<pair<string, int64> > listReceived;
465 list<pair<string, int64> > listSent;
466 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
468 if (strAccount == "")
469 nGenerated = allGeneratedMature;
470 if (strAccount == strSentAccount)
472 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
476 CRITICAL_BLOCK(cs_mapAddressBook)
478 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
480 if (mapAddressBook.count(r.first))
482 if (mapAddressBook[r.first] == strAccount)
484 nReceived += r.second;
487 else if (strAccount.empty())
489 nReceived += r.second;
497 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
509 // Load the block this tx is in
511 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
513 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
518 // Update the tx's hashBlock
519 hashBlock = pblock->GetHash();
521 // Locate the transaction
522 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
523 if (pblock->vtx[nIndex] == *(CTransaction*)this)
525 if (nIndex == pblock->vtx.size())
527 vMerkleBranch.clear();
529 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
533 // Fill in merkle branch
534 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
537 // Is the tx in a block that's in the main chain
538 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
539 if (mi == mapBlockIndex.end())
541 CBlockIndex* pindex = (*mi).second;
542 if (!pindex || !pindex->IsInMainChain())
545 return pindexBest->nHeight - pindex->nHeight + 1;
550 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
554 const int COPY_DEPTH = 3;
555 if (SetMerkleBranch() < COPY_DEPTH)
557 vector<uint256> vWorkQueue;
558 BOOST_FOREACH(const CTxIn& txin, vin)
559 vWorkQueue.push_back(txin.prevout.hash);
561 // This critsect is OK because txdb is already open
562 CRITICAL_BLOCK(cs_mapWallet)
564 map<uint256, const CMerkleTx*> mapWalletPrev;
565 set<uint256> setAlreadyDone;
566 for (int i = 0; i < vWorkQueue.size(); i++)
568 uint256 hash = vWorkQueue[i];
569 if (setAlreadyDone.count(hash))
571 setAlreadyDone.insert(hash);
574 if (mapWallet.count(hash))
576 tx = mapWallet[hash];
577 BOOST_FOREACH(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
578 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
580 else if (mapWalletPrev.count(hash))
582 tx = *mapWalletPrev[hash];
584 else if (!fClient && txdb.ReadDiskTx(hash, tx))
590 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
594 int nDepth = tx.SetMerkleBranch();
595 vtxPrev.push_back(tx);
597 if (nDepth < COPY_DEPTH)
598 BOOST_FOREACH(const CTxIn& txin, tx.vin)
599 vWorkQueue.push_back(txin.prevout.hash);
604 reverse(vtxPrev.begin(), vtxPrev.end());
617 bool CTransaction::CheckTransaction() const
619 // Basic checks that don't depend on any context
620 if (vin.empty() || vout.empty())
621 return error("CTransaction::CheckTransaction() : vin or vout empty");
624 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
625 return error("CTransaction::CheckTransaction() : size limits failed");
627 // Check for negative or overflow output values
629 BOOST_FOREACH(const CTxOut& txout, vout)
631 if (txout.nValue < 0)
632 return error("CTransaction::CheckTransaction() : txout.nValue negative");
633 if (txout.nValue > MAX_MONEY)
634 return error("CTransaction::CheckTransaction() : txout.nValue too high");
635 nValueOut += txout.nValue;
636 if (!MoneyRange(nValueOut))
637 return error("CTransaction::CheckTransaction() : txout total out of range");
642 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
643 return error("CTransaction::CheckTransaction() : coinbase script size");
647 BOOST_FOREACH(const CTxIn& txin, vin)
648 if (txin.prevout.IsNull())
649 return error("CTransaction::CheckTransaction() : prevout is null");
655 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
658 *pfMissingInputs = false;
660 if (!CheckTransaction())
661 return error("AcceptToMemoryPool() : CheckTransaction failed");
663 // Coinbase is only valid in a block, not as a loose transaction
665 return error("AcceptToMemoryPool() : coinbase as individual tx");
667 // To help v0.1.5 clients who would see it as a negative number
668 if ((int64)nLockTime > INT_MAX)
669 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
672 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
673 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
674 // attacks disallow transactions with more than one SigOp per 34 bytes.
675 // 34 bytes because a TxOut is:
676 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
677 if (GetSigOpCount() > nSize / 34 || nSize < 100)
678 return error("AcceptToMemoryPool() : nonstandard transaction");
680 // Rather not work on nonstandard transactions (unless -testnet)
681 if (!fTestNet && !IsStandard())
682 return error("AcceptToMemoryPool() : nonstandard transaction type");
684 // Do we already have it?
685 uint256 hash = GetHash();
686 CRITICAL_BLOCK(cs_mapTransactions)
687 if (mapTransactions.count(hash))
690 if (txdb.ContainsTx(hash))
693 // Check for conflicts with in-memory transactions
694 CTransaction* ptxOld = NULL;
695 for (int i = 0; i < vin.size(); i++)
697 COutPoint outpoint = vin[i].prevout;
698 if (mapNextTx.count(outpoint))
700 // Disable replacement feature for now
703 // Allow replacing with a newer version of the same transaction
706 ptxOld = mapNextTx[outpoint].ptx;
707 if (ptxOld->IsFinal())
709 if (!IsNewerThan(*ptxOld))
711 for (int i = 0; i < vin.size(); i++)
713 COutPoint outpoint = vin[i].prevout;
714 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
723 // Check against previous transactions
724 map<uint256, CTxIndex> mapUnused;
726 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
729 *pfMissingInputs = true;
730 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
733 // Don't accept it if it can't get into a block
734 if (nFees < GetMinFee(1000, true, true))
735 return error("AcceptToMemoryPool() : not enough fees");
737 // Continuously rate-limit free transactions
738 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
739 // be annoying or make other's transactions take longer to confirm.
740 if (nFees < MIN_RELAY_TX_FEE)
742 static CCriticalSection cs;
743 static double dFreeCount;
744 static int64 nLastTime;
745 int64 nNow = GetTime();
749 // Use an exponentially decaying ~10-minute window:
750 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
752 // -limitfreerelay unit is thousand-bytes-per-minute
753 // At default rate it would take over a month to fill 1GB
754 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())
755 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
757 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
763 // Store transaction in memory
764 CRITICAL_BLOCK(cs_mapTransactions)
768 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
769 ptxOld->RemoveFromMemoryPool();
771 AddToMemoryPoolUnchecked();
774 ///// are we sure this is ok when loading transactions or restoring block txes
775 // If updated, erase old tx from wallet
777 EraseFromWallet(ptxOld->GetHash());
779 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
784 bool CTransaction::AddToMemoryPoolUnchecked()
786 // Add to memory pool without checking anything. Don't call this directly,
787 // call AcceptToMemoryPool to properly check the transaction first.
788 CRITICAL_BLOCK(cs_mapTransactions)
790 uint256 hash = GetHash();
791 mapTransactions[hash] = *this;
792 for (int i = 0; i < vin.size(); i++)
793 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
794 nTransactionsUpdated++;
800 bool CTransaction::RemoveFromMemoryPool()
802 // Remove transaction from memory pool
803 CRITICAL_BLOCK(cs_mapTransactions)
805 BOOST_FOREACH(const CTxIn& txin, vin)
806 mapNextTx.erase(txin.prevout);
807 mapTransactions.erase(GetHash());
808 nTransactionsUpdated++;
818 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
820 if (hashBlock == 0 || nIndex == -1)
823 // Find the block it claims to be in
824 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
825 if (mi == mapBlockIndex.end())
827 CBlockIndex* pindex = (*mi).second;
828 if (!pindex || !pindex->IsInMainChain())
831 // Make sure the merkle branch connects to this block
832 if (!fMerkleVerified)
834 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
836 fMerkleVerified = true;
839 nHeightRet = pindex->nHeight;
840 return pindexBest->nHeight - pindex->nHeight + 1;
844 int CMerkleTx::GetBlocksToMaturity() const
848 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
852 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
856 if (!IsInMainChain() && !ClientConnectInputs())
858 return CTransaction::AcceptToMemoryPool(txdb, false);
862 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
868 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
870 CRITICAL_BLOCK(cs_mapTransactions)
872 // Add previous supporting transactions first
873 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
875 if (!tx.IsCoinBase())
877 uint256 hash = tx.GetHash();
878 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
879 tx.AcceptToMemoryPool(txdb, fCheckInputs);
882 return AcceptToMemoryPool(txdb, fCheckInputs);
887 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
891 CBlockIndex* pindex = pindexStart;
892 CRITICAL_BLOCK(cs_mapWallet)
897 block.ReadFromDisk(pindex, true);
898 BOOST_FOREACH(CTransaction& tx, block.vtx)
900 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
903 pindex = pindex->pnext;
909 void ReacceptWalletTransactions()
913 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
916 vector<CDiskTxPos> vMissingTx;
917 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
919 CWalletTx& wtx = item.second;
920 if (wtx.IsCoinBase() && wtx.IsSpent(0))
924 bool fUpdated = false;
925 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
927 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
928 if (txindex.vSpent.size() != wtx.vout.size())
930 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
933 for (int i = 0; i < txindex.vSpent.size(); i++)
937 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
941 vMissingTx.push_back(txindex.vSpent[i]);
946 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
953 // Reaccept any txes of ours that aren't already in a block
954 if (!wtx.IsCoinBase())
955 wtx.AcceptWalletTransaction(txdb, false);
958 if (!vMissingTx.empty())
960 // TODO: optimize this to scan just part of the block chain?
961 if (ScanForWalletTransactions(pindexGenesisBlock))
962 fRepeat = true; // Found missing transactions: re-do Reaccept.
968 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
970 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
972 if (!tx.IsCoinBase())
974 uint256 hash = tx.GetHash();
975 if (!txdb.ContainsTx(hash))
976 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
981 uint256 hash = GetHash();
982 if (!txdb.ContainsTx(hash))
984 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
985 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
990 void ResendWalletTransactions()
992 // Do this infrequently and randomly to avoid giving away
993 // that these are our transactions.
994 static int64 nNextTime;
995 if (GetTime() < nNextTime)
997 bool fFirst = (nNextTime == 0);
998 nNextTime = GetTime() + GetRand(30 * 60);
1002 // Only do it if there's been a new block since last time
1003 static int64 nLastTime;
1004 if (nTimeBestReceived < nLastTime)
1006 nLastTime = GetTime();
1008 // Rebroadcast any of our txes that aren't in a block yet
1009 printf("ResendWalletTransactions()\n");
1011 CRITICAL_BLOCK(cs_mapWallet)
1013 // Sort them in chronological order
1014 multimap<unsigned int, CWalletTx*> mapSorted;
1015 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1017 CWalletTx& wtx = item.second;
1018 // Don't rebroadcast until it's had plenty of time that
1019 // it should have gotten in already by now.
1020 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1021 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1023 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1025 CWalletTx& wtx = *item.second;
1026 wtx.RelayWalletTransaction(txdb);
1031 int CTxIndex::GetDepthInMainChain() const
1033 // Read block header
1035 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
1037 // Find the block in the index
1038 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
1039 if (mi == mapBlockIndex.end())
1041 CBlockIndex* pindex = (*mi).second;
1042 if (!pindex || !pindex->IsInMainChain())
1044 return 1 + nBestHeight - pindex->nHeight;
1056 //////////////////////////////////////////////////////////////////////////////
1058 // CBlock and CBlockIndex
1061 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1063 if (!fReadTransactions)
1065 *this = pindex->GetBlockHeader();
1068 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1070 if (GetHash() != pindex->GetBlockHash())
1071 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1075 uint256 GetOrphanRoot(const CBlock* pblock)
1077 // Work back to the first block in the orphan chain
1078 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1079 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1080 return pblock->GetHash();
1083 int64 GetBlockValue(int nHeight, int64 nFees)
1085 int64 nSubsidy = 50 * COIN;
1087 // Subsidy is cut in half every 4 years
1088 nSubsidy >>= (nHeight / 210000);
1090 return nSubsidy + nFees;
1093 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1095 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1096 const int64 nTargetSpacing = 10 * 60;
1097 const int64 nInterval = nTargetTimespan / nTargetSpacing;
1100 if (pindexLast == NULL)
1101 return bnProofOfWorkLimit.GetCompact();
1103 // Only change once per interval
1104 if ((pindexLast->nHeight+1) % nInterval != 0)
1105 return pindexLast->nBits;
1107 // Go back by what we want to be 14 days worth of blocks
1108 const CBlockIndex* pindexFirst = pindexLast;
1109 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1110 pindexFirst = pindexFirst->pprev;
1111 assert(pindexFirst);
1113 // Limit adjustment step
1114 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1115 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1116 if (nActualTimespan < nTargetTimespan/4)
1117 nActualTimespan = nTargetTimespan/4;
1118 if (nActualTimespan > nTargetTimespan*4)
1119 nActualTimespan = nTargetTimespan*4;
1123 bnNew.SetCompact(pindexLast->nBits);
1124 bnNew *= nActualTimespan;
1125 bnNew /= nTargetTimespan;
1127 if (bnNew > bnProofOfWorkLimit)
1128 bnNew = bnProofOfWorkLimit;
1131 printf("GetNextWorkRequired RETARGET\n");
1132 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1133 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1134 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1136 return bnNew.GetCompact();
1139 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1142 bnTarget.SetCompact(nBits);
1145 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1146 return error("CheckProofOfWork() : nBits below minimum work");
1148 // Check proof of work matches claimed amount
1149 if (hash > bnTarget.getuint256())
1150 return error("CheckProofOfWork() : hash doesn't match nBits");
1155 bool IsInitialBlockDownload()
1157 if (pindexBest == NULL || (!fTestNet && nBestHeight < 118000))
1159 static int64 nLastUpdate;
1160 static CBlockIndex* pindexLastBest;
1161 if (pindexBest != pindexLastBest)
1163 pindexLastBest = pindexBest;
1164 nLastUpdate = GetTime();
1166 return (GetTime() - nLastUpdate < 10 &&
1167 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1170 void InvalidChainFound(CBlockIndex* pindexNew)
1172 if (pindexNew->bnChainWork > bnBestInvalidWork)
1174 bnBestInvalidWork = pindexNew->bnChainWork;
1175 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1178 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());
1179 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1180 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1181 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1194 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1196 // Relinquish previous transactions' spent pointers
1199 BOOST_FOREACH(const CTxIn& txin, vin)
1201 COutPoint prevout = txin.prevout;
1203 // Get prev txindex from disk
1205 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1206 return error("DisconnectInputs() : ReadTxIndex failed");
1208 if (prevout.n >= txindex.vSpent.size())
1209 return error("DisconnectInputs() : prevout.n out of range");
1211 // Mark outpoint as not spent
1212 txindex.vSpent[prevout.n].SetNull();
1215 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1216 return error("DisconnectInputs() : UpdateTxIndex failed");
1220 // Remove transaction from index
1221 if (!txdb.EraseTxIndex(*this))
1222 return error("DisconnectInputs() : EraseTxPos failed");
1228 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1229 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1231 // Take over previous transactions' spent pointers
1235 for (int i = 0; i < vin.size(); i++)
1237 COutPoint prevout = vin[i].prevout;
1242 if (fMiner && mapTestPool.count(prevout.hash))
1244 // Get txindex from current proposed changes
1245 txindex = mapTestPool[prevout.hash];
1249 // Read txindex from txdb
1250 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1252 if (!fFound && (fBlock || fMiner))
1253 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());
1256 CTransaction txPrev;
1257 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1259 // Get prev tx from single transactions in memory
1260 CRITICAL_BLOCK(cs_mapTransactions)
1262 if (!mapTransactions.count(prevout.hash))
1263 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1264 txPrev = mapTransactions[prevout.hash];
1267 txindex.vSpent.resize(txPrev.vout.size());
1271 // Get prev tx from disk
1272 if (!txPrev.ReadFromDisk(txindex.pos))
1273 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1276 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1277 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());
1279 // If prev is coinbase, check that it's matured
1280 if (txPrev.IsCoinBase())
1281 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1282 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1283 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1286 if (!VerifySignature(txPrev, *this, i))
1287 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1289 // Check for conflicts
1290 if (!txindex.vSpent[prevout.n].IsNull())
1291 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());
1293 // Check for negative or overflow input values
1294 nValueIn += txPrev.vout[prevout.n].nValue;
1295 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1296 return error("ConnectInputs() : txin values out of range");
1298 // Mark outpoints as spent
1299 txindex.vSpent[prevout.n] = posThisTx;
1304 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1305 return error("ConnectInputs() : UpdateTxIndex failed");
1309 mapTestPool[prevout.hash] = txindex;
1313 if (nValueIn < GetValueOut())
1314 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1316 // Tally transaction fees
1317 int64 nTxFee = nValueIn - GetValueOut();
1319 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1320 if (nTxFee < nMinFee)
1323 if (!MoneyRange(nFees))
1324 return error("ConnectInputs() : nFees out of range");
1329 // Add transaction to disk index
1330 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1331 return error("ConnectInputs() : AddTxPos failed");
1335 // Add transaction to test pool
1336 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1343 bool CTransaction::ClientConnectInputs()
1348 // Take over previous transactions' spent pointers
1349 CRITICAL_BLOCK(cs_mapTransactions)
1352 for (int i = 0; i < vin.size(); i++)
1354 // Get prev tx from single transactions in memory
1355 COutPoint prevout = vin[i].prevout;
1356 if (!mapTransactions.count(prevout.hash))
1358 CTransaction& txPrev = mapTransactions[prevout.hash];
1360 if (prevout.n >= txPrev.vout.size())
1364 if (!VerifySignature(txPrev, *this, i))
1365 return error("ConnectInputs() : VerifySignature failed");
1367 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1368 ///// this has to go away now that posNext is gone
1369 // // Check for conflicts
1370 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1371 // return error("ConnectInputs() : prev tx already used");
1373 // // Flag outpoints as used
1374 // txPrev.vout[prevout.n].posNext = posThisTx;
1376 nValueIn += txPrev.vout[prevout.n].nValue;
1378 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1379 return error("ClientConnectInputs() : txin values out of range");
1381 if (GetValueOut() > nValueIn)
1391 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1393 // Disconnect in reverse order
1394 for (int i = vtx.size()-1; i >= 0; i--)
1395 if (!vtx[i].DisconnectInputs(txdb))
1398 // Update block index on disk without changing it in memory.
1399 // The memory index structure will be changed after the db commits.
1402 CDiskBlockIndex blockindexPrev(pindex->pprev);
1403 blockindexPrev.hashNext = 0;
1404 if (!txdb.WriteBlockIndex(blockindexPrev))
1405 return error("DisconnectBlock() : WriteBlockIndex failed");
1411 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1413 // Check it again in case a previous version let a bad block in
1417 //// issue here: it doesn't know the version
1418 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1420 map<uint256, CTxIndex> mapUnused;
1422 BOOST_FOREACH(CTransaction& tx, vtx)
1424 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1425 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1427 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1431 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1434 // Update block index on disk without changing it in memory.
1435 // The memory index structure will be changed after the db commits.
1438 CDiskBlockIndex blockindexPrev(pindex->pprev);
1439 blockindexPrev.hashNext = pindex->GetBlockHash();
1440 if (!txdb.WriteBlockIndex(blockindexPrev))
1441 return error("ConnectBlock() : WriteBlockIndex failed");
1444 // Watch for transactions paying to me
1445 BOOST_FOREACH(CTransaction& tx, vtx)
1446 AddToWalletIfInvolvingMe(tx, this, true);
1451 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1453 printf("REORGANIZE\n");
1456 CBlockIndex* pfork = pindexBest;
1457 CBlockIndex* plonger = pindexNew;
1458 while (pfork != plonger)
1460 while (plonger->nHeight > pfork->nHeight)
1461 if (!(plonger = plonger->pprev))
1462 return error("Reorganize() : plonger->pprev is null");
1463 if (pfork == plonger)
1465 if (!(pfork = pfork->pprev))
1466 return error("Reorganize() : pfork->pprev is null");
1469 // List of what to disconnect
1470 vector<CBlockIndex*> vDisconnect;
1471 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1472 vDisconnect.push_back(pindex);
1474 // List of what to connect
1475 vector<CBlockIndex*> vConnect;
1476 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1477 vConnect.push_back(pindex);
1478 reverse(vConnect.begin(), vConnect.end());
1480 // Disconnect shorter branch
1481 vector<CTransaction> vResurrect;
1482 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1485 if (!block.ReadFromDisk(pindex))
1486 return error("Reorganize() : ReadFromDisk for disconnect failed");
1487 if (!block.DisconnectBlock(txdb, pindex))
1488 return error("Reorganize() : DisconnectBlock failed");
1490 // Queue memory transactions to resurrect
1491 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1492 if (!tx.IsCoinBase())
1493 vResurrect.push_back(tx);
1496 // Connect longer branch
1497 vector<CTransaction> vDelete;
1498 for (int i = 0; i < vConnect.size(); i++)
1500 CBlockIndex* pindex = vConnect[i];
1502 if (!block.ReadFromDisk(pindex))
1503 return error("Reorganize() : ReadFromDisk for connect failed");
1504 if (!block.ConnectBlock(txdb, pindex))
1508 return error("Reorganize() : ConnectBlock failed");
1511 // Queue memory transactions to delete
1512 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1513 vDelete.push_back(tx);
1515 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1516 return error("Reorganize() : WriteHashBestChain failed");
1518 // Make sure it's successfully written to disk before changing memory structure
1519 if (!txdb.TxnCommit())
1520 return error("Reorganize() : TxnCommit failed");
1522 // Disconnect shorter branch
1523 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1525 pindex->pprev->pnext = NULL;
1527 // Connect longer branch
1528 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1530 pindex->pprev->pnext = pindex;
1532 // Resurrect memory transactions that were in the disconnected branch
1533 BOOST_FOREACH(CTransaction& tx, vResurrect)
1534 tx.AcceptToMemoryPool(txdb, false);
1536 // Delete redundant memory transactions that are in the connected branch
1537 BOOST_FOREACH(CTransaction& tx, vDelete)
1538 tx.RemoveFromMemoryPool();
1544 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1546 uint256 hash = GetHash();
1549 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1551 txdb.WriteHashBestChain(hash);
1552 if (!txdb.TxnCommit())
1553 return error("SetBestChain() : TxnCommit failed");
1554 pindexGenesisBlock = pindexNew;
1556 else if (hashPrevBlock == hashBestChain)
1558 // Adding to current best branch
1559 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1562 InvalidChainFound(pindexNew);
1563 return error("SetBestChain() : ConnectBlock failed");
1565 if (!txdb.TxnCommit())
1566 return error("SetBestChain() : TxnCommit failed");
1568 // Add to current best branch
1569 pindexNew->pprev->pnext = pindexNew;
1571 // Delete redundant memory transactions
1572 BOOST_FOREACH(CTransaction& tx, vtx)
1573 tx.RemoveFromMemoryPool();
1578 if (!Reorganize(txdb, pindexNew))
1581 InvalidChainFound(pindexNew);
1582 return error("SetBestChain() : Reorganize failed");
1586 // Update best block in wallet (so we can detect restored wallets)
1587 if (!IsInitialBlockDownload())
1590 const CBlockLocator locator(pindexNew);
1591 if (!walletdb.WriteBestBlock(locator))
1592 return error("SetBestChain() : WriteWalletBest failed");
1596 hashBestChain = hash;
1597 pindexBest = pindexNew;
1598 nBestHeight = pindexBest->nHeight;
1599 bnBestChainWork = pindexNew->bnChainWork;
1600 nTimeBestReceived = GetTime();
1601 nTransactionsUpdated++;
1602 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1608 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1610 // Check for duplicate
1611 uint256 hash = GetHash();
1612 if (mapBlockIndex.count(hash))
1613 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1615 // Construct new block index object
1616 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1618 return error("AddToBlockIndex() : new CBlockIndex failed");
1619 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1620 pindexNew->phashBlock = &((*mi).first);
1621 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1622 if (miPrev != mapBlockIndex.end())
1624 pindexNew->pprev = (*miPrev).second;
1625 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1627 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1631 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1632 if (!txdb.TxnCommit())
1636 if (pindexNew->bnChainWork > bnBestChainWork)
1637 if (!SetBestChain(txdb, pindexNew))
1642 if (pindexNew == pindexBest)
1644 // Notify UI to display prev block's coinbase if it was ours
1645 static uint256 hashPrevBestCoinBase;
1646 CRITICAL_BLOCK(cs_mapWallet)
1647 vWalletUpdated.push_back(hashPrevBestCoinBase);
1648 hashPrevBestCoinBase = vtx[0].GetHash();
1658 bool CBlock::CheckBlock() const
1660 // These are checks that are independent of context
1661 // that can be verified before saving an orphan block.
1664 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1665 return error("CheckBlock() : size limits failed");
1667 // Check proof of work matches claimed amount
1668 if (!CheckProofOfWork(GetHash(), nBits))
1669 return error("CheckBlock() : proof of work failed");
1672 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1673 return error("CheckBlock() : block timestamp too far in the future");
1675 // First transaction must be coinbase, the rest must not be
1676 if (vtx.empty() || !vtx[0].IsCoinBase())
1677 return error("CheckBlock() : first tx is not coinbase");
1678 for (int i = 1; i < vtx.size(); i++)
1679 if (vtx[i].IsCoinBase())
1680 return error("CheckBlock() : more than one coinbase");
1682 // Check transactions
1683 BOOST_FOREACH(const CTransaction& tx, vtx)
1684 if (!tx.CheckTransaction())
1685 return error("CheckBlock() : CheckTransaction failed");
1687 // Check that it's not full of nonstandard transactions
1688 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1689 return error("CheckBlock() : too many nonstandard transactions");
1692 if (hashMerkleRoot != BuildMerkleTree())
1693 return error("CheckBlock() : hashMerkleRoot mismatch");
1698 bool CBlock::AcceptBlock()
1700 // Check for duplicate
1701 uint256 hash = GetHash();
1702 if (mapBlockIndex.count(hash))
1703 return error("AcceptBlock() : block already in mapBlockIndex");
1705 // Get prev block index
1706 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1707 if (mi == mapBlockIndex.end())
1708 return error("AcceptBlock() : prev block not found");
1709 CBlockIndex* pindexPrev = (*mi).second;
1710 int nHeight = pindexPrev->nHeight+1;
1712 // Check proof of work
1713 if (nBits != GetNextWorkRequired(pindexPrev))
1714 return error("AcceptBlock() : incorrect proof of work");
1716 // Check timestamp against prev
1717 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1718 return error("AcceptBlock() : block's timestamp is too early");
1720 // Check that all transactions are finalized
1721 BOOST_FOREACH(const CTransaction& tx, vtx)
1722 if (!tx.IsFinal(nHeight, GetBlockTime()))
1723 return error("AcceptBlock() : contains a non-final transaction");
1725 // Check that the block chain matches the known block chain up to a checkpoint
1727 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1728 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1729 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1730 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1731 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1732 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1733 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))
1734 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1736 // Write block to history file
1737 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1738 return error("AcceptBlock() : out of disk space");
1739 unsigned int nFile = -1;
1740 unsigned int nBlockPos = 0;
1741 if (!WriteToDisk(nFile, nBlockPos))
1742 return error("AcceptBlock() : WriteToDisk failed");
1743 if (!AddToBlockIndex(nFile, nBlockPos))
1744 return error("AcceptBlock() : AddToBlockIndex failed");
1746 // Relay inventory, but don't relay old inventory during initial block download
1747 if (hashBestChain == hash)
1748 CRITICAL_BLOCK(cs_vNodes)
1749 BOOST_FOREACH(CNode* pnode, vNodes)
1750 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
1751 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1756 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1758 // Check for duplicate
1759 uint256 hash = pblock->GetHash();
1760 if (mapBlockIndex.count(hash))
1761 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1762 if (mapOrphanBlocks.count(hash))
1763 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1765 // Preliminary checks
1766 if (!pblock->CheckBlock())
1767 return error("ProcessBlock() : CheckBlock FAILED");
1769 // If don't already have its previous block, shunt it off to holding area until we get it
1770 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1772 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1773 CBlock* pblock2 = new CBlock(*pblock);
1774 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1775 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1777 // Ask this guy to fill in what we're missing
1779 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1784 if (!pblock->AcceptBlock())
1785 return error("ProcessBlock() : AcceptBlock FAILED");
1787 // Recursively process any orphan blocks that depended on this one
1788 vector<uint256> vWorkQueue;
1789 vWorkQueue.push_back(hash);
1790 for (int i = 0; i < vWorkQueue.size(); i++)
1792 uint256 hashPrev = vWorkQueue[i];
1793 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1794 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1797 CBlock* pblockOrphan = (*mi).second;
1798 if (pblockOrphan->AcceptBlock())
1799 vWorkQueue.push_back(pblockOrphan->GetHash());
1800 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1801 delete pblockOrphan;
1803 mapOrphanBlocksByPrev.erase(hashPrev);
1806 printf("ProcessBlock: ACCEPTED\n");
1817 template<typename Stream>
1818 bool ScanMessageStart(Stream& s)
1820 // Scan ahead to the next pchMessageStart, which should normally be immediately
1821 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1823 short prevmask = s.exceptions(0);
1824 const char* p = BEGIN(pchMessageStart);
1834 s.exceptions(prevmask);
1838 p = BEGIN(pchMessageStart);
1841 if (++p == END(pchMessageStart))
1844 s.exceptions(prevmask);
1853 s.exceptions(prevmask);
1858 bool CheckDiskSpace(uint64 nAdditionalBytes)
1860 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1862 // Check for 15MB because database could create another 10MB log file at any time
1863 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1866 string strMessage = _("Warning: Disk space is low ");
1867 strMiscWarning = strMessage;
1868 printf("*** %s\n", strMessage.c_str());
1869 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1870 CreateThread(Shutdown, NULL);
1876 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1880 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1883 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1885 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1894 static unsigned int nCurrentBlockFile = 1;
1896 FILE* AppendBlockFile(unsigned int& nFileRet)
1901 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1904 if (fseek(file, 0, SEEK_END) != 0)
1906 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1907 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1909 nFileRet = nCurrentBlockFile;
1913 nCurrentBlockFile++;
1917 bool LoadBlockIndex(bool fAllowNew)
1921 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1922 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1923 pchMessageStart[0] = 0xfa;
1924 pchMessageStart[1] = 0xbf;
1925 pchMessageStart[2] = 0xb5;
1926 pchMessageStart[3] = 0xda;
1933 if (!txdb.LoadBlockIndex())
1938 // Init with genesis block
1940 if (mapBlockIndex.empty())
1946 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1947 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1948 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1949 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1950 // vMerkleTree: 4a5e1e
1953 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1955 txNew.vin.resize(1);
1956 txNew.vout.resize(1);
1957 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1958 txNew.vout[0].nValue = 50 * COIN;
1959 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1961 block.vtx.push_back(txNew);
1962 block.hashPrevBlock = 0;
1963 block.hashMerkleRoot = block.BuildMerkleTree();
1965 block.nTime = 1231006505;
1966 block.nBits = 0x1d00ffff;
1967 block.nNonce = 2083236893;
1971 block.nTime = 1296688602;
1972 block.nBits = 0x1d07fff8;
1973 block.nNonce = 384568319;
1977 printf("%s\n", block.GetHash().ToString().c_str());
1978 printf("%s\n", hashGenesisBlock.ToString().c_str());
1979 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1980 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1982 assert(block.GetHash() == hashGenesisBlock);
1984 // Start new block file
1986 unsigned int nBlockPos;
1987 if (!block.WriteToDisk(nFile, nBlockPos))
1988 return error("LoadBlockIndex() : writing genesis block to disk failed");
1989 if (!block.AddToBlockIndex(nFile, nBlockPos))
1990 return error("LoadBlockIndex() : genesis block not accepted");
1998 void PrintBlockTree()
2000 // precompute tree structure
2001 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2002 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2004 CBlockIndex* pindex = (*mi).second;
2005 mapNext[pindex->pprev].push_back(pindex);
2007 //while (rand() % 3 == 0)
2008 // mapNext[pindex->pprev].push_back(pindex);
2011 vector<pair<int, CBlockIndex*> > vStack;
2012 vStack.push_back(make_pair(0, pindexGenesisBlock));
2015 while (!vStack.empty())
2017 int nCol = vStack.back().first;
2018 CBlockIndex* pindex = vStack.back().second;
2021 // print split or gap
2022 if (nCol > nPrevCol)
2024 for (int i = 0; i < nCol-1; i++)
2028 else if (nCol < nPrevCol)
2030 for (int i = 0; i < nCol; i++)
2037 for (int i = 0; i < nCol; i++)
2042 block.ReadFromDisk(pindex);
2043 printf("%d (%u,%u) %s %s tx %d",
2047 block.GetHash().ToString().substr(0,20).c_str(),
2048 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2051 CRITICAL_BLOCK(cs_mapWallet)
2053 if (mapWallet.count(block.vtx[0].GetHash()))
2055 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2056 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2062 // put the main timechain first
2063 vector<CBlockIndex*>& vNext = mapNext[pindex];
2064 for (int i = 0; i < vNext.size(); i++)
2066 if (vNext[i]->pnext)
2068 swap(vNext[0], vNext[i]);
2074 for (int i = 0; i < vNext.size(); i++)
2075 vStack.push_back(make_pair(nCol+i, vNext[i]));
2088 //////////////////////////////////////////////////////////////////////////////
2093 map<uint256, CAlert> mapAlerts;
2094 CCriticalSection cs_mapAlerts;
2096 string GetWarnings(string strFor)
2099 string strStatusBar;
2101 if (GetBoolArg("-testsafemode"))
2104 // Misc warnings like out of disk space and clock is wrong
2105 if (strMiscWarning != "")
2108 strStatusBar = strMiscWarning;
2111 // Longer invalid proof-of-work chain
2112 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2115 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2119 CRITICAL_BLOCK(cs_mapAlerts)
2121 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2123 const CAlert& alert = item.second;
2124 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2126 nPriority = alert.nPriority;
2127 strStatusBar = alert.strStatusBar;
2132 if (strFor == "statusbar")
2133 return strStatusBar;
2134 else if (strFor == "rpc")
2136 assert(("GetWarnings() : invalid parameter", false));
2140 bool CAlert::ProcessAlert()
2142 if (!CheckSignature())
2147 CRITICAL_BLOCK(cs_mapAlerts)
2149 // Cancel previous alerts
2150 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2152 const CAlert& alert = (*mi).second;
2155 printf("cancelling alert %d\n", alert.nID);
2156 mapAlerts.erase(mi++);
2158 else if (!alert.IsInEffect())
2160 printf("expiring alert %d\n", alert.nID);
2161 mapAlerts.erase(mi++);
2167 // Check if this alert has been cancelled
2168 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2170 const CAlert& alert = item.second;
2171 if (alert.Cancels(*this))
2173 printf("alert already cancelled by %d\n", alert.nID);
2179 mapAlerts.insert(make_pair(GetHash(), *this));
2182 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2194 //////////////////////////////////////////////////////////////////////////////
2200 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2204 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2205 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2207 // Don't know what it is, just say we already got one
2214 // The message start string is designed to be unlikely to occur in normal data.
2215 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2216 // a large 4-byte int at any alignment.
2217 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2220 bool ProcessMessages(CNode* pfrom)
2222 CDataStream& vRecv = pfrom->vRecv;
2226 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2230 // (4) message start
2239 // Scan for message start
2240 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2241 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2242 if (vRecv.end() - pstart < nHeaderSize)
2244 if (vRecv.size() > nHeaderSize)
2246 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2247 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2251 if (pstart - vRecv.begin() > 0)
2252 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2253 vRecv.erase(vRecv.begin(), pstart);
2256 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2261 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2264 string strCommand = hdr.GetCommand();
2267 unsigned int nMessageSize = hdr.nMessageSize;
2268 if (nMessageSize > MAX_SIZE)
2270 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2273 if (nMessageSize > vRecv.size())
2275 // Rewind and wait for rest of message
2276 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2281 if (vRecv.GetVersion() >= 209)
2283 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2284 unsigned int nChecksum = 0;
2285 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2286 if (nChecksum != hdr.nChecksum)
2288 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2289 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2294 // Copy message to its own buffer
2295 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2296 vRecv.ignore(nMessageSize);
2302 CRITICAL_BLOCK(cs_main)
2303 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2307 catch (std::ios_base::failure& e)
2309 if (strstr(e.what(), "end of data"))
2311 // Allow exceptions from underlength message on vRecv
2312 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());
2314 else if (strstr(e.what(), "size too large"))
2316 // Allow exceptions from overlong size
2317 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2321 PrintExceptionContinue(&e, "ProcessMessage()");
2324 catch (std::exception& e) {
2325 PrintExceptionContinue(&e, "ProcessMessage()");
2327 PrintExceptionContinue(NULL, "ProcessMessage()");
2331 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2341 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2343 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2344 RandAddSeedPerfmon();
2346 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2347 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2348 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2350 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2358 if (strCommand == "version")
2360 // Each connection can only send one version message
2361 if (pfrom->nVersion != 0)
2368 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2369 if (pfrom->nVersion == 10300)
2370 pfrom->nVersion = 300;
2371 if (pfrom->nVersion >= 106 && !vRecv.empty())
2372 vRecv >> addrFrom >> nNonce;
2373 if (pfrom->nVersion >= 106 && !vRecv.empty())
2374 vRecv >> pfrom->strSubVer;
2375 if (pfrom->nVersion >= 209 && !vRecv.empty())
2376 vRecv >> pfrom->nStartingHeight;
2378 if (pfrom->nVersion == 0)
2381 // Disconnect if we connected to ourself
2382 if (nNonce == nLocalHostNonce && nNonce > 1)
2384 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2385 pfrom->fDisconnect = true;
2389 // Be shy and don't send version until we hear
2390 if (pfrom->fInbound)
2391 pfrom->PushVersion();
2393 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2395 AddTimeData(pfrom->addr.ip, nTime);
2398 if (pfrom->nVersion >= 209)
2399 pfrom->PushMessage("verack");
2400 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2401 if (pfrom->nVersion < 209)
2402 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2404 if (!pfrom->fInbound)
2406 // Advertise our address
2407 if (addrLocalHost.IsRoutable() && !fUseProxy)
2409 CAddress addr(addrLocalHost);
2410 addr.nTime = GetAdjustedTime();
2411 pfrom->PushAddress(addr);
2414 // Get recent addresses
2415 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2417 pfrom->PushMessage("getaddr");
2418 pfrom->fGetAddr = true;
2422 // Ask the first connected node for block updates
2423 static int nAskedForBlocks;
2424 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2427 pfrom->PushGetBlocks(pindexBest, uint256(0));
2431 CRITICAL_BLOCK(cs_mapAlerts)
2432 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2433 item.second.RelayTo(pfrom);
2435 pfrom->fSuccessfullyConnected = true;
2437 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2441 else if (pfrom->nVersion == 0)
2443 // Must have a version message before anything else
2448 else if (strCommand == "verack")
2450 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2454 else if (strCommand == "addr")
2456 vector<CAddress> vAddr;
2459 // Don't want addr from older versions unless seeding
2460 if (pfrom->nVersion < 209)
2462 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2464 if (vAddr.size() > 1000)
2465 return error("message addr size() = %d", vAddr.size());
2467 // Store the new addresses
2468 int64 nNow = GetAdjustedTime();
2469 int64 nSince = nNow - 10 * 60;
2470 BOOST_FOREACH(CAddress& addr, vAddr)
2474 // ignore IPv6 for now, since it isn't implemented anyway
2477 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2478 addr.nTime = nNow - 5 * 24 * 60 * 60;
2479 AddAddress(addr, 2 * 60 * 60);
2480 pfrom->AddAddressKnown(addr);
2481 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2483 // Relay to a limited number of other nodes
2484 CRITICAL_BLOCK(cs_vNodes)
2486 // Use deterministic randomness to send to the same nodes for 24 hours
2487 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2488 static uint256 hashSalt;
2490 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2491 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2492 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2493 multimap<uint256, CNode*> mapMix;
2494 BOOST_FOREACH(CNode* pnode, vNodes)
2496 if (pnode->nVersion < 31402)
2498 unsigned int nPointer;
2499 memcpy(&nPointer, &pnode, sizeof(nPointer));
2500 uint256 hashKey = hashRand ^ nPointer;
2501 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2502 mapMix.insert(make_pair(hashKey, pnode));
2504 int nRelayNodes = 2;
2505 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2506 ((*mi).second)->PushAddress(addr);
2510 if (vAddr.size() < 1000)
2511 pfrom->fGetAddr = false;
2515 else if (strCommand == "inv")
2519 if (vInv.size() > 50000)
2520 return error("message inv size() = %d", vInv.size());
2523 BOOST_FOREACH(const CInv& inv, vInv)
2527 pfrom->AddInventoryKnown(inv);
2529 bool fAlreadyHave = AlreadyHave(txdb, inv);
2530 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2534 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2535 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2537 // Track requests for our stuff
2538 CRITICAL_BLOCK(cs_mapRequestCount)
2540 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2541 if (mi != mapRequestCount.end())
2548 else if (strCommand == "getdata")
2552 if (vInv.size() > 50000)
2553 return error("message getdata size() = %d", vInv.size());
2555 BOOST_FOREACH(const CInv& inv, vInv)
2559 printf("received getdata for: %s\n", inv.ToString().c_str());
2561 if (inv.type == MSG_BLOCK)
2563 // Send block from disk
2564 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2565 if (mi != mapBlockIndex.end())
2568 block.ReadFromDisk((*mi).second);
2569 pfrom->PushMessage("block", block);
2571 // Trigger them to send a getblocks request for the next batch of inventory
2572 if (inv.hash == pfrom->hashContinue)
2574 // Bypass PushInventory, this must send even if redundant,
2575 // and we want it right after the last block so they don't
2576 // wait for other stuff first.
2578 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2579 pfrom->PushMessage("inv", vInv);
2580 pfrom->hashContinue = 0;
2584 else if (inv.IsKnownType())
2586 // Send stream from relay memory
2587 CRITICAL_BLOCK(cs_mapRelay)
2589 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2590 if (mi != mapRelay.end())
2591 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2595 // Track requests for our stuff
2596 CRITICAL_BLOCK(cs_mapRequestCount)
2598 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2599 if (mi != mapRequestCount.end())
2606 else if (strCommand == "getblocks")
2608 CBlockLocator locator;
2610 vRecv >> locator >> hashStop;
2612 // Find the last block the caller has in the main chain
2613 CBlockIndex* pindex = locator.GetBlockIndex();
2615 // Send the rest of the chain
2617 pindex = pindex->pnext;
2618 int nLimit = 500 + locator.GetDistanceBack();
2619 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2620 for (; pindex; pindex = pindex->pnext)
2622 if (pindex->GetBlockHash() == hashStop)
2624 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2627 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2630 // When this block is requested, we'll send an inv that'll make them
2631 // getblocks the next batch of inventory.
2632 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2633 pfrom->hashContinue = pindex->GetBlockHash();
2640 else if (strCommand == "getheaders")
2642 CBlockLocator locator;
2644 vRecv >> locator >> hashStop;
2646 CBlockIndex* pindex = NULL;
2647 if (locator.IsNull())
2649 // If locator is null, return the hashStop block
2650 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2651 if (mi == mapBlockIndex.end())
2653 pindex = (*mi).second;
2657 // Find the last block the caller has in the main chain
2658 pindex = locator.GetBlockIndex();
2660 pindex = pindex->pnext;
2663 vector<CBlock> vHeaders;
2664 int nLimit = 2000 + locator.GetDistanceBack();
2665 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2666 for (; pindex; pindex = pindex->pnext)
2668 vHeaders.push_back(pindex->GetBlockHeader());
2669 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2672 pfrom->PushMessage("headers", vHeaders);
2676 else if (strCommand == "tx")
2678 vector<uint256> vWorkQueue;
2679 CDataStream vMsg(vRecv);
2683 CInv inv(MSG_TX, tx.GetHash());
2684 pfrom->AddInventoryKnown(inv);
2686 bool fMissingInputs = false;
2687 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2689 AddToWalletIfInvolvingMe(tx, NULL, true);
2690 RelayMessage(inv, vMsg);
2691 mapAlreadyAskedFor.erase(inv);
2692 vWorkQueue.push_back(inv.hash);
2694 // Recursively process any orphan transactions that depended on this one
2695 for (int i = 0; i < vWorkQueue.size(); i++)
2697 uint256 hashPrev = vWorkQueue[i];
2698 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2699 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2702 const CDataStream& vMsg = *((*mi).second);
2704 CDataStream(vMsg) >> tx;
2705 CInv inv(MSG_TX, tx.GetHash());
2707 if (tx.AcceptToMemoryPool(true))
2709 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2710 AddToWalletIfInvolvingMe(tx, NULL, true);
2711 RelayMessage(inv, vMsg);
2712 mapAlreadyAskedFor.erase(inv);
2713 vWorkQueue.push_back(inv.hash);
2718 BOOST_FOREACH(uint256 hash, vWorkQueue)
2719 EraseOrphanTx(hash);
2721 else if (fMissingInputs)
2723 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2729 else if (strCommand == "block")
2734 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2737 CInv inv(MSG_BLOCK, block.GetHash());
2738 pfrom->AddInventoryKnown(inv);
2740 if (ProcessBlock(pfrom, &block))
2741 mapAlreadyAskedFor.erase(inv);
2745 else if (strCommand == "getaddr")
2747 // Nodes rebroadcast an addr every 24 hours
2748 pfrom->vAddrToSend.clear();
2749 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2750 CRITICAL_BLOCK(cs_mapAddresses)
2752 unsigned int nCount = 0;
2753 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2755 const CAddress& addr = item.second;
2756 if (addr.nTime > nSince)
2759 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2761 const CAddress& addr = item.second;
2762 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2763 pfrom->PushAddress(addr);
2769 else if (strCommand == "checkorder")
2774 if (!GetBoolArg("-allowreceivebyip"))
2776 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2783 /// we have a chance to check the order here
2785 // Keep giving the same key to the same ip until they use it
2786 if (!mapReuseKey.count(pfrom->addr.ip))
2787 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2789 // Send back approval of order and pubkey to use
2790 CScript scriptPubKey;
2791 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2792 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2796 else if (strCommand == "submitorder")
2801 if (!GetBoolArg("-allowreceivebyip"))
2803 pfrom->PushMessage("reply", hashReply, (int)2);
2809 wtxNew.fFromMe = false;
2812 if (!wtxNew.AcceptWalletTransaction())
2814 pfrom->PushMessage("reply", hashReply, (int)1);
2815 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2817 wtxNew.fTimeReceivedIsTxTime = true;
2818 AddToWallet(wtxNew);
2819 wtxNew.RelayWalletTransaction();
2820 mapReuseKey.erase(pfrom->addr.ip);
2822 // Send back confirmation
2823 pfrom->PushMessage("reply", hashReply, (int)0);
2827 else if (strCommand == "reply")
2832 CRequestTracker tracker;
2833 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2835 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2836 if (mi != pfrom->mapRequests.end())
2838 tracker = (*mi).second;
2839 pfrom->mapRequests.erase(mi);
2842 if (!tracker.IsNull())
2843 tracker.fn(tracker.param1, vRecv);
2847 else if (strCommand == "ping")
2852 else if (strCommand == "alert")
2857 if (alert.ProcessAlert())
2860 pfrom->setKnown.insert(alert.GetHash());
2861 CRITICAL_BLOCK(cs_vNodes)
2862 BOOST_FOREACH(CNode* pnode, vNodes)
2863 alert.RelayTo(pnode);
2870 // Ignore unknown commands for extensibility
2874 // Update the last seen time for this node's address
2875 if (pfrom->fNetworkNode)
2876 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2877 AddressCurrentlyConnected(pfrom->addr);
2891 bool SendMessages(CNode* pto, bool fSendTrickle)
2893 CRITICAL_BLOCK(cs_main)
2895 // Don't send anything until we get their version message
2896 if (pto->nVersion == 0)
2900 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2901 pto->PushMessage("ping");
2903 // Resend wallet transactions that haven't gotten in a block yet
2904 ResendWalletTransactions();
2906 // Address refresh broadcast
2907 static int64 nLastRebroadcast;
2908 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2910 nLastRebroadcast = GetTime();
2911 CRITICAL_BLOCK(cs_vNodes)
2913 BOOST_FOREACH(CNode* pnode, vNodes)
2915 // Periodically clear setAddrKnown to allow refresh broadcasts
2916 pnode->setAddrKnown.clear();
2918 // Rebroadcast our address
2919 if (addrLocalHost.IsRoutable() && !fUseProxy)
2921 CAddress addr(addrLocalHost);
2922 addr.nTime = GetAdjustedTime();
2923 pnode->PushAddress(addr);
2929 // Clear out old addresses periodically so it's not too much work at once
2930 static int64 nLastClear;
2931 if (nLastClear == 0)
2932 nLastClear = GetTime();
2933 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2935 nLastClear = GetTime();
2936 CRITICAL_BLOCK(cs_mapAddresses)
2939 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2940 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2941 mi != mapAddresses.end();)
2943 const CAddress& addr = (*mi).second;
2944 if (addr.nTime < nSince)
2946 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2948 addrdb.EraseAddress(addr);
2949 mapAddresses.erase(mi++);
2963 vector<CAddress> vAddr;
2964 vAddr.reserve(pto->vAddrToSend.size());
2965 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2967 // returns true if wasn't already contained in the set
2968 if (pto->setAddrKnown.insert(addr).second)
2970 vAddr.push_back(addr);
2971 // receiver rejects addr messages larger than 1000
2972 if (vAddr.size() >= 1000)
2974 pto->PushMessage("addr", vAddr);
2979 pto->vAddrToSend.clear();
2981 pto->PushMessage("addr", vAddr);
2986 // Message: inventory
2989 vector<CInv> vInvWait;
2990 CRITICAL_BLOCK(pto->cs_inventory)
2992 vInv.reserve(pto->vInventoryToSend.size());
2993 vInvWait.reserve(pto->vInventoryToSend.size());
2994 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2996 if (pto->setInventoryKnown.count(inv))
2999 // trickle out tx inv to protect privacy
3000 if (inv.type == MSG_TX && !fSendTrickle)
3002 // 1/4 of tx invs blast to all immediately
3003 static uint256 hashSalt;
3005 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
3006 uint256 hashRand = inv.hash ^ hashSalt;
3007 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3008 bool fTrickleWait = ((hashRand & 3) != 0);
3010 // always trickle our own transactions
3013 TRY_CRITICAL_BLOCK(cs_mapWallet)
3015 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
3016 if (mi != mapWallet.end())
3018 CWalletTx& wtx = (*mi).second;
3020 fTrickleWait = true;
3027 vInvWait.push_back(inv);
3032 // returns true if wasn't already contained in the set
3033 if (pto->setInventoryKnown.insert(inv).second)
3035 vInv.push_back(inv);
3036 if (vInv.size() >= 1000)
3038 pto->PushMessage("inv", vInv);
3043 pto->vInventoryToSend = vInvWait;
3046 pto->PushMessage("inv", vInv);
3052 vector<CInv> vGetData;
3053 int64 nNow = GetTime() * 1000000;
3055 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3057 const CInv& inv = (*pto->mapAskFor.begin()).second;
3058 if (!AlreadyHave(txdb, inv))
3060 printf("sending getdata: %s\n", inv.ToString().c_str());
3061 vGetData.push_back(inv);
3062 if (vGetData.size() >= 1000)
3064 pto->PushMessage("getdata", vGetData);
3068 pto->mapAskFor.erase(pto->mapAskFor.begin());
3070 if (!vGetData.empty())
3071 pto->PushMessage("getdata", vGetData);
3090 //////////////////////////////////////////////////////////////////////////////
3095 void GenerateBitcoins(bool fGenerate)
3097 if (fGenerateBitcoins != fGenerate)
3099 fGenerateBitcoins = fGenerate;
3100 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3103 if (fGenerateBitcoins)
3105 int nProcessors = boost::thread::hardware_concurrency();
3106 printf("%d processors\n", nProcessors);
3107 if (nProcessors < 1)
3109 if (fLimitProcessors && nProcessors > nLimitProcessors)
3110 nProcessors = nLimitProcessors;
3111 int nAddThreads = nProcessors - vnThreadsRunning[3];
3112 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3113 for (int i = 0; i < nAddThreads; i++)
3115 if (!CreateThread(ThreadBitcoinMiner, NULL))
3116 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3122 void ThreadBitcoinMiner(void* parg)
3126 vnThreadsRunning[3]++;
3128 vnThreadsRunning[3]--;
3130 catch (std::exception& e) {
3131 vnThreadsRunning[3]--;
3132 PrintException(&e, "ThreadBitcoinMiner()");
3134 vnThreadsRunning[3]--;
3135 PrintException(NULL, "ThreadBitcoinMiner()");
3137 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3139 if (vnThreadsRunning[3] == 0)
3141 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3145 int FormatHashBlocks(void* pbuffer, unsigned int len)
3147 unsigned char* pdata = (unsigned char*)pbuffer;
3148 unsigned int blocks = 1 + ((len + 8) / 64);
3149 unsigned char* pend = pdata + 64 * blocks;
3150 memset(pdata + len, 0, 64 * blocks - len);
3152 unsigned int bits = len * 8;
3153 pend[-1] = (bits >> 0) & 0xff;
3154 pend[-2] = (bits >> 8) & 0xff;
3155 pend[-3] = (bits >> 16) & 0xff;
3156 pend[-4] = (bits >> 24) & 0xff;
3160 using CryptoPP::ByteReverse;
3162 static const unsigned int pSHA256InitState[8] =
3163 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3165 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3167 memcpy(pstate, pinit, 32);
3168 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3172 // ScanHash scans nonces looking for a hash with at least some zero bits.
3173 // It operates on big endian data. Caller does the byte reversing.
3174 // All input buffers are 16-byte aligned. nNonce is usually preserved
3175 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3176 // the block is rebuilt and nNonce starts over at zero.
3178 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3180 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3184 // Hash pdata using pmidstate as the starting state into
3185 // preformatted buffer phash1, then hash phash1 into phash
3187 SHA256Transform(phash1, pdata, pmidstate);
3188 SHA256Transform(phash, phash1, pSHA256InitState);
3190 // Return the nonce if the hash has at least some zero bits,
3191 // caller will check if it has enough to reach the target
3192 if (((unsigned short*)phash)[14] == 0)
3195 // If nothing found after trying for a while, return -1
3196 if ((nNonce & 0xffff) == 0)
3198 nHashesDone = 0xffff+1;
3209 set<uint256> setDependsOn;
3212 COrphan(CTransaction* ptxIn)
3220 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3221 BOOST_FOREACH(uint256 hash, setDependsOn)
3222 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3227 CBlock* CreateNewBlock(CReserveKey& reservekey)
3229 CBlockIndex* pindexPrev = pindexBest;
3232 auto_ptr<CBlock> pblock(new CBlock());
3236 // Create coinbase tx
3238 txNew.vin.resize(1);
3239 txNew.vin[0].prevout.SetNull();
3240 txNew.vout.resize(1);
3241 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3243 // Add our coinbase tx as first transaction
3244 pblock->vtx.push_back(txNew);
3246 // Collect memory pool transactions into the block
3248 CRITICAL_BLOCK(cs_main)
3249 CRITICAL_BLOCK(cs_mapTransactions)
3253 // Priority order to process transactions
3254 list<COrphan> vOrphan; // list memory doesn't move
3255 map<uint256, vector<COrphan*> > mapDependers;
3256 multimap<double, CTransaction*> mapPriority;
3257 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3259 CTransaction& tx = (*mi).second;
3260 if (tx.IsCoinBase() || !tx.IsFinal())
3263 COrphan* porphan = NULL;
3264 double dPriority = 0;
3265 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3267 // Read prev transaction
3268 CTransaction txPrev;
3270 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3272 // Has to wait for dependencies
3275 // Use list for automatic deletion
3276 vOrphan.push_back(COrphan(&tx));
3277 porphan = &vOrphan.back();
3279 mapDependers[txin.prevout.hash].push_back(porphan);
3280 porphan->setDependsOn.insert(txin.prevout.hash);
3283 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3285 // Read block header
3286 int nConf = txindex.GetDepthInMainChain();
3288 dPriority += (double)nValueIn * nConf;
3290 if (fDebug && GetBoolArg("-printpriority"))
3291 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3294 // Priority is sum(valuein * age) / txsize
3295 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3298 porphan->dPriority = dPriority;
3300 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3302 if (fDebug && GetBoolArg("-printpriority"))
3304 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3311 // Collect transactions into block
3312 map<uint256, CTxIndex> mapTestPool;
3313 uint64 nBlockSize = 1000;
3314 int nBlockSigOps = 100;
3315 while (!mapPriority.empty())
3317 // Take highest priority transaction off priority queue
3318 double dPriority = -(*mapPriority.begin()).first;
3319 CTransaction& tx = *(*mapPriority.begin()).second;
3320 mapPriority.erase(mapPriority.begin());
3323 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3324 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3326 int nTxSigOps = tx.GetSigOpCount();
3327 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3330 // Transaction fee required depends on block size
3331 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3332 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
3334 // Connecting shouldn't fail due to dependency on other memory pool transactions
3335 // because we're already processing them in order of dependency
3336 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3337 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3339 swap(mapTestPool, mapTestPoolTmp);
3342 pblock->vtx.push_back(tx);
3343 nBlockSize += nTxSize;
3344 nBlockSigOps += nTxSigOps;
3346 // Add transactions that depend on this one to the priority queue
3347 uint256 hash = tx.GetHash();
3348 if (mapDependers.count(hash))
3350 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3352 if (!porphan->setDependsOn.empty())
3354 porphan->setDependsOn.erase(hash);
3355 if (porphan->setDependsOn.empty())
3356 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3362 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3365 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3366 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3367 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3368 pblock->nBits = GetNextWorkRequired(pindexPrev);
3371 return pblock.release();
3375 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3377 // Update nExtraNonce
3378 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3379 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3384 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3385 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3389 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3392 // Prebuild hash buffers
3399 uint256 hashPrevBlock;
3400 uint256 hashMerkleRoot;
3403 unsigned int nNonce;
3406 unsigned char pchPadding0[64];
3408 unsigned char pchPadding1[64];
3411 memset(&tmp, 0, sizeof(tmp));
3413 tmp.block.nVersion = pblock->nVersion;
3414 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3415 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3416 tmp.block.nTime = pblock->nTime;
3417 tmp.block.nBits = pblock->nBits;
3418 tmp.block.nNonce = pblock->nNonce;
3420 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3421 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3423 // Byte swap all the input buffer
3424 for (int i = 0; i < sizeof(tmp)/4; i++)
3425 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3427 // Precalc the first half of the first hash, which stays constant
3428 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3430 memcpy(pdata, &tmp.block, 128);
3431 memcpy(phash1, &tmp.hash1, 64);
3435 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3437 uint256 hash = pblock->GetHash();
3438 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3440 if (hash > hashTarget)
3444 printf("BitcoinMiner:\n");
3445 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3447 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3448 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3451 CRITICAL_BLOCK(cs_main)
3453 if (pblock->hashPrevBlock != hashBestChain)
3454 return error("BitcoinMiner : generated block is stale");
3456 // Remove key from key pool
3457 reservekey.KeepKey();
3459 // Track how many getdata requests this block gets
3460 CRITICAL_BLOCK(cs_mapRequestCount)
3461 mapRequestCount[pblock->GetHash()] = 0;
3463 // Process this block the same as if we had received it from another node
3464 if (!ProcessBlock(NULL, pblock))
3465 return error("BitcoinMiner : ProcessBlock, block not accepted");
3475 printf("BitcoinMiner started\n");
3476 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3478 // Each thread has its own key and counter
3479 CReserveKey reservekey;
3480 unsigned int nExtraNonce = 0;
3481 int64 nPrevTime = 0;
3483 while (fGenerateBitcoins)
3485 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3489 while (vNodes.empty() || IsInitialBlockDownload())
3494 if (!fGenerateBitcoins)
3502 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3503 CBlockIndex* pindexPrev = pindexBest;
3505 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3508 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3510 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3514 // Prebuild hash buffers
3516 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3517 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3518 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3520 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3522 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3523 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3529 int64 nStart = GetTime();
3530 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3532 uint256& hash = *alignup<16>(hashbuf);
3535 unsigned int nHashesDone = 0;
3536 unsigned int nNonceFound;
3539 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3540 (char*)&hash, nHashesDone);
3542 // Check if something found
3543 if (nNonceFound != -1)
3545 for (int i = 0; i < sizeof(hash)/4; i++)
3546 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3548 if (hash <= hashTarget)
3551 pblock->nNonce = ByteReverse(nNonceFound);
3552 assert(hash == pblock->GetHash());
3554 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3555 CheckWork(pblock.get(), reservekey);
3556 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3562 static int64 nHashCounter;
3563 if (nHPSTimerStart == 0)
3565 nHPSTimerStart = GetTimeMillis();
3569 nHashCounter += nHashesDone;
3570 if (GetTimeMillis() - nHPSTimerStart > 4000)
3572 static CCriticalSection cs;
3575 if (GetTimeMillis() - nHPSTimerStart > 4000)
3577 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3578 nHPSTimerStart = GetTimeMillis();
3580 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3581 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3582 static int64 nLogTime;
3583 if (GetTime() - nLogTime > 30 * 60)
3585 nLogTime = GetTime();
3586 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3587 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3593 // Check for stop or if block needs to be rebuilt
3596 if (!fGenerateBitcoins)
3598 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3602 if (nBlockNonce >= 0xffff0000)
3604 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3606 if (pindexPrev != pindexBest)
3609 // Update nTime every few seconds
3610 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3611 nBlockTime = ByteReverse(pblock->nTime);
3633 //////////////////////////////////////////////////////////////////////////////
3641 int64 nStart = GetTimeMillis();
3644 CRITICAL_BLOCK(cs_mapWallet)
3646 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3648 CWalletTx* pcoin = &(*it).second;
3649 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3651 nTotal += pcoin->GetAvailableCredit();
3655 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3660 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3662 setCoinsRet.clear();
3665 // List of values less than target
3666 pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;
3667 coinLowestLarger.first = INT64_MAX;
3668 coinLowestLarger.second.first = NULL;
3669 vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;
3670 int64 nTotalLower = 0;
3672 CRITICAL_BLOCK(cs_mapWallet)
3674 vector<CWalletTx*> vCoins;
3675 vCoins.reserve(mapWallet.size());
3676 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3677 vCoins.push_back(&(*it).second);
3678 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3680 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
3682 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3685 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3688 int nDepth = pcoin->GetDepthInMainChain();
3689 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3692 for (int i = 0; i < pcoin->vout.size(); i++)
3694 if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())
3697 int64 n = pcoin->vout[i].nValue;
3702 pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
3704 if (n == nTargetValue)
3706 setCoinsRet.insert(coin.second);
3707 nValueRet += coin.first;
3710 else if (n < nTargetValue + CENT)
3712 vValue.push_back(coin);
3715 else if (n < coinLowestLarger.first)
3717 coinLowestLarger = coin;
3723 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
3725 for (int i = 0; i < vValue.size(); ++i)
3727 setCoinsRet.insert(vValue[i].second);
3728 nValueRet += vValue[i].first;
3733 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
3735 if (coinLowestLarger.second.first == NULL)
3737 setCoinsRet.insert(coinLowestLarger.second);
3738 nValueRet += coinLowestLarger.first;
3742 if (nTotalLower >= nTargetValue + CENT)
3743 nTargetValue += CENT;
3745 // Solve subset sum by stochastic approximation
3746 sort(vValue.rbegin(), vValue.rend());
3747 vector<char> vfIncluded;
3748 vector<char> vfBest(vValue.size(), true);
3749 int64 nBest = nTotalLower;
3751 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3753 vfIncluded.assign(vValue.size(), false);
3755 bool fReachedTarget = false;
3756 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3758 for (int i = 0; i < vValue.size(); i++)
3760 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3762 nTotal += vValue[i].first;
3763 vfIncluded[i] = true;
3764 if (nTotal >= nTargetValue)
3766 fReachedTarget = true;
3770 vfBest = vfIncluded;
3772 nTotal -= vValue[i].first;
3773 vfIncluded[i] = false;
3780 // If the next larger is still closer, return it
3781 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
3783 setCoinsRet.insert(coinLowestLarger.second);
3784 nValueRet += coinLowestLarger.first;
3787 for (int i = 0; i < vValue.size(); i++)
3790 setCoinsRet.insert(vValue[i].second);
3791 nValueRet += vValue[i].first;
3795 printf("SelectCoins() best subset: ");
3796 for (int i = 0; i < vValue.size(); i++)
3798 printf("%s ", FormatMoney(vValue[i].first).c_str());
3799 printf("total %s\n", FormatMoney(nBest).c_str());
3805 bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3807 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
3808 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
3809 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
3815 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3818 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3824 if (vecSend.empty() || nValue < 0)
3827 CRITICAL_BLOCK(cs_main)
3829 // txdb must be opened before the mapWallet lock
3831 CRITICAL_BLOCK(cs_mapWallet)
3833 nFeeRet = nTransactionFee;
3837 wtxNew.vout.clear();
3838 wtxNew.fFromMe = true;
3840 int64 nTotalValue = nValue + nFeeRet;
3841 double dPriority = 0;
3842 // vouts to the payees
3843 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3844 wtxNew.vout.push_back(CTxOut(s.second, s.first));
3846 // Choose coins to use
3847 set<pair<CWalletTx*,unsigned int> > setCoins;
3849 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
3851 BOOST_FOREACH(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)
3853 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
3854 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
3857 int64 nChange = nValueIn - nValue - nFeeRet;
3859 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
3860 // or until nChange becomes zero
3861 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
3863 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
3864 nChange -= nMoveToFee;
3865 nFeeRet += nMoveToFee;
3870 // Note: We use a new key here to keep it from being obvious which side is the change.
3871 // The drawback is that by not reusing a previous key, the change may be lost if a
3872 // backup is restored, if the backup doesn't have the new private key for the change.
3873 // If we reused the old key, it would be possible to add code to look for and
3874 // rediscover unknown transactions that were written with keys of ours to recover
3875 // post-backup change.
3877 // Reserve a new key pair from key pool
3878 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3879 assert(mapKeys.count(vchPubKey));
3881 // Fill a vout to ourself, using same address type as the payment
3882 CScript scriptChange;
3883 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
3884 scriptChange.SetBitcoinAddress(vchPubKey);
3886 scriptChange << vchPubKey << OP_CHECKSIG;
3888 // Insert change txn at random position:
3889 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
3890 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
3893 reservekey.ReturnKey();
3896 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3897 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
3901 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3902 if (!SignSignature(*coin.first, wtxNew, nIn++))
3906 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3907 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3909 dPriority /= nBytes;
3911 // Check that enough fee is included
3912 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3913 bool fAllowFree = CTransaction::AllowFree(dPriority);
3914 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
3915 if (nFeeRet < max(nPayFee, nMinFee))
3917 nFeeRet = max(nPayFee, nMinFee);
3921 // Fill vtxPrev by copying from previous transactions vtxPrev
3922 wtxNew.AddSupportingTransactions(txdb);
3923 wtxNew.fTimeReceivedIsTxTime = true;
3932 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3934 vector< pair<CScript, int64> > vecSend;
3935 vecSend.push_back(make_pair(scriptPubKey, nValue));
3936 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
3939 // Call after CreateTransaction unless you want to abort
3940 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3942 CRITICAL_BLOCK(cs_main)
3944 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3945 CRITICAL_BLOCK(cs_mapWallet)
3947 // This is only to keep the database open to defeat the auto-flush for the
3948 // duration of this scope. This is the only place where this optimization
3949 // maybe makes sense; please don't do it anywhere else.
3950 CWalletDB walletdb("r");
3952 // Take key pair from key pool so it won't be used again
3953 reservekey.KeepKey();
3955 // Add tx to wallet, because if it has change it's also ours,
3956 // otherwise just for transaction history.
3957 AddToWallet(wtxNew);
3959 // Mark old coins as spent
3960 set<CWalletTx*> setCoins;
3961 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3963 CWalletTx &pcoin = mapWallet[txin.prevout.hash];
3964 pcoin.MarkSpent(txin.prevout.n);
3965 pcoin.WriteToDisk();
3966 vWalletUpdated.push_back(pcoin.GetHash());
3970 // Track how many getdata requests our transaction gets
3971 CRITICAL_BLOCK(cs_mapRequestCount)
3972 mapRequestCount[wtxNew.GetHash()] = 0;
3975 if (!wtxNew.AcceptToMemoryPool())
3977 // This must not fail. The transaction has already been signed and recorded.
3978 printf("CommitTransaction() : Error: Transaction not valid");
3981 wtxNew.RelayWalletTransaction();
3990 // requires cs_main lock
3991 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3993 CReserveKey reservekey;
3995 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3998 if (nValue + nFeeRequired > GetBalance())
3999 strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
4001 strError = _("Error: Transaction creation failed ");
4002 printf("SendMoney() : %s", strError.c_str());
4006 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4009 if (!CommitTransaction(wtxNew, reservekey))
4010 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.");
4018 // requires cs_main lock
4019 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4023 return _("Invalid amount");
4024 if (nValue + nTransactionFee > GetBalance())
4025 return _("Insufficient funds");
4027 // Parse bitcoin address
4028 CScript scriptPubKey;
4029 if (!scriptPubKey.SetBitcoinAddress(strAddress))
4030 return _("Invalid bitcoin address");
4032 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);