1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8 #include "cryptopp/sha.h"
9 #include <boost/filesystem/fstream.hpp>
12 using namespace boost;
18 CCriticalSection cs_main;
20 map<uint256, CTransaction> mapTransactions;
21 CCriticalSection cs_mapTransactions;
22 unsigned int nTransactionsUpdated = 0;
23 map<COutPoint, CInPoint> mapNextTx;
25 map<uint256, CBlockIndex*> mapBlockIndex;
26 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
27 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
28 const int nTotalBlocksEstimate = 131000; // Conservative estimate of total nr of blocks on main chain
29 CBlockIndex* pindexGenesisBlock = NULL;
31 CBigNum bnBestChainWork = 0;
32 CBigNum bnBestInvalidWork = 0;
33 uint256 hashBestChain = 0;
34 CBlockIndex* pindexBest = NULL;
35 int64 nTimeBestReceived = 0;
37 map<uint256, CBlock*> mapOrphanBlocks;
38 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
40 map<uint256, CDataStream*> mapOrphanTransactions;
41 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
43 map<uint256, CWalletTx> mapWallet;
44 vector<uint256> vWalletUpdated;
45 CCriticalSection cs_mapWallet;
47 map<vector<unsigned char>, CPrivKey> mapKeys;
48 map<uint160, vector<unsigned char> > mapPubKeys;
49 CCriticalSection cs_mapKeys;
52 map<uint256, int> mapRequestCount;
53 CCriticalSection cs_mapRequestCount;
55 map<string, string> mapAddressBook;
56 CCriticalSection cs_mapAddressBook;
58 vector<unsigned char> vchDefaultKey;
64 int fGenerateBitcoins = false;
65 int64 nTransactionFee = 0;
66 CAddress addrIncoming;
67 int fLimitProcessors = false;
68 int nLimitProcessors = 1;
69 int fMinimizeToTray = true;
70 int fMinimizeOnClose = true;
83 //////////////////////////////////////////////////////////////////////////////
88 bool AddKey(const CKey& key)
90 CRITICAL_BLOCK(cs_mapKeys)
92 mapKeys[key.GetPubKey()] = key.GetPrivKey();
93 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
95 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
98 vector<unsigned char> GenerateNewKey()
100 RandAddSeedPerfmon();
104 throw runtime_error("GenerateNewKey() : AddKey failed");
105 return key.GetPubKey();
111 //////////////////////////////////////////////////////////////////////////////
116 bool AddToWallet(const CWalletTx& wtxIn)
118 uint256 hash = wtxIn.GetHash();
119 CRITICAL_BLOCK(cs_mapWallet)
121 // Inserts only if not already there, returns tx inserted or tx found
122 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
123 CWalletTx& wtx = (*ret.first).second;
124 bool fInsertedNew = ret.second;
126 wtx.nTimeReceived = GetAdjustedTime();
128 bool fUpdated = false;
132 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
134 wtx.hashBlock = wtxIn.hashBlock;
137 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
139 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
140 wtx.nIndex = wtxIn.nIndex;
143 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
145 wtx.fFromMe = wtxIn.fFromMe;
148 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
152 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
155 if (fInsertedNew || fUpdated)
156 if (!wtx.WriteToDisk())
159 // If default receiving address gets used, replace it with a new one
160 CScript scriptDefaultKey;
161 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
162 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
164 if (txout.scriptPubKey == scriptDefaultKey)
167 vchDefaultKey = GetKeyFromKeyPool();
168 walletdb.WriteDefaultKey(vchDefaultKey);
169 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
174 vWalletUpdated.push_back(hash);
182 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false)
184 uint256 hash = tx.GetHash();
185 bool fExisted = mapWallet.count(hash);
186 if (fExisted && !fUpdate) return false;
187 if (fExisted || tx.IsMine() || tx.IsFromMe())
190 // Get merkle branch if transaction was found in a block
192 wtx.SetMerkleBranch(pblock);
193 return AddToWallet(wtx);
198 bool EraseFromWallet(uint256 hash)
200 CRITICAL_BLOCK(cs_mapWallet)
202 if (mapWallet.erase(hash))
203 CWalletDB().EraseTx(hash);
208 void WalletUpdateSpent(const COutPoint& prevout)
210 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
211 // Update the wallet spent flag if it doesn't know due to wallet.dat being
212 // restored from backup or the user making copies of wallet.dat.
213 CRITICAL_BLOCK(cs_mapWallet)
215 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
216 if (mi != mapWallet.end())
218 CWalletTx& wtx = (*mi).second;
219 if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())
221 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
222 wtx.MarkSpent(prevout.n);
224 vWalletUpdated.push_back(prevout.hash);
237 //////////////////////////////////////////////////////////////////////////////
239 // mapOrphanTransactions
242 void AddOrphanTx(const CDataStream& vMsg)
245 CDataStream(vMsg) >> tx;
246 uint256 hash = tx.GetHash();
247 if (mapOrphanTransactions.count(hash))
249 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
250 BOOST_FOREACH(const CTxIn& txin, tx.vin)
251 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
254 void EraseOrphanTx(uint256 hash)
256 if (!mapOrphanTransactions.count(hash))
258 const CDataStream* pvMsg = mapOrphanTransactions[hash];
260 CDataStream(*pvMsg) >> tx;
261 BOOST_FOREACH(const CTxIn& txin, tx.vin)
263 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
264 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
266 if ((*mi).second == pvMsg)
267 mapOrphanTransactionsByPrev.erase(mi++);
273 mapOrphanTransactions.erase(hash);
283 //////////////////////////////////////////////////////////////////////////////
285 // CTransaction and CTxIndex
288 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
291 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
293 if (!ReadFromDisk(txindexRet.pos))
295 if (prevout.n >= vout.size())
303 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
306 return ReadFromDisk(txdb, prevout, txindex);
309 bool CTransaction::ReadFromDisk(COutPoint prevout)
313 return ReadFromDisk(txdb, prevout, txindex);
316 bool CTxIn::IsMine() const
318 CRITICAL_BLOCK(cs_mapWallet)
320 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
321 if (mi != mapWallet.end())
323 const CWalletTx& prev = (*mi).second;
324 if (prevout.n < prev.vout.size())
325 if (prev.vout[prevout.n].IsMine())
332 int64 CTxIn::GetDebit() const
334 CRITICAL_BLOCK(cs_mapWallet)
336 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
337 if (mi != mapWallet.end())
339 const CWalletTx& prev = (*mi).second;
340 if (prevout.n < prev.vout.size())
341 if (prev.vout[prevout.n].IsMine())
342 return prev.vout[prevout.n].nValue;
348 int64 CWalletTx::GetTxTime() const
350 if (!fTimeReceivedIsTxTime && hashBlock != 0)
352 // If we did not receive the transaction directly, we rely on the block's
353 // time to figure out when it happened. We use the median over a range
354 // of blocks to try to filter out inaccurate block times.
355 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
356 if (mi != mapBlockIndex.end())
358 CBlockIndex* pindex = (*mi).second;
360 return pindex->GetMedianTime();
363 return nTimeReceived;
366 int CWalletTx::GetRequestCount() const
368 // Returns -1 if it wasn't being tracked
370 CRITICAL_BLOCK(cs_mapRequestCount)
377 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
378 if (mi != mapRequestCount.end())
379 nRequests = (*mi).second;
384 // Did anyone request this transaction?
385 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
386 if (mi != mapRequestCount.end())
388 nRequests = (*mi).second;
390 // How about the block it's in?
391 if (nRequests == 0 && hashBlock != 0)
393 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
394 if (mi != mapRequestCount.end())
395 nRequests = (*mi).second;
397 nRequests = 1; // If it's in someone else's block it must have got out
405 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
406 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
408 nGeneratedImmature = nGeneratedMature = nFee = 0;
409 listReceived.clear();
411 strSentAccount = strFromAccount;
415 if (GetBlocksToMaturity() > 0)
416 nGeneratedImmature = CTransaction::GetCredit();
418 nGeneratedMature = GetCredit();
423 int64 nDebit = GetDebit();
424 if (nDebit > 0) // debit>0 means we signed/sent this transaction
426 int64 nValueOut = GetValueOut();
427 nFee = nDebit - nValueOut;
430 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
431 // but non-standard clients might (so return a list of address/amount pairs)
432 BOOST_FOREACH(const CTxOut& txout, vout)
436 vector<unsigned char> vchPubKey;
437 if (ExtractHash160(txout.scriptPubKey, hash160))
438 address = Hash160ToAddress(hash160);
439 else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))
440 address = PubKeyToAddress(vchPubKey);
443 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
444 this->GetHash().ToString().c_str());
445 address = " unknown ";
448 // Don't report 'change' txouts
449 if (nDebit > 0 && txout.IsChange())
453 listSent.push_back(make_pair(address, txout.nValue));
456 listReceived.push_back(make_pair(address, txout.nValue));
461 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
462 int64& nSent, int64& nFee) const
464 nGenerated = nReceived = nSent = nFee = 0;
466 int64 allGeneratedImmature, allGeneratedMature, allFee;
467 allGeneratedImmature = allGeneratedMature = allFee = 0;
468 string strSentAccount;
469 list<pair<string, int64> > listReceived;
470 list<pair<string, int64> > listSent;
471 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
473 if (strAccount == "")
474 nGenerated = allGeneratedMature;
475 if (strAccount == strSentAccount)
477 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
481 CRITICAL_BLOCK(cs_mapAddressBook)
483 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
485 if (mapAddressBook.count(r.first))
487 if (mapAddressBook[r.first] == strAccount)
489 nReceived += r.second;
492 else if (strAccount.empty())
494 nReceived += r.second;
502 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
514 // Load the block this tx is in
516 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
518 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
523 // Update the tx's hashBlock
524 hashBlock = pblock->GetHash();
526 // Locate the transaction
527 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
528 if (pblock->vtx[nIndex] == *(CTransaction*)this)
530 if (nIndex == pblock->vtx.size())
532 vMerkleBranch.clear();
534 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
538 // Fill in merkle branch
539 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
542 // Is the tx in a block that's in the main chain
543 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
544 if (mi == mapBlockIndex.end())
546 CBlockIndex* pindex = (*mi).second;
547 if (!pindex || !pindex->IsInMainChain())
550 return pindexBest->nHeight - pindex->nHeight + 1;
555 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
559 const int COPY_DEPTH = 3;
560 if (SetMerkleBranch() < COPY_DEPTH)
562 vector<uint256> vWorkQueue;
563 BOOST_FOREACH(const CTxIn& txin, vin)
564 vWorkQueue.push_back(txin.prevout.hash);
566 // This critsect is OK because txdb is already open
567 CRITICAL_BLOCK(cs_mapWallet)
569 map<uint256, const CMerkleTx*> mapWalletPrev;
570 set<uint256> setAlreadyDone;
571 for (int i = 0; i < vWorkQueue.size(); i++)
573 uint256 hash = vWorkQueue[i];
574 if (setAlreadyDone.count(hash))
576 setAlreadyDone.insert(hash);
579 if (mapWallet.count(hash))
581 tx = mapWallet[hash];
582 BOOST_FOREACH(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
583 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
585 else if (mapWalletPrev.count(hash))
587 tx = *mapWalletPrev[hash];
589 else if (!fClient && txdb.ReadDiskTx(hash, tx))
595 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
599 int nDepth = tx.SetMerkleBranch();
600 vtxPrev.push_back(tx);
602 if (nDepth < COPY_DEPTH)
603 BOOST_FOREACH(const CTxIn& txin, tx.vin)
604 vWorkQueue.push_back(txin.prevout.hash);
609 reverse(vtxPrev.begin(), vtxPrev.end());
622 bool CTransaction::CheckTransaction() const
624 // Basic checks that don't depend on any context
625 if (vin.empty() || vout.empty())
626 return error("CTransaction::CheckTransaction() : vin or vout empty");
629 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
630 return error("CTransaction::CheckTransaction() : size limits failed");
632 // Check for negative or overflow output values
634 BOOST_FOREACH(const CTxOut& txout, vout)
636 if (txout.nValue < 0)
637 return error("CTransaction::CheckTransaction() : txout.nValue negative");
638 if (txout.nValue > MAX_MONEY)
639 return error("CTransaction::CheckTransaction() : txout.nValue too high");
640 nValueOut += txout.nValue;
641 if (!MoneyRange(nValueOut))
642 return error("CTransaction::CheckTransaction() : txout total out of range");
647 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
648 return error("CTransaction::CheckTransaction() : coinbase script size");
652 BOOST_FOREACH(const CTxIn& txin, vin)
653 if (txin.prevout.IsNull())
654 return error("CTransaction::CheckTransaction() : prevout is null");
660 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
663 *pfMissingInputs = false;
665 if (!CheckTransaction())
666 return error("AcceptToMemoryPool() : CheckTransaction failed");
668 // Coinbase is only valid in a block, not as a loose transaction
670 return error("AcceptToMemoryPool() : coinbase as individual tx");
672 // To help v0.1.5 clients who would see it as a negative number
673 if ((int64)nLockTime > INT_MAX)
674 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
677 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
678 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
679 // attacks disallow transactions with more than one SigOp per 34 bytes.
680 // 34 bytes because a TxOut is:
681 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
682 if (GetSigOpCount() > nSize / 34 || nSize < 100)
683 return error("AcceptToMemoryPool() : nonstandard transaction");
685 // Rather not work on nonstandard transactions (unless -testnet)
686 if (!fTestNet && !IsStandard())
687 return error("AcceptToMemoryPool() : nonstandard transaction type");
689 // Do we already have it?
690 uint256 hash = GetHash();
691 CRITICAL_BLOCK(cs_mapTransactions)
692 if (mapTransactions.count(hash))
695 if (txdb.ContainsTx(hash))
698 // Check for conflicts with in-memory transactions
699 CTransaction* ptxOld = NULL;
700 for (int i = 0; i < vin.size(); i++)
702 COutPoint outpoint = vin[i].prevout;
703 if (mapNextTx.count(outpoint))
705 // Disable replacement feature for now
708 // Allow replacing with a newer version of the same transaction
711 ptxOld = mapNextTx[outpoint].ptx;
712 if (ptxOld->IsFinal())
714 if (!IsNewerThan(*ptxOld))
716 for (int i = 0; i < vin.size(); i++)
718 COutPoint outpoint = vin[i].prevout;
719 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
728 // Check against previous transactions
729 map<uint256, CTxIndex> mapUnused;
731 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
734 *pfMissingInputs = true;
735 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
738 // Don't accept it if it can't get into a block
739 if (nFees < GetMinFee(1000, true, true))
740 return error("AcceptToMemoryPool() : not enough fees");
742 // Continuously rate-limit free transactions
743 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
744 // be annoying or make other's transactions take longer to confirm.
745 if (nFees < MIN_RELAY_TX_FEE)
747 static CCriticalSection cs;
748 static double dFreeCount;
749 static int64 nLastTime;
750 int64 nNow = GetTime();
754 // Use an exponentially decaying ~10-minute window:
755 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
757 // -limitfreerelay unit is thousand-bytes-per-minute
758 // At default rate it would take over a month to fill 1GB
759 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())
760 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
762 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
768 // Store transaction in memory
769 CRITICAL_BLOCK(cs_mapTransactions)
773 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
774 ptxOld->RemoveFromMemoryPool();
776 AddToMemoryPoolUnchecked();
779 ///// are we sure this is ok when loading transactions or restoring block txes
780 // If updated, erase old tx from wallet
782 EraseFromWallet(ptxOld->GetHash());
784 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
789 bool CTransaction::AddToMemoryPoolUnchecked()
791 // Add to memory pool without checking anything. Don't call this directly,
792 // call AcceptToMemoryPool to properly check the transaction first.
793 CRITICAL_BLOCK(cs_mapTransactions)
795 uint256 hash = GetHash();
796 mapTransactions[hash] = *this;
797 for (int i = 0; i < vin.size(); i++)
798 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
799 nTransactionsUpdated++;
805 bool CTransaction::RemoveFromMemoryPool()
807 // Remove transaction from memory pool
808 CRITICAL_BLOCK(cs_mapTransactions)
810 BOOST_FOREACH(const CTxIn& txin, vin)
811 mapNextTx.erase(txin.prevout);
812 mapTransactions.erase(GetHash());
813 nTransactionsUpdated++;
823 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
825 if (hashBlock == 0 || nIndex == -1)
828 // Find the block it claims to be in
829 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
830 if (mi == mapBlockIndex.end())
832 CBlockIndex* pindex = (*mi).second;
833 if (!pindex || !pindex->IsInMainChain())
836 // Make sure the merkle branch connects to this block
837 if (!fMerkleVerified)
839 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
841 fMerkleVerified = true;
844 nHeightRet = pindex->nHeight;
845 return pindexBest->nHeight - pindex->nHeight + 1;
849 int CMerkleTx::GetBlocksToMaturity() const
853 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
857 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
861 if (!IsInMainChain() && !ClientConnectInputs())
863 return CTransaction::AcceptToMemoryPool(txdb, false);
867 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
873 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
875 CRITICAL_BLOCK(cs_mapTransactions)
877 // Add previous supporting transactions first
878 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
880 if (!tx.IsCoinBase())
882 uint256 hash = tx.GetHash();
883 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
884 tx.AcceptToMemoryPool(txdb, fCheckInputs);
887 return AcceptToMemoryPool(txdb, fCheckInputs);
892 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
896 CBlockIndex* pindex = pindexStart;
897 CRITICAL_BLOCK(cs_mapWallet)
902 block.ReadFromDisk(pindex, true);
903 BOOST_FOREACH(CTransaction& tx, block.vtx)
905 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
908 pindex = pindex->pnext;
914 void ReacceptWalletTransactions()
918 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
921 vector<CDiskTxPos> vMissingTx;
922 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
924 CWalletTx& wtx = item.second;
925 if (wtx.IsCoinBase() && wtx.IsSpent(0))
929 bool fUpdated = false;
930 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
932 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
933 if (txindex.vSpent.size() != wtx.vout.size())
935 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
938 for (int i = 0; i < txindex.vSpent.size(); i++)
942 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
946 vMissingTx.push_back(txindex.vSpent[i]);
951 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
958 // Reaccept any txes of ours that aren't already in a block
959 if (!wtx.IsCoinBase())
960 wtx.AcceptWalletTransaction(txdb, false);
963 if (!vMissingTx.empty())
965 // TODO: optimize this to scan just part of the block chain?
966 if (ScanForWalletTransactions(pindexGenesisBlock))
967 fRepeat = true; // Found missing transactions: re-do Reaccept.
973 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
975 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
977 if (!tx.IsCoinBase())
979 uint256 hash = tx.GetHash();
980 if (!txdb.ContainsTx(hash))
981 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
986 uint256 hash = GetHash();
987 if (!txdb.ContainsTx(hash))
989 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
990 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
995 void ResendWalletTransactions()
997 // Do this infrequently and randomly to avoid giving away
998 // that these are our transactions.
999 static int64 nNextTime;
1000 if (GetTime() < nNextTime)
1002 bool fFirst = (nNextTime == 0);
1003 nNextTime = GetTime() + GetRand(30 * 60);
1007 // Only do it if there's been a new block since last time
1008 static int64 nLastTime;
1009 if (nTimeBestReceived < nLastTime)
1011 nLastTime = GetTime();
1013 // Rebroadcast any of our txes that aren't in a block yet
1014 printf("ResendWalletTransactions()\n");
1016 CRITICAL_BLOCK(cs_mapWallet)
1018 // Sort them in chronological order
1019 multimap<unsigned int, CWalletTx*> mapSorted;
1020 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1022 CWalletTx& wtx = item.second;
1023 // Don't rebroadcast until it's had plenty of time that
1024 // it should have gotten in already by now.
1025 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1026 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1028 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1030 CWalletTx& wtx = *item.second;
1031 wtx.RelayWalletTransaction(txdb);
1036 int CTxIndex::GetDepthInMainChain() const
1038 // Read block header
1040 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
1042 // Find the block in the index
1043 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
1044 if (mi == mapBlockIndex.end())
1046 CBlockIndex* pindex = (*mi).second;
1047 if (!pindex || !pindex->IsInMainChain())
1049 return 1 + nBestHeight - pindex->nHeight;
1061 //////////////////////////////////////////////////////////////////////////////
1063 // CBlock and CBlockIndex
1066 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1068 if (!fReadTransactions)
1070 *this = pindex->GetBlockHeader();
1073 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1075 if (GetHash() != pindex->GetBlockHash())
1076 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1080 uint256 GetOrphanRoot(const CBlock* pblock)
1082 // Work back to the first block in the orphan chain
1083 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1084 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1085 return pblock->GetHash();
1088 int64 GetBlockValue(int nHeight, int64 nFees)
1090 int64 nSubsidy = 50 * COIN;
1092 // Subsidy is cut in half every 4 years
1093 nSubsidy >>= (nHeight / 210000);
1095 return nSubsidy + nFees;
1098 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1100 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1101 const int64 nTargetSpacing = 10 * 60;
1102 const int64 nInterval = nTargetTimespan / nTargetSpacing;
1105 if (pindexLast == NULL)
1106 return bnProofOfWorkLimit.GetCompact();
1108 // Only change once per interval
1109 if ((pindexLast->nHeight+1) % nInterval != 0)
1110 return pindexLast->nBits;
1112 // Go back by what we want to be 14 days worth of blocks
1113 const CBlockIndex* pindexFirst = pindexLast;
1114 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1115 pindexFirst = pindexFirst->pprev;
1116 assert(pindexFirst);
1118 // Limit adjustment step
1119 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1120 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1121 if (nActualTimespan < nTargetTimespan/4)
1122 nActualTimespan = nTargetTimespan/4;
1123 if (nActualTimespan > nTargetTimespan*4)
1124 nActualTimespan = nTargetTimespan*4;
1128 bnNew.SetCompact(pindexLast->nBits);
1129 bnNew *= nActualTimespan;
1130 bnNew /= nTargetTimespan;
1132 if (bnNew > bnProofOfWorkLimit)
1133 bnNew = bnProofOfWorkLimit;
1136 printf("GetNextWorkRequired RETARGET\n");
1137 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1138 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1139 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1141 return bnNew.GetCompact();
1144 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1147 bnTarget.SetCompact(nBits);
1150 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1151 return error("CheckProofOfWork() : nBits below minimum work");
1153 // Check proof of work matches claimed amount
1154 if (hash > bnTarget.getuint256())
1155 return error("CheckProofOfWork() : hash doesn't match nBits");
1160 // Return conservative estimate of total number of blocks, 0 if unknown
1161 int GetTotalBlocksEstimate()
1169 return nTotalBlocksEstimate;
1173 bool IsInitialBlockDownload()
1175 if (pindexBest == NULL || nBestHeight < GetTotalBlocksEstimate())
1177 static int64 nLastUpdate;
1178 static CBlockIndex* pindexLastBest;
1179 if (pindexBest != pindexLastBest)
1181 pindexLastBest = pindexBest;
1182 nLastUpdate = GetTime();
1184 return (GetTime() - nLastUpdate < 10 &&
1185 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1188 void InvalidChainFound(CBlockIndex* pindexNew)
1190 if (pindexNew->bnChainWork > bnBestInvalidWork)
1192 bnBestInvalidWork = pindexNew->bnChainWork;
1193 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1196 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());
1197 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1198 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1199 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1212 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1214 // Relinquish previous transactions' spent pointers
1217 BOOST_FOREACH(const CTxIn& txin, vin)
1219 COutPoint prevout = txin.prevout;
1221 // Get prev txindex from disk
1223 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1224 return error("DisconnectInputs() : ReadTxIndex failed");
1226 if (prevout.n >= txindex.vSpent.size())
1227 return error("DisconnectInputs() : prevout.n out of range");
1229 // Mark outpoint as not spent
1230 txindex.vSpent[prevout.n].SetNull();
1233 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1234 return error("DisconnectInputs() : UpdateTxIndex failed");
1238 // Remove transaction from index
1239 if (!txdb.EraseTxIndex(*this))
1240 return error("DisconnectInputs() : EraseTxPos failed");
1246 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1247 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1249 // Take over previous transactions' spent pointers
1253 for (int i = 0; i < vin.size(); i++)
1255 COutPoint prevout = vin[i].prevout;
1260 if (fMiner && mapTestPool.count(prevout.hash))
1262 // Get txindex from current proposed changes
1263 txindex = mapTestPool[prevout.hash];
1267 // Read txindex from txdb
1268 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1270 if (!fFound && (fBlock || fMiner))
1271 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());
1274 CTransaction txPrev;
1275 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1277 // Get prev tx from single transactions in memory
1278 CRITICAL_BLOCK(cs_mapTransactions)
1280 if (!mapTransactions.count(prevout.hash))
1281 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1282 txPrev = mapTransactions[prevout.hash];
1285 txindex.vSpent.resize(txPrev.vout.size());
1289 // Get prev tx from disk
1290 if (!txPrev.ReadFromDisk(txindex.pos))
1291 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1294 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1295 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());
1297 // If prev is coinbase, check that it's matured
1298 if (txPrev.IsCoinBase())
1299 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1300 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1301 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1304 if (!VerifySignature(txPrev, *this, i))
1305 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1307 // Check for conflicts
1308 if (!txindex.vSpent[prevout.n].IsNull())
1309 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());
1311 // Check for negative or overflow input values
1312 nValueIn += txPrev.vout[prevout.n].nValue;
1313 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1314 return error("ConnectInputs() : txin values out of range");
1316 // Mark outpoints as spent
1317 txindex.vSpent[prevout.n] = posThisTx;
1322 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1323 return error("ConnectInputs() : UpdateTxIndex failed");
1327 mapTestPool[prevout.hash] = txindex;
1331 if (nValueIn < GetValueOut())
1332 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1334 // Tally transaction fees
1335 int64 nTxFee = nValueIn - GetValueOut();
1337 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1338 if (nTxFee < nMinFee)
1341 if (!MoneyRange(nFees))
1342 return error("ConnectInputs() : nFees out of range");
1347 // Add transaction to disk index
1348 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1349 return error("ConnectInputs() : AddTxPos failed");
1353 // Add transaction to test pool
1354 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1361 bool CTransaction::ClientConnectInputs()
1366 // Take over previous transactions' spent pointers
1367 CRITICAL_BLOCK(cs_mapTransactions)
1370 for (int i = 0; i < vin.size(); i++)
1372 // Get prev tx from single transactions in memory
1373 COutPoint prevout = vin[i].prevout;
1374 if (!mapTransactions.count(prevout.hash))
1376 CTransaction& txPrev = mapTransactions[prevout.hash];
1378 if (prevout.n >= txPrev.vout.size())
1382 if (!VerifySignature(txPrev, *this, i))
1383 return error("ConnectInputs() : VerifySignature failed");
1385 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1386 ///// this has to go away now that posNext is gone
1387 // // Check for conflicts
1388 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1389 // return error("ConnectInputs() : prev tx already used");
1391 // // Flag outpoints as used
1392 // txPrev.vout[prevout.n].posNext = posThisTx;
1394 nValueIn += txPrev.vout[prevout.n].nValue;
1396 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1397 return error("ClientConnectInputs() : txin values out of range");
1399 if (GetValueOut() > nValueIn)
1409 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1411 // Disconnect in reverse order
1412 for (int i = vtx.size()-1; i >= 0; i--)
1413 if (!vtx[i].DisconnectInputs(txdb))
1416 // Update block index on disk without changing it in memory.
1417 // The memory index structure will be changed after the db commits.
1420 CDiskBlockIndex blockindexPrev(pindex->pprev);
1421 blockindexPrev.hashNext = 0;
1422 if (!txdb.WriteBlockIndex(blockindexPrev))
1423 return error("DisconnectBlock() : WriteBlockIndex failed");
1429 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1431 // Check it again in case a previous version let a bad block in
1435 //// issue here: it doesn't know the version
1436 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1438 map<uint256, CTxIndex> mapUnused;
1440 BOOST_FOREACH(CTransaction& tx, vtx)
1442 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1443 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1445 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1449 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1452 // Update block index on disk without changing it in memory.
1453 // The memory index structure will be changed after the db commits.
1456 CDiskBlockIndex blockindexPrev(pindex->pprev);
1457 blockindexPrev.hashNext = pindex->GetBlockHash();
1458 if (!txdb.WriteBlockIndex(blockindexPrev))
1459 return error("ConnectBlock() : WriteBlockIndex failed");
1462 // Watch for transactions paying to me
1463 BOOST_FOREACH(CTransaction& tx, vtx)
1464 AddToWalletIfInvolvingMe(tx, this, true);
1469 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1471 printf("REORGANIZE\n");
1474 CBlockIndex* pfork = pindexBest;
1475 CBlockIndex* plonger = pindexNew;
1476 while (pfork != plonger)
1478 while (plonger->nHeight > pfork->nHeight)
1479 if (!(plonger = plonger->pprev))
1480 return error("Reorganize() : plonger->pprev is null");
1481 if (pfork == plonger)
1483 if (!(pfork = pfork->pprev))
1484 return error("Reorganize() : pfork->pprev is null");
1487 // List of what to disconnect
1488 vector<CBlockIndex*> vDisconnect;
1489 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1490 vDisconnect.push_back(pindex);
1492 // List of what to connect
1493 vector<CBlockIndex*> vConnect;
1494 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1495 vConnect.push_back(pindex);
1496 reverse(vConnect.begin(), vConnect.end());
1498 // Disconnect shorter branch
1499 vector<CTransaction> vResurrect;
1500 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1503 if (!block.ReadFromDisk(pindex))
1504 return error("Reorganize() : ReadFromDisk for disconnect failed");
1505 if (!block.DisconnectBlock(txdb, pindex))
1506 return error("Reorganize() : DisconnectBlock failed");
1508 // Queue memory transactions to resurrect
1509 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1510 if (!tx.IsCoinBase())
1511 vResurrect.push_back(tx);
1514 // Connect longer branch
1515 vector<CTransaction> vDelete;
1516 for (int i = 0; i < vConnect.size(); i++)
1518 CBlockIndex* pindex = vConnect[i];
1520 if (!block.ReadFromDisk(pindex))
1521 return error("Reorganize() : ReadFromDisk for connect failed");
1522 if (!block.ConnectBlock(txdb, pindex))
1526 return error("Reorganize() : ConnectBlock failed");
1529 // Queue memory transactions to delete
1530 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1531 vDelete.push_back(tx);
1533 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1534 return error("Reorganize() : WriteHashBestChain failed");
1536 // Make sure it's successfully written to disk before changing memory structure
1537 if (!txdb.TxnCommit())
1538 return error("Reorganize() : TxnCommit failed");
1540 // Disconnect shorter branch
1541 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1543 pindex->pprev->pnext = NULL;
1545 // Connect longer branch
1546 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1548 pindex->pprev->pnext = pindex;
1550 // Resurrect memory transactions that were in the disconnected branch
1551 BOOST_FOREACH(CTransaction& tx, vResurrect)
1552 tx.AcceptToMemoryPool(txdb, false);
1554 // Delete redundant memory transactions that are in the connected branch
1555 BOOST_FOREACH(CTransaction& tx, vDelete)
1556 tx.RemoveFromMemoryPool();
1562 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1564 uint256 hash = GetHash();
1567 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1569 txdb.WriteHashBestChain(hash);
1570 if (!txdb.TxnCommit())
1571 return error("SetBestChain() : TxnCommit failed");
1572 pindexGenesisBlock = pindexNew;
1574 else if (hashPrevBlock == hashBestChain)
1576 // Adding to current best branch
1577 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1580 InvalidChainFound(pindexNew);
1581 return error("SetBestChain() : ConnectBlock failed");
1583 if (!txdb.TxnCommit())
1584 return error("SetBestChain() : TxnCommit failed");
1586 // Add to current best branch
1587 pindexNew->pprev->pnext = pindexNew;
1589 // Delete redundant memory transactions
1590 BOOST_FOREACH(CTransaction& tx, vtx)
1591 tx.RemoveFromMemoryPool();
1596 if (!Reorganize(txdb, pindexNew))
1599 InvalidChainFound(pindexNew);
1600 return error("SetBestChain() : Reorganize failed");
1604 // Update best block in wallet (so we can detect restored wallets)
1605 if (!IsInitialBlockDownload())
1608 const CBlockLocator locator(pindexNew);
1609 if (!walletdb.WriteBestBlock(locator))
1610 return error("SetBestChain() : WriteWalletBest failed");
1614 hashBestChain = hash;
1615 pindexBest = pindexNew;
1616 nBestHeight = pindexBest->nHeight;
1617 bnBestChainWork = pindexNew->bnChainWork;
1618 nTimeBestReceived = GetTime();
1619 nTransactionsUpdated++;
1620 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1626 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1628 // Check for duplicate
1629 uint256 hash = GetHash();
1630 if (mapBlockIndex.count(hash))
1631 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1633 // Construct new block index object
1634 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1636 return error("AddToBlockIndex() : new CBlockIndex failed");
1637 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1638 pindexNew->phashBlock = &((*mi).first);
1639 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1640 if (miPrev != mapBlockIndex.end())
1642 pindexNew->pprev = (*miPrev).second;
1643 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1645 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1649 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1650 if (!txdb.TxnCommit())
1654 if (pindexNew->bnChainWork > bnBestChainWork)
1655 if (!SetBestChain(txdb, pindexNew))
1660 if (pindexNew == pindexBest)
1662 // Notify UI to display prev block's coinbase if it was ours
1663 static uint256 hashPrevBestCoinBase;
1664 CRITICAL_BLOCK(cs_mapWallet)
1665 vWalletUpdated.push_back(hashPrevBestCoinBase);
1666 hashPrevBestCoinBase = vtx[0].GetHash();
1676 bool CBlock::CheckBlock() const
1678 // These are checks that are independent of context
1679 // that can be verified before saving an orphan block.
1682 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1683 return error("CheckBlock() : size limits failed");
1685 // Check proof of work matches claimed amount
1686 if (!CheckProofOfWork(GetHash(), nBits))
1687 return error("CheckBlock() : proof of work failed");
1690 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1691 return error("CheckBlock() : block timestamp too far in the future");
1693 // First transaction must be coinbase, the rest must not be
1694 if (vtx.empty() || !vtx[0].IsCoinBase())
1695 return error("CheckBlock() : first tx is not coinbase");
1696 for (int i = 1; i < vtx.size(); i++)
1697 if (vtx[i].IsCoinBase())
1698 return error("CheckBlock() : more than one coinbase");
1700 // Check transactions
1701 BOOST_FOREACH(const CTransaction& tx, vtx)
1702 if (!tx.CheckTransaction())
1703 return error("CheckBlock() : CheckTransaction failed");
1705 // Check that it's not full of nonstandard transactions
1706 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1707 return error("CheckBlock() : too many nonstandard transactions");
1710 if (hashMerkleRoot != BuildMerkleTree())
1711 return error("CheckBlock() : hashMerkleRoot mismatch");
1716 bool CBlock::AcceptBlock()
1718 // Check for duplicate
1719 uint256 hash = GetHash();
1720 if (mapBlockIndex.count(hash))
1721 return error("AcceptBlock() : block already in mapBlockIndex");
1723 // Get prev block index
1724 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1725 if (mi == mapBlockIndex.end())
1726 return error("AcceptBlock() : prev block not found");
1727 CBlockIndex* pindexPrev = (*mi).second;
1728 int nHeight = pindexPrev->nHeight+1;
1730 // Check proof of work
1731 if (nBits != GetNextWorkRequired(pindexPrev))
1732 return error("AcceptBlock() : incorrect proof of work");
1734 // Check timestamp against prev
1735 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1736 return error("AcceptBlock() : block's timestamp is too early");
1738 // Check that all transactions are finalized
1739 BOOST_FOREACH(const CTransaction& tx, vtx)
1740 if (!tx.IsFinal(nHeight, GetBlockTime()))
1741 return error("AcceptBlock() : contains a non-final transaction");
1743 // Check that the block chain matches the known block chain up to a checkpoint
1745 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1746 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1747 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1748 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1749 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1750 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1751 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))
1752 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1754 // Write block to history file
1755 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1756 return error("AcceptBlock() : out of disk space");
1757 unsigned int nFile = -1;
1758 unsigned int nBlockPos = 0;
1759 if (!WriteToDisk(nFile, nBlockPos))
1760 return error("AcceptBlock() : WriteToDisk failed");
1761 if (!AddToBlockIndex(nFile, nBlockPos))
1762 return error("AcceptBlock() : AddToBlockIndex failed");
1764 // Relay inventory, but don't relay old inventory during initial block download
1765 if (hashBestChain == hash)
1766 CRITICAL_BLOCK(cs_vNodes)
1767 BOOST_FOREACH(CNode* pnode, vNodes)
1768 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
1769 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1774 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1776 // Check for duplicate
1777 uint256 hash = pblock->GetHash();
1778 if (mapBlockIndex.count(hash))
1779 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1780 if (mapOrphanBlocks.count(hash))
1781 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1783 // Preliminary checks
1784 if (!pblock->CheckBlock())
1785 return error("ProcessBlock() : CheckBlock FAILED");
1787 // If don't already have its previous block, shunt it off to holding area until we get it
1788 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1790 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1791 CBlock* pblock2 = new CBlock(*pblock);
1792 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1793 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1795 // Ask this guy to fill in what we're missing
1797 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1802 if (!pblock->AcceptBlock())
1803 return error("ProcessBlock() : AcceptBlock FAILED");
1805 // Recursively process any orphan blocks that depended on this one
1806 vector<uint256> vWorkQueue;
1807 vWorkQueue.push_back(hash);
1808 for (int i = 0; i < vWorkQueue.size(); i++)
1810 uint256 hashPrev = vWorkQueue[i];
1811 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1812 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1815 CBlock* pblockOrphan = (*mi).second;
1816 if (pblockOrphan->AcceptBlock())
1817 vWorkQueue.push_back(pblockOrphan->GetHash());
1818 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1819 delete pblockOrphan;
1821 mapOrphanBlocksByPrev.erase(hashPrev);
1824 printf("ProcessBlock: ACCEPTED\n");
1835 template<typename Stream>
1836 bool ScanMessageStart(Stream& s)
1838 // Scan ahead to the next pchMessageStart, which should normally be immediately
1839 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1841 short prevmask = s.exceptions(0);
1842 const char* p = BEGIN(pchMessageStart);
1852 s.exceptions(prevmask);
1856 p = BEGIN(pchMessageStart);
1859 if (++p == END(pchMessageStart))
1862 s.exceptions(prevmask);
1871 s.exceptions(prevmask);
1876 bool CheckDiskSpace(uint64 nAdditionalBytes)
1878 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1880 // Check for 15MB because database could create another 10MB log file at any time
1881 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1884 string strMessage = _("Warning: Disk space is low ");
1885 strMiscWarning = strMessage;
1886 printf("*** %s\n", strMessage.c_str());
1887 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1888 CreateThread(Shutdown, NULL);
1894 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1898 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1901 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1903 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1912 static unsigned int nCurrentBlockFile = 1;
1914 FILE* AppendBlockFile(unsigned int& nFileRet)
1919 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1922 if (fseek(file, 0, SEEK_END) != 0)
1924 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1925 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1927 nFileRet = nCurrentBlockFile;
1931 nCurrentBlockFile++;
1935 bool LoadBlockIndex(bool fAllowNew)
1939 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1940 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1941 pchMessageStart[0] = 0xfa;
1942 pchMessageStart[1] = 0xbf;
1943 pchMessageStart[2] = 0xb5;
1944 pchMessageStart[3] = 0xda;
1951 if (!txdb.LoadBlockIndex())
1956 // Init with genesis block
1958 if (mapBlockIndex.empty())
1964 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1965 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1966 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1967 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1968 // vMerkleTree: 4a5e1e
1971 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1973 txNew.vin.resize(1);
1974 txNew.vout.resize(1);
1975 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1976 txNew.vout[0].nValue = 50 * COIN;
1977 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1979 block.vtx.push_back(txNew);
1980 block.hashPrevBlock = 0;
1981 block.hashMerkleRoot = block.BuildMerkleTree();
1983 block.nTime = 1231006505;
1984 block.nBits = 0x1d00ffff;
1985 block.nNonce = 2083236893;
1989 block.nTime = 1296688602;
1990 block.nBits = 0x1d07fff8;
1991 block.nNonce = 384568319;
1995 printf("%s\n", block.GetHash().ToString().c_str());
1996 printf("%s\n", hashGenesisBlock.ToString().c_str());
1997 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1998 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2000 assert(block.GetHash() == hashGenesisBlock);
2002 // Start new block file
2004 unsigned int nBlockPos;
2005 if (!block.WriteToDisk(nFile, nBlockPos))
2006 return error("LoadBlockIndex() : writing genesis block to disk failed");
2007 if (!block.AddToBlockIndex(nFile, nBlockPos))
2008 return error("LoadBlockIndex() : genesis block not accepted");
2016 void PrintBlockTree()
2018 // precompute tree structure
2019 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2020 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2022 CBlockIndex* pindex = (*mi).second;
2023 mapNext[pindex->pprev].push_back(pindex);
2025 //while (rand() % 3 == 0)
2026 // mapNext[pindex->pprev].push_back(pindex);
2029 vector<pair<int, CBlockIndex*> > vStack;
2030 vStack.push_back(make_pair(0, pindexGenesisBlock));
2033 while (!vStack.empty())
2035 int nCol = vStack.back().first;
2036 CBlockIndex* pindex = vStack.back().second;
2039 // print split or gap
2040 if (nCol > nPrevCol)
2042 for (int i = 0; i < nCol-1; i++)
2046 else if (nCol < nPrevCol)
2048 for (int i = 0; i < nCol; i++)
2055 for (int i = 0; i < nCol; i++)
2060 block.ReadFromDisk(pindex);
2061 printf("%d (%u,%u) %s %s tx %d",
2065 block.GetHash().ToString().substr(0,20).c_str(),
2066 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2069 CRITICAL_BLOCK(cs_mapWallet)
2071 if (mapWallet.count(block.vtx[0].GetHash()))
2073 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2074 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2080 // put the main timechain first
2081 vector<CBlockIndex*>& vNext = mapNext[pindex];
2082 for (int i = 0; i < vNext.size(); i++)
2084 if (vNext[i]->pnext)
2086 swap(vNext[0], vNext[i]);
2092 for (int i = 0; i < vNext.size(); i++)
2093 vStack.push_back(make_pair(nCol+i, vNext[i]));
2106 //////////////////////////////////////////////////////////////////////////////
2111 map<uint256, CAlert> mapAlerts;
2112 CCriticalSection cs_mapAlerts;
2114 string GetWarnings(string strFor)
2117 string strStatusBar;
2119 if (GetBoolArg("-testsafemode"))
2122 // Misc warnings like out of disk space and clock is wrong
2123 if (strMiscWarning != "")
2126 strStatusBar = strMiscWarning;
2129 // Longer invalid proof-of-work chain
2130 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2133 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2137 CRITICAL_BLOCK(cs_mapAlerts)
2139 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2141 const CAlert& alert = item.second;
2142 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2144 nPriority = alert.nPriority;
2145 strStatusBar = alert.strStatusBar;
2150 if (strFor == "statusbar")
2151 return strStatusBar;
2152 else if (strFor == "rpc")
2154 assert(("GetWarnings() : invalid parameter", false));
2158 bool CAlert::ProcessAlert()
2160 if (!CheckSignature())
2165 CRITICAL_BLOCK(cs_mapAlerts)
2167 // Cancel previous alerts
2168 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2170 const CAlert& alert = (*mi).second;
2173 printf("cancelling alert %d\n", alert.nID);
2174 mapAlerts.erase(mi++);
2176 else if (!alert.IsInEffect())
2178 printf("expiring alert %d\n", alert.nID);
2179 mapAlerts.erase(mi++);
2185 // Check if this alert has been cancelled
2186 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2188 const CAlert& alert = item.second;
2189 if (alert.Cancels(*this))
2191 printf("alert already cancelled by %d\n", alert.nID);
2197 mapAlerts.insert(make_pair(GetHash(), *this));
2200 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2212 //////////////////////////////////////////////////////////////////////////////
2218 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2222 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2223 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2225 // Don't know what it is, just say we already got one
2232 // The message start string is designed to be unlikely to occur in normal data.
2233 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2234 // a large 4-byte int at any alignment.
2235 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2238 bool ProcessMessages(CNode* pfrom)
2240 CDataStream& vRecv = pfrom->vRecv;
2244 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2248 // (4) message start
2257 // Scan for message start
2258 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2259 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2260 if (vRecv.end() - pstart < nHeaderSize)
2262 if (vRecv.size() > nHeaderSize)
2264 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2265 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2269 if (pstart - vRecv.begin() > 0)
2270 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2271 vRecv.erase(vRecv.begin(), pstart);
2274 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2279 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2282 string strCommand = hdr.GetCommand();
2285 unsigned int nMessageSize = hdr.nMessageSize;
2286 if (nMessageSize > MAX_SIZE)
2288 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2291 if (nMessageSize > vRecv.size())
2293 // Rewind and wait for rest of message
2294 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2299 if (vRecv.GetVersion() >= 209)
2301 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2302 unsigned int nChecksum = 0;
2303 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2304 if (nChecksum != hdr.nChecksum)
2306 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2307 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2312 // Copy message to its own buffer
2313 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2314 vRecv.ignore(nMessageSize);
2320 CRITICAL_BLOCK(cs_main)
2321 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2325 catch (std::ios_base::failure& e)
2327 if (strstr(e.what(), "end of data"))
2329 // Allow exceptions from underlength message on vRecv
2330 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());
2332 else if (strstr(e.what(), "size too large"))
2334 // Allow exceptions from overlong size
2335 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2339 PrintExceptionContinue(&e, "ProcessMessage()");
2342 catch (std::exception& e) {
2343 PrintExceptionContinue(&e, "ProcessMessage()");
2345 PrintExceptionContinue(NULL, "ProcessMessage()");
2349 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2359 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2361 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2362 RandAddSeedPerfmon();
2364 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2365 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2366 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2368 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2376 if (strCommand == "version")
2378 // Each connection can only send one version message
2379 if (pfrom->nVersion != 0)
2386 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2387 if (pfrom->nVersion == 10300)
2388 pfrom->nVersion = 300;
2389 if (pfrom->nVersion >= 106 && !vRecv.empty())
2390 vRecv >> addrFrom >> nNonce;
2391 if (pfrom->nVersion >= 106 && !vRecv.empty())
2392 vRecv >> pfrom->strSubVer;
2393 if (pfrom->nVersion >= 209 && !vRecv.empty())
2394 vRecv >> pfrom->nStartingHeight;
2396 if (pfrom->nVersion == 0)
2399 // Disconnect if we connected to ourself
2400 if (nNonce == nLocalHostNonce && nNonce > 1)
2402 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2403 pfrom->fDisconnect = true;
2407 // Be shy and don't send version until we hear
2408 if (pfrom->fInbound)
2409 pfrom->PushVersion();
2411 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2413 AddTimeData(pfrom->addr.ip, nTime);
2416 if (pfrom->nVersion >= 209)
2417 pfrom->PushMessage("verack");
2418 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2419 if (pfrom->nVersion < 209)
2420 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2422 if (!pfrom->fInbound)
2424 // Advertise our address
2425 if (addrLocalHost.IsRoutable() && !fUseProxy)
2427 CAddress addr(addrLocalHost);
2428 addr.nTime = GetAdjustedTime();
2429 pfrom->PushAddress(addr);
2432 // Get recent addresses
2433 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2435 pfrom->PushMessage("getaddr");
2436 pfrom->fGetAddr = true;
2440 // Ask the first connected node for block updates
2441 static int nAskedForBlocks;
2442 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2445 pfrom->PushGetBlocks(pindexBest, uint256(0));
2449 CRITICAL_BLOCK(cs_mapAlerts)
2450 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2451 item.second.RelayTo(pfrom);
2453 pfrom->fSuccessfullyConnected = true;
2455 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2459 else if (pfrom->nVersion == 0)
2461 // Must have a version message before anything else
2466 else if (strCommand == "verack")
2468 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2472 else if (strCommand == "addr")
2474 vector<CAddress> vAddr;
2477 // Don't want addr from older versions unless seeding
2478 if (pfrom->nVersion < 209)
2480 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2482 if (vAddr.size() > 1000)
2483 return error("message addr size() = %d", vAddr.size());
2485 // Store the new addresses
2486 int64 nNow = GetAdjustedTime();
2487 int64 nSince = nNow - 10 * 60;
2488 BOOST_FOREACH(CAddress& addr, vAddr)
2492 // ignore IPv6 for now, since it isn't implemented anyway
2495 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2496 addr.nTime = nNow - 5 * 24 * 60 * 60;
2497 AddAddress(addr, 2 * 60 * 60);
2498 pfrom->AddAddressKnown(addr);
2499 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2501 // Relay to a limited number of other nodes
2502 CRITICAL_BLOCK(cs_vNodes)
2504 // Use deterministic randomness to send to the same nodes for 24 hours
2505 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2506 static uint256 hashSalt;
2508 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2509 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2510 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2511 multimap<uint256, CNode*> mapMix;
2512 BOOST_FOREACH(CNode* pnode, vNodes)
2514 if (pnode->nVersion < 31402)
2516 unsigned int nPointer;
2517 memcpy(&nPointer, &pnode, sizeof(nPointer));
2518 uint256 hashKey = hashRand ^ nPointer;
2519 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2520 mapMix.insert(make_pair(hashKey, pnode));
2522 int nRelayNodes = 2;
2523 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2524 ((*mi).second)->PushAddress(addr);
2528 if (vAddr.size() < 1000)
2529 pfrom->fGetAddr = false;
2533 else if (strCommand == "inv")
2537 if (vInv.size() > 50000)
2538 return error("message inv size() = %d", vInv.size());
2541 BOOST_FOREACH(const CInv& inv, vInv)
2545 pfrom->AddInventoryKnown(inv);
2547 bool fAlreadyHave = AlreadyHave(txdb, inv);
2548 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2552 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2553 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2555 // Track requests for our stuff
2556 CRITICAL_BLOCK(cs_mapRequestCount)
2558 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2559 if (mi != mapRequestCount.end())
2566 else if (strCommand == "getdata")
2570 if (vInv.size() > 50000)
2571 return error("message getdata size() = %d", vInv.size());
2573 BOOST_FOREACH(const CInv& inv, vInv)
2577 printf("received getdata for: %s\n", inv.ToString().c_str());
2579 if (inv.type == MSG_BLOCK)
2581 // Send block from disk
2582 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2583 if (mi != mapBlockIndex.end())
2586 block.ReadFromDisk((*mi).second);
2587 pfrom->PushMessage("block", block);
2589 // Trigger them to send a getblocks request for the next batch of inventory
2590 if (inv.hash == pfrom->hashContinue)
2592 // Bypass PushInventory, this must send even if redundant,
2593 // and we want it right after the last block so they don't
2594 // wait for other stuff first.
2596 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2597 pfrom->PushMessage("inv", vInv);
2598 pfrom->hashContinue = 0;
2602 else if (inv.IsKnownType())
2604 // Send stream from relay memory
2605 CRITICAL_BLOCK(cs_mapRelay)
2607 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2608 if (mi != mapRelay.end())
2609 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2613 // Track requests for our stuff
2614 CRITICAL_BLOCK(cs_mapRequestCount)
2616 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2617 if (mi != mapRequestCount.end())
2624 else if (strCommand == "getblocks")
2626 CBlockLocator locator;
2628 vRecv >> locator >> hashStop;
2630 // Find the last block the caller has in the main chain
2631 CBlockIndex* pindex = locator.GetBlockIndex();
2633 // Send the rest of the chain
2635 pindex = pindex->pnext;
2636 int nLimit = 500 + locator.GetDistanceBack();
2637 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2638 for (; pindex; pindex = pindex->pnext)
2640 if (pindex->GetBlockHash() == hashStop)
2642 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2645 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2648 // When this block is requested, we'll send an inv that'll make them
2649 // getblocks the next batch of inventory.
2650 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2651 pfrom->hashContinue = pindex->GetBlockHash();
2658 else if (strCommand == "getheaders")
2660 CBlockLocator locator;
2662 vRecv >> locator >> hashStop;
2664 CBlockIndex* pindex = NULL;
2665 if (locator.IsNull())
2667 // If locator is null, return the hashStop block
2668 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2669 if (mi == mapBlockIndex.end())
2671 pindex = (*mi).second;
2675 // Find the last block the caller has in the main chain
2676 pindex = locator.GetBlockIndex();
2678 pindex = pindex->pnext;
2681 vector<CBlock> vHeaders;
2682 int nLimit = 2000 + locator.GetDistanceBack();
2683 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2684 for (; pindex; pindex = pindex->pnext)
2686 vHeaders.push_back(pindex->GetBlockHeader());
2687 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2690 pfrom->PushMessage("headers", vHeaders);
2694 else if (strCommand == "tx")
2696 vector<uint256> vWorkQueue;
2697 CDataStream vMsg(vRecv);
2701 CInv inv(MSG_TX, tx.GetHash());
2702 pfrom->AddInventoryKnown(inv);
2704 bool fMissingInputs = false;
2705 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2707 AddToWalletIfInvolvingMe(tx, NULL, true);
2708 RelayMessage(inv, vMsg);
2709 mapAlreadyAskedFor.erase(inv);
2710 vWorkQueue.push_back(inv.hash);
2712 // Recursively process any orphan transactions that depended on this one
2713 for (int i = 0; i < vWorkQueue.size(); i++)
2715 uint256 hashPrev = vWorkQueue[i];
2716 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2717 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2720 const CDataStream& vMsg = *((*mi).second);
2722 CDataStream(vMsg) >> tx;
2723 CInv inv(MSG_TX, tx.GetHash());
2725 if (tx.AcceptToMemoryPool(true))
2727 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2728 AddToWalletIfInvolvingMe(tx, NULL, true);
2729 RelayMessage(inv, vMsg);
2730 mapAlreadyAskedFor.erase(inv);
2731 vWorkQueue.push_back(inv.hash);
2736 BOOST_FOREACH(uint256 hash, vWorkQueue)
2737 EraseOrphanTx(hash);
2739 else if (fMissingInputs)
2741 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2747 else if (strCommand == "block")
2752 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2755 CInv inv(MSG_BLOCK, block.GetHash());
2756 pfrom->AddInventoryKnown(inv);
2758 if (ProcessBlock(pfrom, &block))
2759 mapAlreadyAskedFor.erase(inv);
2763 else if (strCommand == "getaddr")
2765 // Nodes rebroadcast an addr every 24 hours
2766 pfrom->vAddrToSend.clear();
2767 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2768 CRITICAL_BLOCK(cs_mapAddresses)
2770 unsigned int nCount = 0;
2771 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2773 const CAddress& addr = item.second;
2774 if (addr.nTime > nSince)
2777 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2779 const CAddress& addr = item.second;
2780 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2781 pfrom->PushAddress(addr);
2787 else if (strCommand == "checkorder")
2792 if (!GetBoolArg("-allowreceivebyip"))
2794 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2801 /// we have a chance to check the order here
2803 // Keep giving the same key to the same ip until they use it
2804 if (!mapReuseKey.count(pfrom->addr.ip))
2805 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2807 // Send back approval of order and pubkey to use
2808 CScript scriptPubKey;
2809 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2810 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2814 else if (strCommand == "submitorder")
2819 if (!GetBoolArg("-allowreceivebyip"))
2821 pfrom->PushMessage("reply", hashReply, (int)2);
2827 wtxNew.fFromMe = false;
2830 if (!wtxNew.AcceptWalletTransaction())
2832 pfrom->PushMessage("reply", hashReply, (int)1);
2833 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2835 wtxNew.fTimeReceivedIsTxTime = true;
2836 AddToWallet(wtxNew);
2837 wtxNew.RelayWalletTransaction();
2838 mapReuseKey.erase(pfrom->addr.ip);
2840 // Send back confirmation
2841 pfrom->PushMessage("reply", hashReply, (int)0);
2845 else if (strCommand == "reply")
2850 CRequestTracker tracker;
2851 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2853 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2854 if (mi != pfrom->mapRequests.end())
2856 tracker = (*mi).second;
2857 pfrom->mapRequests.erase(mi);
2860 if (!tracker.IsNull())
2861 tracker.fn(tracker.param1, vRecv);
2865 else if (strCommand == "ping")
2870 else if (strCommand == "alert")
2875 if (alert.ProcessAlert())
2878 pfrom->setKnown.insert(alert.GetHash());
2879 CRITICAL_BLOCK(cs_vNodes)
2880 BOOST_FOREACH(CNode* pnode, vNodes)
2881 alert.RelayTo(pnode);
2888 // Ignore unknown commands for extensibility
2892 // Update the last seen time for this node's address
2893 if (pfrom->fNetworkNode)
2894 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2895 AddressCurrentlyConnected(pfrom->addr);
2909 bool SendMessages(CNode* pto, bool fSendTrickle)
2911 CRITICAL_BLOCK(cs_main)
2913 // Don't send anything until we get their version message
2914 if (pto->nVersion == 0)
2918 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2919 pto->PushMessage("ping");
2921 // Resend wallet transactions that haven't gotten in a block yet
2922 ResendWalletTransactions();
2924 // Address refresh broadcast
2925 static int64 nLastRebroadcast;
2926 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2928 nLastRebroadcast = GetTime();
2929 CRITICAL_BLOCK(cs_vNodes)
2931 BOOST_FOREACH(CNode* pnode, vNodes)
2933 // Periodically clear setAddrKnown to allow refresh broadcasts
2934 pnode->setAddrKnown.clear();
2936 // Rebroadcast our address
2937 if (addrLocalHost.IsRoutable() && !fUseProxy)
2939 CAddress addr(addrLocalHost);
2940 addr.nTime = GetAdjustedTime();
2941 pnode->PushAddress(addr);
2947 // Clear out old addresses periodically so it's not too much work at once
2948 static int64 nLastClear;
2949 if (nLastClear == 0)
2950 nLastClear = GetTime();
2951 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2953 nLastClear = GetTime();
2954 CRITICAL_BLOCK(cs_mapAddresses)
2957 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2958 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2959 mi != mapAddresses.end();)
2961 const CAddress& addr = (*mi).second;
2962 if (addr.nTime < nSince)
2964 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2966 addrdb.EraseAddress(addr);
2967 mapAddresses.erase(mi++);
2981 vector<CAddress> vAddr;
2982 vAddr.reserve(pto->vAddrToSend.size());
2983 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2985 // returns true if wasn't already contained in the set
2986 if (pto->setAddrKnown.insert(addr).second)
2988 vAddr.push_back(addr);
2989 // receiver rejects addr messages larger than 1000
2990 if (vAddr.size() >= 1000)
2992 pto->PushMessage("addr", vAddr);
2997 pto->vAddrToSend.clear();
2999 pto->PushMessage("addr", vAddr);
3004 // Message: inventory
3007 vector<CInv> vInvWait;
3008 CRITICAL_BLOCK(pto->cs_inventory)
3010 vInv.reserve(pto->vInventoryToSend.size());
3011 vInvWait.reserve(pto->vInventoryToSend.size());
3012 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3014 if (pto->setInventoryKnown.count(inv))
3017 // trickle out tx inv to protect privacy
3018 if (inv.type == MSG_TX && !fSendTrickle)
3020 // 1/4 of tx invs blast to all immediately
3021 static uint256 hashSalt;
3023 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
3024 uint256 hashRand = inv.hash ^ hashSalt;
3025 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3026 bool fTrickleWait = ((hashRand & 3) != 0);
3028 // always trickle our own transactions
3031 TRY_CRITICAL_BLOCK(cs_mapWallet)
3033 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
3034 if (mi != mapWallet.end())
3036 CWalletTx& wtx = (*mi).second;
3038 fTrickleWait = true;
3045 vInvWait.push_back(inv);
3050 // returns true if wasn't already contained in the set
3051 if (pto->setInventoryKnown.insert(inv).second)
3053 vInv.push_back(inv);
3054 if (vInv.size() >= 1000)
3056 pto->PushMessage("inv", vInv);
3061 pto->vInventoryToSend = vInvWait;
3064 pto->PushMessage("inv", vInv);
3070 vector<CInv> vGetData;
3071 int64 nNow = GetTime() * 1000000;
3073 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3075 const CInv& inv = (*pto->mapAskFor.begin()).second;
3076 if (!AlreadyHave(txdb, inv))
3078 printf("sending getdata: %s\n", inv.ToString().c_str());
3079 vGetData.push_back(inv);
3080 if (vGetData.size() >= 1000)
3082 pto->PushMessage("getdata", vGetData);
3086 pto->mapAskFor.erase(pto->mapAskFor.begin());
3088 if (!vGetData.empty())
3089 pto->PushMessage("getdata", vGetData);
3108 //////////////////////////////////////////////////////////////////////////////
3113 void GenerateBitcoins(bool fGenerate)
3115 if (fGenerateBitcoins != fGenerate)
3117 fGenerateBitcoins = fGenerate;
3118 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3121 if (fGenerateBitcoins)
3123 int nProcessors = boost::thread::hardware_concurrency();
3124 printf("%d processors\n", nProcessors);
3125 if (nProcessors < 1)
3127 if (fLimitProcessors && nProcessors > nLimitProcessors)
3128 nProcessors = nLimitProcessors;
3129 int nAddThreads = nProcessors - vnThreadsRunning[3];
3130 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3131 for (int i = 0; i < nAddThreads; i++)
3133 if (!CreateThread(ThreadBitcoinMiner, NULL))
3134 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3140 void ThreadBitcoinMiner(void* parg)
3144 vnThreadsRunning[3]++;
3146 vnThreadsRunning[3]--;
3148 catch (std::exception& e) {
3149 vnThreadsRunning[3]--;
3150 PrintException(&e, "ThreadBitcoinMiner()");
3152 vnThreadsRunning[3]--;
3153 PrintException(NULL, "ThreadBitcoinMiner()");
3155 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3157 if (vnThreadsRunning[3] == 0)
3159 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3163 int FormatHashBlocks(void* pbuffer, unsigned int len)
3165 unsigned char* pdata = (unsigned char*)pbuffer;
3166 unsigned int blocks = 1 + ((len + 8) / 64);
3167 unsigned char* pend = pdata + 64 * blocks;
3168 memset(pdata + len, 0, 64 * blocks - len);
3170 unsigned int bits = len * 8;
3171 pend[-1] = (bits >> 0) & 0xff;
3172 pend[-2] = (bits >> 8) & 0xff;
3173 pend[-3] = (bits >> 16) & 0xff;
3174 pend[-4] = (bits >> 24) & 0xff;
3178 using CryptoPP::ByteReverse;
3180 static const unsigned int pSHA256InitState[8] =
3181 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3183 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3185 memcpy(pstate, pinit, 32);
3186 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3190 // ScanHash scans nonces looking for a hash with at least some zero bits.
3191 // It operates on big endian data. Caller does the byte reversing.
3192 // All input buffers are 16-byte aligned. nNonce is usually preserved
3193 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3194 // the block is rebuilt and nNonce starts over at zero.
3196 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3198 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3202 // Hash pdata using pmidstate as the starting state into
3203 // preformatted buffer phash1, then hash phash1 into phash
3205 SHA256Transform(phash1, pdata, pmidstate);
3206 SHA256Transform(phash, phash1, pSHA256InitState);
3208 // Return the nonce if the hash has at least some zero bits,
3209 // caller will check if it has enough to reach the target
3210 if (((unsigned short*)phash)[14] == 0)
3213 // If nothing found after trying for a while, return -1
3214 if ((nNonce & 0xffff) == 0)
3216 nHashesDone = 0xffff+1;
3227 set<uint256> setDependsOn;
3230 COrphan(CTransaction* ptxIn)
3238 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3239 BOOST_FOREACH(uint256 hash, setDependsOn)
3240 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3245 CBlock* CreateNewBlock(CReserveKey& reservekey)
3247 CBlockIndex* pindexPrev = pindexBest;
3250 auto_ptr<CBlock> pblock(new CBlock());
3254 // Create coinbase tx
3256 txNew.vin.resize(1);
3257 txNew.vin[0].prevout.SetNull();
3258 txNew.vout.resize(1);
3259 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3261 // Add our coinbase tx as first transaction
3262 pblock->vtx.push_back(txNew);
3264 // Collect memory pool transactions into the block
3266 CRITICAL_BLOCK(cs_main)
3267 CRITICAL_BLOCK(cs_mapTransactions)
3271 // Priority order to process transactions
3272 list<COrphan> vOrphan; // list memory doesn't move
3273 map<uint256, vector<COrphan*> > mapDependers;
3274 multimap<double, CTransaction*> mapPriority;
3275 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3277 CTransaction& tx = (*mi).second;
3278 if (tx.IsCoinBase() || !tx.IsFinal())
3281 COrphan* porphan = NULL;
3282 double dPriority = 0;
3283 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3285 // Read prev transaction
3286 CTransaction txPrev;
3288 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3290 // Has to wait for dependencies
3293 // Use list for automatic deletion
3294 vOrphan.push_back(COrphan(&tx));
3295 porphan = &vOrphan.back();
3297 mapDependers[txin.prevout.hash].push_back(porphan);
3298 porphan->setDependsOn.insert(txin.prevout.hash);
3301 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3303 // Read block header
3304 int nConf = txindex.GetDepthInMainChain();
3306 dPriority += (double)nValueIn * nConf;
3308 if (fDebug && GetBoolArg("-printpriority"))
3309 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3312 // Priority is sum(valuein * age) / txsize
3313 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3316 porphan->dPriority = dPriority;
3318 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3320 if (fDebug && GetBoolArg("-printpriority"))
3322 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3329 // Collect transactions into block
3330 map<uint256, CTxIndex> mapTestPool;
3331 uint64 nBlockSize = 1000;
3332 int nBlockSigOps = 100;
3333 while (!mapPriority.empty())
3335 // Take highest priority transaction off priority queue
3336 double dPriority = -(*mapPriority.begin()).first;
3337 CTransaction& tx = *(*mapPriority.begin()).second;
3338 mapPriority.erase(mapPriority.begin());
3341 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3342 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3344 int nTxSigOps = tx.GetSigOpCount();
3345 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3348 // Transaction fee required depends on block size
3349 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3350 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
3352 // Connecting shouldn't fail due to dependency on other memory pool transactions
3353 // because we're already processing them in order of dependency
3354 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3355 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3357 swap(mapTestPool, mapTestPoolTmp);
3360 pblock->vtx.push_back(tx);
3361 nBlockSize += nTxSize;
3362 nBlockSigOps += nTxSigOps;
3364 // Add transactions that depend on this one to the priority queue
3365 uint256 hash = tx.GetHash();
3366 if (mapDependers.count(hash))
3368 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3370 if (!porphan->setDependsOn.empty())
3372 porphan->setDependsOn.erase(hash);
3373 if (porphan->setDependsOn.empty())
3374 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3380 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3383 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3384 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3385 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3386 pblock->nBits = GetNextWorkRequired(pindexPrev);
3389 return pblock.release();
3393 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3395 // Update nExtraNonce
3396 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3397 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3402 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3403 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3407 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3410 // Prebuild hash buffers
3417 uint256 hashPrevBlock;
3418 uint256 hashMerkleRoot;
3421 unsigned int nNonce;
3424 unsigned char pchPadding0[64];
3426 unsigned char pchPadding1[64];
3429 memset(&tmp, 0, sizeof(tmp));
3431 tmp.block.nVersion = pblock->nVersion;
3432 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3433 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3434 tmp.block.nTime = pblock->nTime;
3435 tmp.block.nBits = pblock->nBits;
3436 tmp.block.nNonce = pblock->nNonce;
3438 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3439 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3441 // Byte swap all the input buffer
3442 for (int i = 0; i < sizeof(tmp)/4; i++)
3443 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3445 // Precalc the first half of the first hash, which stays constant
3446 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3448 memcpy(pdata, &tmp.block, 128);
3449 memcpy(phash1, &tmp.hash1, 64);
3453 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3455 uint256 hash = pblock->GetHash();
3456 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3458 if (hash > hashTarget)
3462 printf("BitcoinMiner:\n");
3463 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3465 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3466 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3469 CRITICAL_BLOCK(cs_main)
3471 if (pblock->hashPrevBlock != hashBestChain)
3472 return error("BitcoinMiner : generated block is stale");
3474 // Remove key from key pool
3475 reservekey.KeepKey();
3477 // Track how many getdata requests this block gets
3478 CRITICAL_BLOCK(cs_mapRequestCount)
3479 mapRequestCount[pblock->GetHash()] = 0;
3481 // Process this block the same as if we had received it from another node
3482 if (!ProcessBlock(NULL, pblock))
3483 return error("BitcoinMiner : ProcessBlock, block not accepted");
3493 printf("BitcoinMiner started\n");
3494 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3496 // Each thread has its own key and counter
3497 CReserveKey reservekey;
3498 unsigned int nExtraNonce = 0;
3499 int64 nPrevTime = 0;
3501 while (fGenerateBitcoins)
3503 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3507 while (vNodes.empty() || IsInitialBlockDownload())
3512 if (!fGenerateBitcoins)
3520 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3521 CBlockIndex* pindexPrev = pindexBest;
3523 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3526 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3528 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3532 // Prebuild hash buffers
3534 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3535 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3536 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3538 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3540 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3541 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3547 int64 nStart = GetTime();
3548 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3550 uint256& hash = *alignup<16>(hashbuf);
3553 unsigned int nHashesDone = 0;
3554 unsigned int nNonceFound;
3557 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3558 (char*)&hash, nHashesDone);
3560 // Check if something found
3561 if (nNonceFound != -1)
3563 for (int i = 0; i < sizeof(hash)/4; i++)
3564 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3566 if (hash <= hashTarget)
3569 pblock->nNonce = ByteReverse(nNonceFound);
3570 assert(hash == pblock->GetHash());
3572 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3573 CheckWork(pblock.get(), reservekey);
3574 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3580 static int64 nHashCounter;
3581 if (nHPSTimerStart == 0)
3583 nHPSTimerStart = GetTimeMillis();
3587 nHashCounter += nHashesDone;
3588 if (GetTimeMillis() - nHPSTimerStart > 4000)
3590 static CCriticalSection cs;
3593 if (GetTimeMillis() - nHPSTimerStart > 4000)
3595 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3596 nHPSTimerStart = GetTimeMillis();
3598 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3599 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3600 static int64 nLogTime;
3601 if (GetTime() - nLogTime > 30 * 60)
3603 nLogTime = GetTime();
3604 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3605 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3611 // Check for stop or if block needs to be rebuilt
3614 if (!fGenerateBitcoins)
3616 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3620 if (nBlockNonce >= 0xffff0000)
3622 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3624 if (pindexPrev != pindexBest)
3627 // Update nTime every few seconds
3628 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3629 nBlockTime = ByteReverse(pblock->nTime);
3651 //////////////////////////////////////////////////////////////////////////////
3659 int64 nStart = GetTimeMillis();
3662 CRITICAL_BLOCK(cs_mapWallet)
3664 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3666 CWalletTx* pcoin = &(*it).second;
3667 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3669 nTotal += pcoin->GetAvailableCredit();
3673 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3678 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3680 setCoinsRet.clear();
3683 // List of values less than target
3684 pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;
3685 coinLowestLarger.first = INT64_MAX;
3686 coinLowestLarger.second.first = NULL;
3687 vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;
3688 int64 nTotalLower = 0;
3690 CRITICAL_BLOCK(cs_mapWallet)
3692 vector<CWalletTx*> vCoins;
3693 vCoins.reserve(mapWallet.size());
3694 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3695 vCoins.push_back(&(*it).second);
3696 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3698 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
3700 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3703 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3706 int nDepth = pcoin->GetDepthInMainChain();
3707 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3710 for (int i = 0; i < pcoin->vout.size(); i++)
3712 if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())
3715 int64 n = pcoin->vout[i].nValue;
3720 pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
3722 if (n == nTargetValue)
3724 setCoinsRet.insert(coin.second);
3725 nValueRet += coin.first;
3728 else if (n < nTargetValue + CENT)
3730 vValue.push_back(coin);
3733 else if (n < coinLowestLarger.first)
3735 coinLowestLarger = coin;
3741 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
3743 for (int i = 0; i < vValue.size(); ++i)
3745 setCoinsRet.insert(vValue[i].second);
3746 nValueRet += vValue[i].first;
3751 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
3753 if (coinLowestLarger.second.first == NULL)
3755 setCoinsRet.insert(coinLowestLarger.second);
3756 nValueRet += coinLowestLarger.first;
3760 if (nTotalLower >= nTargetValue + CENT)
3761 nTargetValue += CENT;
3763 // Solve subset sum by stochastic approximation
3764 sort(vValue.rbegin(), vValue.rend());
3765 vector<char> vfIncluded;
3766 vector<char> vfBest(vValue.size(), true);
3767 int64 nBest = nTotalLower;
3769 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3771 vfIncluded.assign(vValue.size(), false);
3773 bool fReachedTarget = false;
3774 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3776 for (int i = 0; i < vValue.size(); i++)
3778 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3780 nTotal += vValue[i].first;
3781 vfIncluded[i] = true;
3782 if (nTotal >= nTargetValue)
3784 fReachedTarget = true;
3788 vfBest = vfIncluded;
3790 nTotal -= vValue[i].first;
3791 vfIncluded[i] = false;
3798 // If the next larger is still closer, return it
3799 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
3801 setCoinsRet.insert(coinLowestLarger.second);
3802 nValueRet += coinLowestLarger.first;
3805 for (int i = 0; i < vValue.size(); i++)
3808 setCoinsRet.insert(vValue[i].second);
3809 nValueRet += vValue[i].first;
3813 printf("SelectCoins() best subset: ");
3814 for (int i = 0; i < vValue.size(); i++)
3816 printf("%s ", FormatMoney(vValue[i].first).c_str());
3817 printf("total %s\n", FormatMoney(nBest).c_str());
3823 bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3825 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
3826 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
3827 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
3833 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3836 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3842 if (vecSend.empty() || nValue < 0)
3845 CRITICAL_BLOCK(cs_main)
3847 // txdb must be opened before the mapWallet lock
3849 CRITICAL_BLOCK(cs_mapWallet)
3851 nFeeRet = nTransactionFee;
3855 wtxNew.vout.clear();
3856 wtxNew.fFromMe = true;
3858 int64 nTotalValue = nValue + nFeeRet;
3859 double dPriority = 0;
3860 // vouts to the payees
3861 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3862 wtxNew.vout.push_back(CTxOut(s.second, s.first));
3864 // Choose coins to use
3865 set<pair<CWalletTx*,unsigned int> > setCoins;
3867 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
3869 BOOST_FOREACH(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)
3871 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
3872 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
3875 int64 nChange = nValueIn - nValue - nFeeRet;
3877 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
3878 // or until nChange becomes zero
3879 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
3881 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
3882 nChange -= nMoveToFee;
3883 nFeeRet += nMoveToFee;
3888 // Note: We use a new key here to keep it from being obvious which side is the change.
3889 // The drawback is that by not reusing a previous key, the change may be lost if a
3890 // backup is restored, if the backup doesn't have the new private key for the change.
3891 // If we reused the old key, it would be possible to add code to look for and
3892 // rediscover unknown transactions that were written with keys of ours to recover
3893 // post-backup change.
3895 // Reserve a new key pair from key pool
3896 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3897 assert(mapKeys.count(vchPubKey));
3899 // Fill a vout to ourself, using same address type as the payment
3900 CScript scriptChange;
3901 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
3902 scriptChange.SetBitcoinAddress(vchPubKey);
3904 scriptChange << vchPubKey << OP_CHECKSIG;
3906 // Insert change txn at random position:
3907 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
3908 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
3911 reservekey.ReturnKey();
3914 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3915 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
3919 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3920 if (!SignSignature(*coin.first, wtxNew, nIn++))
3924 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3925 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3927 dPriority /= nBytes;
3929 // Check that enough fee is included
3930 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3931 bool fAllowFree = CTransaction::AllowFree(dPriority);
3932 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
3933 if (nFeeRet < max(nPayFee, nMinFee))
3935 nFeeRet = max(nPayFee, nMinFee);
3939 // Fill vtxPrev by copying from previous transactions vtxPrev
3940 wtxNew.AddSupportingTransactions(txdb);
3941 wtxNew.fTimeReceivedIsTxTime = true;
3950 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3952 vector< pair<CScript, int64> > vecSend;
3953 vecSend.push_back(make_pair(scriptPubKey, nValue));
3954 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
3957 // Call after CreateTransaction unless you want to abort
3958 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3960 CRITICAL_BLOCK(cs_main)
3962 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3963 CRITICAL_BLOCK(cs_mapWallet)
3965 // This is only to keep the database open to defeat the auto-flush for the
3966 // duration of this scope. This is the only place where this optimization
3967 // maybe makes sense; please don't do it anywhere else.
3968 CWalletDB walletdb("r");
3970 // Take key pair from key pool so it won't be used again
3971 reservekey.KeepKey();
3973 // Add tx to wallet, because if it has change it's also ours,
3974 // otherwise just for transaction history.
3975 AddToWallet(wtxNew);
3977 // Mark old coins as spent
3978 set<CWalletTx*> setCoins;
3979 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3981 CWalletTx &pcoin = mapWallet[txin.prevout.hash];
3982 pcoin.MarkSpent(txin.prevout.n);
3983 pcoin.WriteToDisk();
3984 vWalletUpdated.push_back(pcoin.GetHash());
3988 // Track how many getdata requests our transaction gets
3989 CRITICAL_BLOCK(cs_mapRequestCount)
3990 mapRequestCount[wtxNew.GetHash()] = 0;
3993 if (!wtxNew.AcceptToMemoryPool())
3995 // This must not fail. The transaction has already been signed and recorded.
3996 printf("CommitTransaction() : Error: Transaction not valid");
3999 wtxNew.RelayWalletTransaction();
4008 // requires cs_main lock
4009 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4011 CReserveKey reservekey;
4013 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
4016 if (nValue + nFeeRequired > GetBalance())
4017 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());
4019 strError = _("Error: Transaction creation failed ");
4020 printf("SendMoney() : %s", strError.c_str());
4024 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4027 if (!CommitTransaction(wtxNew, reservekey))
4028 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.");
4036 // requires cs_main lock
4037 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4041 return _("Invalid amount");
4042 if (nValue + nTransactionFee > GetBalance())
4043 return _("Insufficient funds");
4045 // Parse bitcoin address
4046 CScript scriptPubKey;
4047 if (!scriptPubKey.SetBitcoinAddress(strAddress))
4048 return _("Invalid bitcoin address");
4050 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);