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"
11 using namespace boost;
17 CCriticalSection cs_main;
19 map<uint256, CTransaction> mapTransactions;
20 CCriticalSection cs_mapTransactions;
21 unsigned int nTransactionsUpdated = 0;
22 map<COutPoint, CInPoint> mapNextTx;
24 map<uint256, CBlockIndex*> mapBlockIndex;
25 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
26 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
27 CBlockIndex* pindexGenesisBlock = NULL;
29 CBigNum bnBestChainWork = 0;
30 CBigNum bnBestInvalidWork = 0;
31 uint256 hashBestChain = 0;
32 CBlockIndex* pindexBest = NULL;
33 int64 nTimeBestReceived = 0;
35 map<uint256, CBlock*> mapOrphanBlocks;
36 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
38 map<uint256, CDataStream*> mapOrphanTransactions;
39 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
41 map<uint256, CWalletTx> mapWallet;
42 vector<uint256> vWalletUpdated;
43 CCriticalSection cs_mapWallet;
45 map<vector<unsigned char>, CPrivKey> mapKeys;
46 map<uint160, vector<unsigned char> > mapPubKeys;
47 CCriticalSection cs_mapKeys;
50 map<uint256, int> mapRequestCount;
51 CCriticalSection cs_mapRequestCount;
53 map<string, string> mapAddressBook;
54 CCriticalSection cs_mapAddressBook;
56 vector<unsigned char> vchDefaultKey;
62 int fGenerateBitcoins = false;
63 int64 nTransactionFee = 0;
64 CAddress addrIncoming;
65 int fLimitProcessors = false;
66 int nLimitProcessors = 1;
67 int fMinimizeToTray = true;
68 int fMinimizeOnClose = true;
81 //////////////////////////////////////////////////////////////////////////////
86 bool AddKey(const CKey& key)
88 CRITICAL_BLOCK(cs_mapKeys)
90 mapKeys[key.GetPubKey()] = key.GetPrivKey();
91 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
93 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
96 vector<unsigned char> GenerateNewKey()
102 throw runtime_error("GenerateNewKey() : AddKey failed");
103 return key.GetPubKey();
109 //////////////////////////////////////////////////////////////////////////////
114 bool AddToWallet(const CWalletTx& wtxIn)
116 uint256 hash = wtxIn.GetHash();
117 CRITICAL_BLOCK(cs_mapWallet)
119 // Inserts only if not already there, returns tx inserted or tx found
120 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
121 CWalletTx& wtx = (*ret.first).second;
122 bool fInsertedNew = ret.second;
124 wtx.nTimeReceived = GetAdjustedTime();
126 bool fUpdated = false;
130 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
132 wtx.hashBlock = wtxIn.hashBlock;
135 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
137 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
138 wtx.nIndex = wtxIn.nIndex;
141 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
143 wtx.fFromMe = wtxIn.fFromMe;
146 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
150 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
153 if (fInsertedNew || fUpdated)
154 if (!wtx.WriteToDisk())
157 // If default receiving address gets used, replace it with a new one
158 CScript scriptDefaultKey;
159 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
160 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
162 if (txout.scriptPubKey == scriptDefaultKey)
165 vchDefaultKey = GetKeyFromKeyPool();
166 walletdb.WriteDefaultKey(vchDefaultKey);
167 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
172 vWalletUpdated.push_back(hash);
180 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false)
182 uint256 hash = tx.GetHash();
183 bool fExisted = mapWallet.count(hash);
184 if (fExisted && !fUpdate) return false;
185 if (fExisted || tx.IsMine() || tx.IsFromMe())
188 // Get merkle branch if transaction was found in a block
190 wtx.SetMerkleBranch(pblock);
191 return AddToWallet(wtx);
196 bool EraseFromWallet(uint256 hash)
198 CRITICAL_BLOCK(cs_mapWallet)
200 if (mapWallet.erase(hash))
201 CWalletDB().EraseTx(hash);
206 void WalletUpdateSpent(const COutPoint& prevout)
208 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
209 // Update the wallet spent flag if it doesn't know due to wallet.dat being
210 // restored from backup or the user making copies of wallet.dat.
211 CRITICAL_BLOCK(cs_mapWallet)
213 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
214 if (mi != mapWallet.end())
216 CWalletTx& wtx = (*mi).second;
217 if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())
219 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
220 wtx.MarkSpent(prevout.n);
222 vWalletUpdated.push_back(prevout.hash);
235 //////////////////////////////////////////////////////////////////////////////
237 // mapOrphanTransactions
240 void AddOrphanTx(const CDataStream& vMsg)
243 CDataStream(vMsg) >> tx;
244 uint256 hash = tx.GetHash();
245 if (mapOrphanTransactions.count(hash))
247 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
248 BOOST_FOREACH(const CTxIn& txin, tx.vin)
249 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
252 void EraseOrphanTx(uint256 hash)
254 if (!mapOrphanTransactions.count(hash))
256 const CDataStream* pvMsg = mapOrphanTransactions[hash];
258 CDataStream(*pvMsg) >> tx;
259 BOOST_FOREACH(const CTxIn& txin, tx.vin)
261 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
262 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
264 if ((*mi).second == pvMsg)
265 mapOrphanTransactionsByPrev.erase(mi++);
271 mapOrphanTransactions.erase(hash);
281 //////////////////////////////////////////////////////////////////////////////
283 // CTransaction and CTxIndex
286 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
289 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
291 if (!ReadFromDisk(txindexRet.pos))
293 if (prevout.n >= vout.size())
301 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
304 return ReadFromDisk(txdb, prevout, txindex);
307 bool CTransaction::ReadFromDisk(COutPoint prevout)
311 return ReadFromDisk(txdb, prevout, txindex);
314 bool CTxIn::IsMine() const
316 CRITICAL_BLOCK(cs_mapWallet)
318 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
319 if (mi != mapWallet.end())
321 const CWalletTx& prev = (*mi).second;
322 if (prevout.n < prev.vout.size())
323 if (prev.vout[prevout.n].IsMine())
330 int64 CTxIn::GetDebit() const
332 CRITICAL_BLOCK(cs_mapWallet)
334 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
335 if (mi != mapWallet.end())
337 const CWalletTx& prev = (*mi).second;
338 if (prevout.n < prev.vout.size())
339 if (prev.vout[prevout.n].IsMine())
340 return prev.vout[prevout.n].nValue;
346 int64 CWalletTx::GetTxTime() const
348 if (!fTimeReceivedIsTxTime && hashBlock != 0)
350 // If we did not receive the transaction directly, we rely on the block's
351 // time to figure out when it happened. We use the median over a range
352 // of blocks to try to filter out inaccurate block times.
353 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
354 if (mi != mapBlockIndex.end())
356 CBlockIndex* pindex = (*mi).second;
358 return pindex->GetMedianTime();
361 return nTimeReceived;
364 int CWalletTx::GetRequestCount() const
366 // Returns -1 if it wasn't being tracked
368 CRITICAL_BLOCK(cs_mapRequestCount)
375 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
376 if (mi != mapRequestCount.end())
377 nRequests = (*mi).second;
382 // Did anyone request this transaction?
383 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
384 if (mi != mapRequestCount.end())
386 nRequests = (*mi).second;
388 // How about the block it's in?
389 if (nRequests == 0 && hashBlock != 0)
391 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
392 if (mi != mapRequestCount.end())
393 nRequests = (*mi).second;
395 nRequests = 1; // If it's in someone else's block it must have got out
403 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
404 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
406 nGeneratedImmature = nGeneratedMature = nFee = 0;
407 listReceived.clear();
409 strSentAccount = strFromAccount;
413 if (GetBlocksToMaturity() > 0)
414 nGeneratedImmature = CTransaction::GetCredit();
416 nGeneratedMature = GetCredit();
421 int64 nDebit = GetDebit();
422 if (nDebit > 0) // debit>0 means we signed/sent this transaction
424 int64 nValueOut = GetValueOut();
425 nFee = nDebit - nValueOut;
428 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
429 // but non-standard clients might (so return a list of address/amount pairs)
430 BOOST_FOREACH(const CTxOut& txout, vout)
434 vector<unsigned char> vchPubKey;
435 if (ExtractHash160(txout.scriptPubKey, hash160))
436 address = Hash160ToAddress(hash160);
437 else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))
438 address = PubKeyToAddress(vchPubKey);
441 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
442 this->GetHash().ToString().c_str());
443 address = " unknown ";
446 // Don't report 'change' txouts
447 if (nDebit > 0 && txout.IsChange())
451 listSent.push_back(make_pair(address, txout.nValue));
454 listReceived.push_back(make_pair(address, txout.nValue));
459 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
460 int64& nSent, int64& nFee) const
462 nGenerated = nReceived = nSent = nFee = 0;
464 int64 allGeneratedImmature, allGeneratedMature, allFee;
465 allGeneratedImmature = allGeneratedMature = allFee = 0;
466 string strSentAccount;
467 list<pair<string, int64> > listReceived;
468 list<pair<string, int64> > listSent;
469 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
471 if (strAccount == "")
472 nGenerated = allGeneratedMature;
473 if (strAccount == strSentAccount)
475 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
479 CRITICAL_BLOCK(cs_mapAddressBook)
481 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
483 if (mapAddressBook.count(r.first))
485 if (mapAddressBook[r.first] == strAccount)
487 nReceived += r.second;
490 else if (strAccount.empty())
492 nReceived += r.second;
500 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
512 // Load the block this tx is in
514 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
516 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
521 // Update the tx's hashBlock
522 hashBlock = pblock->GetHash();
524 // Locate the transaction
525 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
526 if (pblock->vtx[nIndex] == *(CTransaction*)this)
528 if (nIndex == pblock->vtx.size())
530 vMerkleBranch.clear();
532 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
536 // Fill in merkle branch
537 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
540 // Is the tx in a block that's in the main chain
541 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
542 if (mi == mapBlockIndex.end())
544 CBlockIndex* pindex = (*mi).second;
545 if (!pindex || !pindex->IsInMainChain())
548 return pindexBest->nHeight - pindex->nHeight + 1;
553 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
557 const int COPY_DEPTH = 3;
558 if (SetMerkleBranch() < COPY_DEPTH)
560 vector<uint256> vWorkQueue;
561 BOOST_FOREACH(const CTxIn& txin, vin)
562 vWorkQueue.push_back(txin.prevout.hash);
564 // This critsect is OK because txdb is already open
565 CRITICAL_BLOCK(cs_mapWallet)
567 map<uint256, const CMerkleTx*> mapWalletPrev;
568 set<uint256> setAlreadyDone;
569 for (int i = 0; i < vWorkQueue.size(); i++)
571 uint256 hash = vWorkQueue[i];
572 if (setAlreadyDone.count(hash))
574 setAlreadyDone.insert(hash);
577 if (mapWallet.count(hash))
579 tx = mapWallet[hash];
580 BOOST_FOREACH(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
581 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
583 else if (mapWalletPrev.count(hash))
585 tx = *mapWalletPrev[hash];
587 else if (!fClient && txdb.ReadDiskTx(hash, tx))
593 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
597 int nDepth = tx.SetMerkleBranch();
598 vtxPrev.push_back(tx);
600 if (nDepth < COPY_DEPTH)
601 BOOST_FOREACH(const CTxIn& txin, tx.vin)
602 vWorkQueue.push_back(txin.prevout.hash);
607 reverse(vtxPrev.begin(), vtxPrev.end());
620 bool CTransaction::CheckTransaction() const
622 // Basic checks that don't depend on any context
623 if (vin.empty() || vout.empty())
624 return error("CTransaction::CheckTransaction() : vin or vout empty");
627 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
628 return error("CTransaction::CheckTransaction() : size limits failed");
630 // Check for negative or overflow output values
632 BOOST_FOREACH(const CTxOut& txout, vout)
634 if (txout.nValue < 0)
635 return error("CTransaction::CheckTransaction() : txout.nValue negative");
636 if (txout.nValue > MAX_MONEY)
637 return error("CTransaction::CheckTransaction() : txout.nValue too high");
638 nValueOut += txout.nValue;
639 if (!MoneyRange(nValueOut))
640 return error("CTransaction::CheckTransaction() : txout total out of range");
645 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
646 return error("CTransaction::CheckTransaction() : coinbase script size");
650 BOOST_FOREACH(const CTxIn& txin, vin)
651 if (txin.prevout.IsNull())
652 return error("CTransaction::CheckTransaction() : prevout is null");
658 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
661 *pfMissingInputs = false;
663 if (!CheckTransaction())
664 return error("AcceptToMemoryPool() : CheckTransaction failed");
666 // Coinbase is only valid in a block, not as a loose transaction
668 return error("AcceptToMemoryPool() : coinbase as individual tx");
670 // To help v0.1.5 clients who would see it as a negative number
671 if ((int64)nLockTime > INT_MAX)
672 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
675 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
676 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
677 // attacks disallow transactions with more than one SigOp per 34 bytes.
678 // 34 bytes because a TxOut is:
679 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
680 if (GetSigOpCount() > nSize / 34 || nSize < 100)
681 return error("AcceptToMemoryPool() : nonstandard transaction");
683 // Rather not work on nonstandard transactions (unless -testnet)
684 if (!fTestNet && !IsStandard())
685 return error("AcceptToMemoryPool() : nonstandard transaction type");
687 // Do we already have it?
688 uint256 hash = GetHash();
689 CRITICAL_BLOCK(cs_mapTransactions)
690 if (mapTransactions.count(hash))
693 if (txdb.ContainsTx(hash))
696 // Check for conflicts with in-memory transactions
697 CTransaction* ptxOld = NULL;
698 for (int i = 0; i < vin.size(); i++)
700 COutPoint outpoint = vin[i].prevout;
701 if (mapNextTx.count(outpoint))
703 // Disable replacement feature for now
706 // Allow replacing with a newer version of the same transaction
709 ptxOld = mapNextTx[outpoint].ptx;
710 if (ptxOld->IsFinal())
712 if (!IsNewerThan(*ptxOld))
714 for (int i = 0; i < vin.size(); i++)
716 COutPoint outpoint = vin[i].prevout;
717 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
726 // Check against previous transactions
727 map<uint256, CTxIndex> mapUnused;
729 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
732 *pfMissingInputs = true;
733 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
736 // Don't accept it if it can't get into a block
737 if (nFees < GetMinFee(1000))
738 return error("AcceptToMemoryPool() : not enough fees");
740 // Continuously rate-limit free transactions
741 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
742 // be annoying or make other's transactions take longer to confirm.
743 if (nFees < MIN_TX_FEE)
745 static CCriticalSection cs;
746 static double dFreeCount;
747 static int64 nLastTime;
748 int64 nNow = GetTime();
752 // Use an exponentially decaying ~10-minute window:
753 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
755 // -limitfreerelay unit is thousand-bytes-per-minute
756 // At default rate it would take over a month to fill 1GB
757 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())
758 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
760 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
766 // Store transaction in memory
767 CRITICAL_BLOCK(cs_mapTransactions)
771 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
772 ptxOld->RemoveFromMemoryPool();
774 AddToMemoryPoolUnchecked();
777 ///// are we sure this is ok when loading transactions or restoring block txes
778 // If updated, erase old tx from wallet
780 EraseFromWallet(ptxOld->GetHash());
782 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
787 bool CTransaction::AddToMemoryPoolUnchecked()
789 // Add to memory pool without checking anything. Don't call this directly,
790 // call AcceptToMemoryPool to properly check the transaction first.
791 CRITICAL_BLOCK(cs_mapTransactions)
793 uint256 hash = GetHash();
794 mapTransactions[hash] = *this;
795 for (int i = 0; i < vin.size(); i++)
796 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
797 nTransactionsUpdated++;
803 bool CTransaction::RemoveFromMemoryPool()
805 // Remove transaction from memory pool
806 CRITICAL_BLOCK(cs_mapTransactions)
808 BOOST_FOREACH(const CTxIn& txin, vin)
809 mapNextTx.erase(txin.prevout);
810 mapTransactions.erase(GetHash());
811 nTransactionsUpdated++;
821 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
823 if (hashBlock == 0 || nIndex == -1)
826 // Find the block it claims to be in
827 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
828 if (mi == mapBlockIndex.end())
830 CBlockIndex* pindex = (*mi).second;
831 if (!pindex || !pindex->IsInMainChain())
834 // Make sure the merkle branch connects to this block
835 if (!fMerkleVerified)
837 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
839 fMerkleVerified = true;
842 nHeightRet = pindex->nHeight;
843 return pindexBest->nHeight - pindex->nHeight + 1;
847 int CMerkleTx::GetBlocksToMaturity() const
851 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
855 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
859 if (!IsInMainChain() && !ClientConnectInputs())
861 return CTransaction::AcceptToMemoryPool(txdb, false);
865 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
871 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
873 CRITICAL_BLOCK(cs_mapTransactions)
875 // Add previous supporting transactions first
876 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
878 if (!tx.IsCoinBase())
880 uint256 hash = tx.GetHash();
881 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
882 tx.AcceptToMemoryPool(txdb, fCheckInputs);
885 return AcceptToMemoryPool(txdb, fCheckInputs);
890 int ScanForWalletTransactions(CBlockIndex* pindexStart)
894 CBlockIndex* pindex = pindexStart;
895 CRITICAL_BLOCK(cs_mapWallet)
900 block.ReadFromDisk(pindex, true);
901 BOOST_FOREACH(CTransaction& tx, block.vtx)
903 if (AddToWalletIfInvolvingMe(tx, &block))
906 pindex = pindex->pnext;
912 void ReacceptWalletTransactions()
916 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
919 vector<CDiskTxPos> vMissingTx;
920 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
922 CWalletTx& wtx = item.second;
923 if (wtx.IsCoinBase() && wtx.IsSpent(0))
927 bool fUpdated = false;
928 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
930 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
931 if (txindex.vSpent.size() != wtx.vout.size())
933 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
936 for (int i = 0; i < txindex.vSpent.size(); i++)
940 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
944 vMissingTx.push_back(txindex.vSpent[i]);
949 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
956 // Reaccept any txes of ours that aren't already in a block
957 if (!wtx.IsCoinBase())
958 wtx.AcceptWalletTransaction(txdb, false);
961 if (!vMissingTx.empty())
963 // TODO: optimize this to scan just part of the block chain?
964 if (ScanForWalletTransactions(pindexGenesisBlock))
965 fRepeat = true; // Found missing transactions: re-do Reaccept.
971 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
973 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
975 if (!tx.IsCoinBase())
977 uint256 hash = tx.GetHash();
978 if (!txdb.ContainsTx(hash))
979 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
984 uint256 hash = GetHash();
985 if (!txdb.ContainsTx(hash))
987 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
988 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
993 void ResendWalletTransactions()
995 // Do this infrequently and randomly to avoid giving away
996 // that these are our transactions.
997 static int64 nNextTime;
998 if (GetTime() < nNextTime)
1000 bool fFirst = (nNextTime == 0);
1001 nNextTime = GetTime() + GetRand(30 * 60);
1005 // Only do it if there's been a new block since last time
1006 static int64 nLastTime;
1007 if (nTimeBestReceived < nLastTime)
1009 nLastTime = GetTime();
1011 // Rebroadcast any of our txes that aren't in a block yet
1012 printf("ResendWalletTransactions()\n");
1014 CRITICAL_BLOCK(cs_mapWallet)
1016 // Sort them in chronological order
1017 multimap<unsigned int, CWalletTx*> mapSorted;
1018 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1020 CWalletTx& wtx = item.second;
1021 // Don't rebroadcast until it's had plenty of time that
1022 // it should have gotten in already by now.
1023 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1024 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1026 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1028 CWalletTx& wtx = *item.second;
1029 wtx.RelayWalletTransaction(txdb);
1034 int CTxIndex::GetDepthInMainChain() const
1036 // Read block header
1038 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
1040 // Find the block in the index
1041 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
1042 if (mi == mapBlockIndex.end())
1044 CBlockIndex* pindex = (*mi).second;
1045 if (!pindex || !pindex->IsInMainChain())
1047 return 1 + nBestHeight - pindex->nHeight;
1059 //////////////////////////////////////////////////////////////////////////////
1061 // CBlock and CBlockIndex
1064 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1066 if (!fReadTransactions)
1068 *this = pindex->GetBlockHeader();
1071 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1073 if (GetHash() != pindex->GetBlockHash())
1074 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1078 uint256 GetOrphanRoot(const CBlock* pblock)
1080 // Work back to the first block in the orphan chain
1081 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1082 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1083 return pblock->GetHash();
1086 int64 GetBlockValue(int nHeight, int64 nFees)
1088 int64 nSubsidy = 50 * COIN;
1090 // Subsidy is cut in half every 4 years
1091 nSubsidy >>= (nHeight / 210000);
1093 return nSubsidy + nFees;
1096 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1098 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1099 const int64 nTargetSpacing = 10 * 60;
1100 const int64 nInterval = nTargetTimespan / nTargetSpacing;
1103 if (pindexLast == NULL)
1104 return bnProofOfWorkLimit.GetCompact();
1106 // Only change once per interval
1107 if ((pindexLast->nHeight+1) % nInterval != 0)
1108 return pindexLast->nBits;
1110 // Go back by what we want to be 14 days worth of blocks
1111 const CBlockIndex* pindexFirst = pindexLast;
1112 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1113 pindexFirst = pindexFirst->pprev;
1114 assert(pindexFirst);
1116 // Limit adjustment step
1117 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1118 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1119 if (nActualTimespan < nTargetTimespan/4)
1120 nActualTimespan = nTargetTimespan/4;
1121 if (nActualTimespan > nTargetTimespan*4)
1122 nActualTimespan = nTargetTimespan*4;
1126 bnNew.SetCompact(pindexLast->nBits);
1127 bnNew *= nActualTimespan;
1128 bnNew /= nTargetTimespan;
1130 if (bnNew > bnProofOfWorkLimit)
1131 bnNew = bnProofOfWorkLimit;
1134 printf("GetNextWorkRequired RETARGET\n");
1135 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1136 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1137 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1139 return bnNew.GetCompact();
1142 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1145 bnTarget.SetCompact(nBits);
1148 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1149 return error("CheckProofOfWork() : nBits below minimum work");
1151 // Check proof of work matches claimed amount
1152 if (hash > bnTarget.getuint256())
1153 return error("CheckProofOfWork() : hash doesn't match nBits");
1158 bool IsInitialBlockDownload()
1160 if (pindexBest == NULL || (!fTestNet && nBestHeight < 118000))
1162 static int64 nLastUpdate;
1163 static CBlockIndex* pindexLastBest;
1164 if (pindexBest != pindexLastBest)
1166 pindexLastBest = pindexBest;
1167 nLastUpdate = GetTime();
1169 return (GetTime() - nLastUpdate < 10 &&
1170 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1173 void InvalidChainFound(CBlockIndex* pindexNew)
1175 if (pindexNew->bnChainWork > bnBestInvalidWork)
1177 bnBestInvalidWork = pindexNew->bnChainWork;
1178 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1181 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());
1182 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1183 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1184 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1197 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1199 // Relinquish previous transactions' spent pointers
1202 BOOST_FOREACH(const CTxIn& txin, vin)
1204 COutPoint prevout = txin.prevout;
1206 // Get prev txindex from disk
1208 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1209 return error("DisconnectInputs() : ReadTxIndex failed");
1211 if (prevout.n >= txindex.vSpent.size())
1212 return error("DisconnectInputs() : prevout.n out of range");
1214 // Mark outpoint as not spent
1215 txindex.vSpent[prevout.n].SetNull();
1218 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1219 return error("DisconnectInputs() : UpdateTxIndex failed");
1223 // Remove transaction from index
1224 if (!txdb.EraseTxIndex(*this))
1225 return error("DisconnectInputs() : EraseTxPos failed");
1231 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1232 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1234 // Take over previous transactions' spent pointers
1238 for (int i = 0; i < vin.size(); i++)
1240 COutPoint prevout = vin[i].prevout;
1245 if (fMiner && mapTestPool.count(prevout.hash))
1247 // Get txindex from current proposed changes
1248 txindex = mapTestPool[prevout.hash];
1252 // Read txindex from txdb
1253 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1255 if (!fFound && (fBlock || fMiner))
1256 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());
1259 CTransaction txPrev;
1260 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1262 // Get prev tx from single transactions in memory
1263 CRITICAL_BLOCK(cs_mapTransactions)
1265 if (!mapTransactions.count(prevout.hash))
1266 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1267 txPrev = mapTransactions[prevout.hash];
1270 txindex.vSpent.resize(txPrev.vout.size());
1274 // Get prev tx from disk
1275 if (!txPrev.ReadFromDisk(txindex.pos))
1276 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1279 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1280 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());
1282 // If prev is coinbase, check that it's matured
1283 if (txPrev.IsCoinBase())
1284 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1285 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1286 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1289 if (!VerifySignature(txPrev, *this, i))
1290 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1292 // Check for conflicts
1293 if (!txindex.vSpent[prevout.n].IsNull())
1294 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());
1296 // Check for negative or overflow input values
1297 nValueIn += txPrev.vout[prevout.n].nValue;
1298 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1299 return error("ConnectInputs() : txin values out of range");
1301 // Mark outpoints as spent
1302 txindex.vSpent[prevout.n] = posThisTx;
1307 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1308 return error("ConnectInputs() : UpdateTxIndex failed");
1312 mapTestPool[prevout.hash] = txindex;
1316 if (nValueIn < GetValueOut())
1317 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1319 // Tally transaction fees
1320 int64 nTxFee = nValueIn - GetValueOut();
1322 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1323 if (nTxFee < nMinFee)
1326 if (!MoneyRange(nFees))
1327 return error("ConnectInputs() : nFees out of range");
1332 // Add transaction to disk index
1333 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1334 return error("ConnectInputs() : AddTxPos failed");
1338 // Add transaction to test pool
1339 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1346 bool CTransaction::ClientConnectInputs()
1351 // Take over previous transactions' spent pointers
1352 CRITICAL_BLOCK(cs_mapTransactions)
1355 for (int i = 0; i < vin.size(); i++)
1357 // Get prev tx from single transactions in memory
1358 COutPoint prevout = vin[i].prevout;
1359 if (!mapTransactions.count(prevout.hash))
1361 CTransaction& txPrev = mapTransactions[prevout.hash];
1363 if (prevout.n >= txPrev.vout.size())
1367 if (!VerifySignature(txPrev, *this, i))
1368 return error("ConnectInputs() : VerifySignature failed");
1370 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1371 ///// this has to go away now that posNext is gone
1372 // // Check for conflicts
1373 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1374 // return error("ConnectInputs() : prev tx already used");
1376 // // Flag outpoints as used
1377 // txPrev.vout[prevout.n].posNext = posThisTx;
1379 nValueIn += txPrev.vout[prevout.n].nValue;
1381 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1382 return error("ClientConnectInputs() : txin values out of range");
1384 if (GetValueOut() > nValueIn)
1394 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1396 // Disconnect in reverse order
1397 for (int i = vtx.size()-1; i >= 0; i--)
1398 if (!vtx[i].DisconnectInputs(txdb))
1401 // Update block index on disk without changing it in memory.
1402 // The memory index structure will be changed after the db commits.
1405 CDiskBlockIndex blockindexPrev(pindex->pprev);
1406 blockindexPrev.hashNext = 0;
1407 if (!txdb.WriteBlockIndex(blockindexPrev))
1408 return error("DisconnectBlock() : WriteBlockIndex failed");
1414 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1416 // Check it again in case a previous version let a bad block in
1420 //// issue here: it doesn't know the version
1421 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1423 map<uint256, CTxIndex> mapUnused;
1425 BOOST_FOREACH(CTransaction& tx, vtx)
1427 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1428 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1430 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1434 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1437 // Update block index on disk without changing it in memory.
1438 // The memory index structure will be changed after the db commits.
1441 CDiskBlockIndex blockindexPrev(pindex->pprev);
1442 blockindexPrev.hashNext = pindex->GetBlockHash();
1443 if (!txdb.WriteBlockIndex(blockindexPrev))
1444 return error("ConnectBlock() : WriteBlockIndex failed");
1447 // Watch for transactions paying to me
1448 BOOST_FOREACH(CTransaction& tx, vtx)
1449 AddToWalletIfInvolvingMe(tx, this, true);
1454 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1456 printf("REORGANIZE\n");
1459 CBlockIndex* pfork = pindexBest;
1460 CBlockIndex* plonger = pindexNew;
1461 while (pfork != plonger)
1463 while (plonger->nHeight > pfork->nHeight)
1464 if (!(plonger = plonger->pprev))
1465 return error("Reorganize() : plonger->pprev is null");
1466 if (pfork == plonger)
1468 if (!(pfork = pfork->pprev))
1469 return error("Reorganize() : pfork->pprev is null");
1472 // List of what to disconnect
1473 vector<CBlockIndex*> vDisconnect;
1474 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1475 vDisconnect.push_back(pindex);
1477 // List of what to connect
1478 vector<CBlockIndex*> vConnect;
1479 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1480 vConnect.push_back(pindex);
1481 reverse(vConnect.begin(), vConnect.end());
1483 // Disconnect shorter branch
1484 vector<CTransaction> vResurrect;
1485 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1488 if (!block.ReadFromDisk(pindex))
1489 return error("Reorganize() : ReadFromDisk for disconnect failed");
1490 if (!block.DisconnectBlock(txdb, pindex))
1491 return error("Reorganize() : DisconnectBlock failed");
1493 // Queue memory transactions to resurrect
1494 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1495 if (!tx.IsCoinBase())
1496 vResurrect.push_back(tx);
1499 // Connect longer branch
1500 vector<CTransaction> vDelete;
1501 for (int i = 0; i < vConnect.size(); i++)
1503 CBlockIndex* pindex = vConnect[i];
1505 if (!block.ReadFromDisk(pindex))
1506 return error("Reorganize() : ReadFromDisk for connect failed");
1507 if (!block.ConnectBlock(txdb, pindex))
1511 return error("Reorganize() : ConnectBlock failed");
1514 // Queue memory transactions to delete
1515 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1516 vDelete.push_back(tx);
1518 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1519 return error("Reorganize() : WriteHashBestChain failed");
1521 // Make sure it's successfully written to disk before changing memory structure
1522 if (!txdb.TxnCommit())
1523 return error("Reorganize() : TxnCommit failed");
1525 // Disconnect shorter branch
1526 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1528 pindex->pprev->pnext = NULL;
1530 // Connect longer branch
1531 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1533 pindex->pprev->pnext = pindex;
1535 // Resurrect memory transactions that were in the disconnected branch
1536 BOOST_FOREACH(CTransaction& tx, vResurrect)
1537 tx.AcceptToMemoryPool(txdb, false);
1539 // Delete redundant memory transactions that are in the connected branch
1540 BOOST_FOREACH(CTransaction& tx, vDelete)
1541 tx.RemoveFromMemoryPool();
1547 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1549 uint256 hash = GetHash();
1552 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1554 txdb.WriteHashBestChain(hash);
1555 if (!txdb.TxnCommit())
1556 return error("SetBestChain() : TxnCommit failed");
1557 pindexGenesisBlock = pindexNew;
1559 else if (hashPrevBlock == hashBestChain)
1561 // Adding to current best branch
1562 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1565 InvalidChainFound(pindexNew);
1566 return error("SetBestChain() : ConnectBlock failed");
1568 if (!txdb.TxnCommit())
1569 return error("SetBestChain() : TxnCommit failed");
1571 // Add to current best branch
1572 pindexNew->pprev->pnext = pindexNew;
1574 // Delete redundant memory transactions
1575 BOOST_FOREACH(CTransaction& tx, vtx)
1576 tx.RemoveFromMemoryPool();
1581 if (!Reorganize(txdb, pindexNew))
1584 InvalidChainFound(pindexNew);
1585 return error("SetBestChain() : Reorganize failed");
1589 // Update best block in wallet (so we can detect restored wallets)
1590 if (!IsInitialBlockDownload())
1593 const CBlockLocator locator(pindexNew);
1594 if (!walletdb.WriteBestBlock(locator))
1595 return error("SetBestChain() : WriteWalletBest failed");
1599 hashBestChain = hash;
1600 pindexBest = pindexNew;
1601 nBestHeight = pindexBest->nHeight;
1602 bnBestChainWork = pindexNew->bnChainWork;
1603 nTimeBestReceived = GetTime();
1604 nTransactionsUpdated++;
1605 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1611 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1613 // Check for duplicate
1614 uint256 hash = GetHash();
1615 if (mapBlockIndex.count(hash))
1616 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1618 // Construct new block index object
1619 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1621 return error("AddToBlockIndex() : new CBlockIndex failed");
1622 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1623 pindexNew->phashBlock = &((*mi).first);
1624 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1625 if (miPrev != mapBlockIndex.end())
1627 pindexNew->pprev = (*miPrev).second;
1628 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1630 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1634 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1635 if (!txdb.TxnCommit())
1639 if (pindexNew->bnChainWork > bnBestChainWork)
1640 if (!SetBestChain(txdb, pindexNew))
1645 if (pindexNew == pindexBest)
1647 // Notify UI to display prev block's coinbase if it was ours
1648 static uint256 hashPrevBestCoinBase;
1649 CRITICAL_BLOCK(cs_mapWallet)
1650 vWalletUpdated.push_back(hashPrevBestCoinBase);
1651 hashPrevBestCoinBase = vtx[0].GetHash();
1661 bool CBlock::CheckBlock() const
1663 // These are checks that are independent of context
1664 // that can be verified before saving an orphan block.
1667 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1668 return error("CheckBlock() : size limits failed");
1670 // Check proof of work matches claimed amount
1671 if (!CheckProofOfWork(GetHash(), nBits))
1672 return error("CheckBlock() : proof of work failed");
1675 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1676 return error("CheckBlock() : block timestamp too far in the future");
1678 // First transaction must be coinbase, the rest must not be
1679 if (vtx.empty() || !vtx[0].IsCoinBase())
1680 return error("CheckBlock() : first tx is not coinbase");
1681 for (int i = 1; i < vtx.size(); i++)
1682 if (vtx[i].IsCoinBase())
1683 return error("CheckBlock() : more than one coinbase");
1685 // Check transactions
1686 BOOST_FOREACH(const CTransaction& tx, vtx)
1687 if (!tx.CheckTransaction())
1688 return error("CheckBlock() : CheckTransaction failed");
1690 // Check that it's not full of nonstandard transactions
1691 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1692 return error("CheckBlock() : too many nonstandard transactions");
1695 if (hashMerkleRoot != BuildMerkleTree())
1696 return error("CheckBlock() : hashMerkleRoot mismatch");
1701 bool CBlock::AcceptBlock()
1703 // Check for duplicate
1704 uint256 hash = GetHash();
1705 if (mapBlockIndex.count(hash))
1706 return error("AcceptBlock() : block already in mapBlockIndex");
1708 // Get prev block index
1709 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1710 if (mi == mapBlockIndex.end())
1711 return error("AcceptBlock() : prev block not found");
1712 CBlockIndex* pindexPrev = (*mi).second;
1713 int nHeight = pindexPrev->nHeight+1;
1715 // Check proof of work
1716 if (nBits != GetNextWorkRequired(pindexPrev))
1717 return error("AcceptBlock() : incorrect proof of work");
1719 // Check timestamp against prev
1720 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1721 return error("AcceptBlock() : block's timestamp is too early");
1723 // Check that all transactions are finalized
1724 BOOST_FOREACH(const CTransaction& tx, vtx)
1725 if (!tx.IsFinal(nHeight, GetBlockTime()))
1726 return error("AcceptBlock() : contains a non-final transaction");
1728 // Check that the block chain matches the known block chain up to a checkpoint
1730 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1731 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1732 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1733 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1734 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1735 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1736 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))
1737 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1739 // Write block to history file
1740 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1741 return error("AcceptBlock() : out of disk space");
1742 unsigned int nFile = -1;
1743 unsigned int nBlockPos = 0;
1744 if (!WriteToDisk(nFile, nBlockPos))
1745 return error("AcceptBlock() : WriteToDisk failed");
1746 if (!AddToBlockIndex(nFile, nBlockPos))
1747 return error("AcceptBlock() : AddToBlockIndex failed");
1749 // Relay inventory, but don't relay old inventory during initial block download
1750 if (hashBestChain == hash)
1751 CRITICAL_BLOCK(cs_vNodes)
1752 BOOST_FOREACH(CNode* pnode, vNodes)
1753 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
1754 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1759 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1761 // Check for duplicate
1762 uint256 hash = pblock->GetHash();
1763 if (mapBlockIndex.count(hash))
1764 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1765 if (mapOrphanBlocks.count(hash))
1766 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1768 // Preliminary checks
1769 if (!pblock->CheckBlock())
1770 return error("ProcessBlock() : CheckBlock FAILED");
1772 // If don't already have its previous block, shunt it off to holding area until we get it
1773 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1775 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1776 CBlock* pblock2 = new CBlock(*pblock);
1777 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1778 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1780 // Ask this guy to fill in what we're missing
1782 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1787 if (!pblock->AcceptBlock())
1788 return error("ProcessBlock() : AcceptBlock FAILED");
1790 // Recursively process any orphan blocks that depended on this one
1791 vector<uint256> vWorkQueue;
1792 vWorkQueue.push_back(hash);
1793 for (int i = 0; i < vWorkQueue.size(); i++)
1795 uint256 hashPrev = vWorkQueue[i];
1796 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1797 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1800 CBlock* pblockOrphan = (*mi).second;
1801 if (pblockOrphan->AcceptBlock())
1802 vWorkQueue.push_back(pblockOrphan->GetHash());
1803 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1804 delete pblockOrphan;
1806 mapOrphanBlocksByPrev.erase(hashPrev);
1809 printf("ProcessBlock: ACCEPTED\n");
1820 template<typename Stream>
1821 bool ScanMessageStart(Stream& s)
1823 // Scan ahead to the next pchMessageStart, which should normally be immediately
1824 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1826 short prevmask = s.exceptions(0);
1827 const char* p = BEGIN(pchMessageStart);
1837 s.exceptions(prevmask);
1841 p = BEGIN(pchMessageStart);
1844 if (++p == END(pchMessageStart))
1847 s.exceptions(prevmask);
1856 s.exceptions(prevmask);
1861 bool CheckDiskSpace(uint64 nAdditionalBytes)
1863 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1865 // Check for 15MB because database could create another 10MB log file at any time
1866 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1869 string strMessage = _("Warning: Disk space is low ");
1870 strMiscWarning = strMessage;
1871 printf("*** %s\n", strMessage.c_str());
1872 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1873 CreateThread(Shutdown, NULL);
1879 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1883 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1886 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1888 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1897 static unsigned int nCurrentBlockFile = 1;
1899 FILE* AppendBlockFile(unsigned int& nFileRet)
1904 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1907 if (fseek(file, 0, SEEK_END) != 0)
1909 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1910 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1912 nFileRet = nCurrentBlockFile;
1916 nCurrentBlockFile++;
1920 bool LoadBlockIndex(bool fAllowNew)
1924 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1925 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1926 pchMessageStart[0] = 0xfa;
1927 pchMessageStart[1] = 0xbf;
1928 pchMessageStart[2] = 0xb5;
1929 pchMessageStart[3] = 0xda;
1936 if (!txdb.LoadBlockIndex())
1941 // Init with genesis block
1943 if (mapBlockIndex.empty())
1949 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1950 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1951 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1952 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1953 // vMerkleTree: 4a5e1e
1956 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1958 txNew.vin.resize(1);
1959 txNew.vout.resize(1);
1960 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1961 txNew.vout[0].nValue = 50 * COIN;
1962 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1964 block.vtx.push_back(txNew);
1965 block.hashPrevBlock = 0;
1966 block.hashMerkleRoot = block.BuildMerkleTree();
1968 block.nTime = 1231006505;
1969 block.nBits = 0x1d00ffff;
1970 block.nNonce = 2083236893;
1974 block.nTime = 1296688602;
1975 block.nBits = 0x1d07fff8;
1976 block.nNonce = 384568319;
1980 printf("%s\n", block.GetHash().ToString().c_str());
1981 printf("%s\n", hashGenesisBlock.ToString().c_str());
1982 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1983 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1985 assert(block.GetHash() == hashGenesisBlock);
1987 // Start new block file
1989 unsigned int nBlockPos;
1990 if (!block.WriteToDisk(nFile, nBlockPos))
1991 return error("LoadBlockIndex() : writing genesis block to disk failed");
1992 if (!block.AddToBlockIndex(nFile, nBlockPos))
1993 return error("LoadBlockIndex() : genesis block not accepted");
2001 void PrintBlockTree()
2003 // precompute tree structure
2004 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2005 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2007 CBlockIndex* pindex = (*mi).second;
2008 mapNext[pindex->pprev].push_back(pindex);
2010 //while (rand() % 3 == 0)
2011 // mapNext[pindex->pprev].push_back(pindex);
2014 vector<pair<int, CBlockIndex*> > vStack;
2015 vStack.push_back(make_pair(0, pindexGenesisBlock));
2018 while (!vStack.empty())
2020 int nCol = vStack.back().first;
2021 CBlockIndex* pindex = vStack.back().second;
2024 // print split or gap
2025 if (nCol > nPrevCol)
2027 for (int i = 0; i < nCol-1; i++)
2031 else if (nCol < nPrevCol)
2033 for (int i = 0; i < nCol; i++)
2040 for (int i = 0; i < nCol; i++)
2045 block.ReadFromDisk(pindex);
2046 printf("%d (%u,%u) %s %s tx %d",
2050 block.GetHash().ToString().substr(0,20).c_str(),
2051 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2054 CRITICAL_BLOCK(cs_mapWallet)
2056 if (mapWallet.count(block.vtx[0].GetHash()))
2058 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2059 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2065 // put the main timechain first
2066 vector<CBlockIndex*>& vNext = mapNext[pindex];
2067 for (int i = 0; i < vNext.size(); i++)
2069 if (vNext[i]->pnext)
2071 swap(vNext[0], vNext[i]);
2077 for (int i = 0; i < vNext.size(); i++)
2078 vStack.push_back(make_pair(nCol+i, vNext[i]));
2091 //////////////////////////////////////////////////////////////////////////////
2096 map<uint256, CAlert> mapAlerts;
2097 CCriticalSection cs_mapAlerts;
2099 string GetWarnings(string strFor)
2102 string strStatusBar;
2104 if (GetBoolArg("-testsafemode"))
2107 // Misc warnings like out of disk space and clock is wrong
2108 if (strMiscWarning != "")
2111 strStatusBar = strMiscWarning;
2114 // Longer invalid proof-of-work chain
2115 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2118 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2122 CRITICAL_BLOCK(cs_mapAlerts)
2124 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2126 const CAlert& alert = item.second;
2127 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2129 nPriority = alert.nPriority;
2130 strStatusBar = alert.strStatusBar;
2135 if (strFor == "statusbar")
2136 return strStatusBar;
2137 else if (strFor == "rpc")
2139 assert(("GetWarnings() : invalid parameter", false));
2143 bool CAlert::ProcessAlert()
2145 if (!CheckSignature())
2150 CRITICAL_BLOCK(cs_mapAlerts)
2152 // Cancel previous alerts
2153 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2155 const CAlert& alert = (*mi).second;
2158 printf("cancelling alert %d\n", alert.nID);
2159 mapAlerts.erase(mi++);
2161 else if (!alert.IsInEffect())
2163 printf("expiring alert %d\n", alert.nID);
2164 mapAlerts.erase(mi++);
2170 // Check if this alert has been cancelled
2171 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2173 const CAlert& alert = item.second;
2174 if (alert.Cancels(*this))
2176 printf("alert already cancelled by %d\n", alert.nID);
2182 mapAlerts.insert(make_pair(GetHash(), *this));
2185 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2197 //////////////////////////////////////////////////////////////////////////////
2203 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2207 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2208 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2210 // Don't know what it is, just say we already got one
2217 // The message start string is designed to be unlikely to occur in normal data.
2218 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2219 // a large 4-byte int at any alignment.
2220 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2223 bool ProcessMessages(CNode* pfrom)
2225 CDataStream& vRecv = pfrom->vRecv;
2229 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2233 // (4) message start
2242 // Scan for message start
2243 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2244 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2245 if (vRecv.end() - pstart < nHeaderSize)
2247 if (vRecv.size() > nHeaderSize)
2249 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2250 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2254 if (pstart - vRecv.begin() > 0)
2255 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2256 vRecv.erase(vRecv.begin(), pstart);
2259 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2264 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2267 string strCommand = hdr.GetCommand();
2270 unsigned int nMessageSize = hdr.nMessageSize;
2271 if (nMessageSize > MAX_SIZE)
2273 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2276 if (nMessageSize > vRecv.size())
2278 // Rewind and wait for rest of message
2279 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2284 if (vRecv.GetVersion() >= 209)
2286 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2287 unsigned int nChecksum = 0;
2288 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2289 if (nChecksum != hdr.nChecksum)
2291 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2292 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2297 // Copy message to its own buffer
2298 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2299 vRecv.ignore(nMessageSize);
2305 CRITICAL_BLOCK(cs_main)
2306 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2310 catch (std::ios_base::failure& e)
2312 if (strstr(e.what(), "end of data"))
2314 // Allow exceptions from underlength message on vRecv
2315 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());
2317 else if (strstr(e.what(), "size too large"))
2319 // Allow exceptions from overlong size
2320 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2324 PrintExceptionContinue(&e, "ProcessMessage()");
2327 catch (std::exception& e) {
2328 PrintExceptionContinue(&e, "ProcessMessage()");
2330 PrintExceptionContinue(NULL, "ProcessMessage()");
2334 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2344 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2346 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2347 RandAddSeedPerfmon();
2349 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2350 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2351 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2353 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2361 if (strCommand == "version")
2363 // Each connection can only send one version message
2364 if (pfrom->nVersion != 0)
2371 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2372 if (pfrom->nVersion == 10300)
2373 pfrom->nVersion = 300;
2374 if (pfrom->nVersion >= 106 && !vRecv.empty())
2375 vRecv >> addrFrom >> nNonce;
2376 if (pfrom->nVersion >= 106 && !vRecv.empty())
2377 vRecv >> pfrom->strSubVer;
2378 if (pfrom->nVersion >= 209 && !vRecv.empty())
2379 vRecv >> pfrom->nStartingHeight;
2381 if (pfrom->nVersion == 0)
2384 // Disconnect if we connected to ourself
2385 if (nNonce == nLocalHostNonce && nNonce > 1)
2387 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2388 pfrom->fDisconnect = true;
2392 // Be shy and don't send version until we hear
2393 if (pfrom->fInbound)
2394 pfrom->PushVersion();
2396 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2398 AddTimeData(pfrom->addr.ip, nTime);
2401 if (pfrom->nVersion >= 209)
2402 pfrom->PushMessage("verack");
2403 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2404 if (pfrom->nVersion < 209)
2405 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2407 if (!pfrom->fInbound)
2409 // Advertise our address
2410 if (addrLocalHost.IsRoutable() && !fUseProxy)
2412 CAddress addr(addrLocalHost);
2413 addr.nTime = GetAdjustedTime();
2414 pfrom->PushAddress(addr);
2417 // Get recent addresses
2418 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2420 pfrom->PushMessage("getaddr");
2421 pfrom->fGetAddr = true;
2425 // Ask the first connected node for block updates
2426 static int nAskedForBlocks;
2427 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2430 pfrom->PushGetBlocks(pindexBest, uint256(0));
2434 CRITICAL_BLOCK(cs_mapAlerts)
2435 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2436 item.second.RelayTo(pfrom);
2438 pfrom->fSuccessfullyConnected = true;
2440 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2444 else if (pfrom->nVersion == 0)
2446 // Must have a version message before anything else
2451 else if (strCommand == "verack")
2453 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2457 else if (strCommand == "addr")
2459 vector<CAddress> vAddr;
2462 // Don't want addr from older versions unless seeding
2463 if (pfrom->nVersion < 209)
2465 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2467 if (vAddr.size() > 1000)
2468 return error("message addr size() = %d", vAddr.size());
2470 // Store the new addresses
2471 int64 nNow = GetAdjustedTime();
2472 int64 nSince = nNow - 10 * 60;
2473 BOOST_FOREACH(CAddress& addr, vAddr)
2477 // ignore IPv6 for now, since it isn't implemented anyway
2480 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2481 addr.nTime = nNow - 5 * 24 * 60 * 60;
2482 AddAddress(addr, 2 * 60 * 60);
2483 pfrom->AddAddressKnown(addr);
2484 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2486 // Relay to a limited number of other nodes
2487 CRITICAL_BLOCK(cs_vNodes)
2489 // Use deterministic randomness to send to the same nodes for 24 hours
2490 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2491 static uint256 hashSalt;
2493 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2494 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2495 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2496 multimap<uint256, CNode*> mapMix;
2497 BOOST_FOREACH(CNode* pnode, vNodes)
2499 if (pnode->nVersion < 31402)
2501 unsigned int nPointer;
2502 memcpy(&nPointer, &pnode, sizeof(nPointer));
2503 uint256 hashKey = hashRand ^ nPointer;
2504 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2505 mapMix.insert(make_pair(hashKey, pnode));
2507 int nRelayNodes = 2;
2508 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2509 ((*mi).second)->PushAddress(addr);
2513 if (vAddr.size() < 1000)
2514 pfrom->fGetAddr = false;
2518 else if (strCommand == "inv")
2522 if (vInv.size() > 50000)
2523 return error("message inv size() = %d", vInv.size());
2526 BOOST_FOREACH(const CInv& inv, vInv)
2530 pfrom->AddInventoryKnown(inv);
2532 bool fAlreadyHave = AlreadyHave(txdb, inv);
2533 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2537 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2538 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2540 // Track requests for our stuff
2541 CRITICAL_BLOCK(cs_mapRequestCount)
2543 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2544 if (mi != mapRequestCount.end())
2551 else if (strCommand == "getdata")
2555 if (vInv.size() > 50000)
2556 return error("message getdata size() = %d", vInv.size());
2558 BOOST_FOREACH(const CInv& inv, vInv)
2562 printf("received getdata for: %s\n", inv.ToString().c_str());
2564 if (inv.type == MSG_BLOCK)
2566 // Send block from disk
2567 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2568 if (mi != mapBlockIndex.end())
2571 block.ReadFromDisk((*mi).second);
2572 pfrom->PushMessage("block", block);
2574 // Trigger them to send a getblocks request for the next batch of inventory
2575 if (inv.hash == pfrom->hashContinue)
2577 // Bypass PushInventory, this must send even if redundant,
2578 // and we want it right after the last block so they don't
2579 // wait for other stuff first.
2581 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2582 pfrom->PushMessage("inv", vInv);
2583 pfrom->hashContinue = 0;
2587 else if (inv.IsKnownType())
2589 // Send stream from relay memory
2590 CRITICAL_BLOCK(cs_mapRelay)
2592 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2593 if (mi != mapRelay.end())
2594 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2598 // Track requests for our stuff
2599 CRITICAL_BLOCK(cs_mapRequestCount)
2601 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2602 if (mi != mapRequestCount.end())
2609 else if (strCommand == "getblocks")
2611 CBlockLocator locator;
2613 vRecv >> locator >> hashStop;
2615 // Find the last block the caller has in the main chain
2616 CBlockIndex* pindex = locator.GetBlockIndex();
2618 // Send the rest of the chain
2620 pindex = pindex->pnext;
2621 int nLimit = 500 + locator.GetDistanceBack();
2622 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2623 for (; pindex; pindex = pindex->pnext)
2625 if (pindex->GetBlockHash() == hashStop)
2627 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2630 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2633 // When this block is requested, we'll send an inv that'll make them
2634 // getblocks the next batch of inventory.
2635 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2636 pfrom->hashContinue = pindex->GetBlockHash();
2643 else if (strCommand == "getheaders")
2645 CBlockLocator locator;
2647 vRecv >> locator >> hashStop;
2649 CBlockIndex* pindex = NULL;
2650 if (locator.IsNull())
2652 // If locator is null, return the hashStop block
2653 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2654 if (mi == mapBlockIndex.end())
2656 pindex = (*mi).second;
2660 // Find the last block the caller has in the main chain
2661 pindex = locator.GetBlockIndex();
2663 pindex = pindex->pnext;
2666 vector<CBlock> vHeaders;
2667 int nLimit = 2000 + locator.GetDistanceBack();
2668 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2669 for (; pindex; pindex = pindex->pnext)
2671 vHeaders.push_back(pindex->GetBlockHeader());
2672 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2675 pfrom->PushMessage("headers", vHeaders);
2679 else if (strCommand == "tx")
2681 vector<uint256> vWorkQueue;
2682 CDataStream vMsg(vRecv);
2686 CInv inv(MSG_TX, tx.GetHash());
2687 pfrom->AddInventoryKnown(inv);
2689 bool fMissingInputs = false;
2690 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2692 AddToWalletIfInvolvingMe(tx, NULL, true);
2693 RelayMessage(inv, vMsg);
2694 mapAlreadyAskedFor.erase(inv);
2695 vWorkQueue.push_back(inv.hash);
2697 // Recursively process any orphan transactions that depended on this one
2698 for (int i = 0; i < vWorkQueue.size(); i++)
2700 uint256 hashPrev = vWorkQueue[i];
2701 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2702 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2705 const CDataStream& vMsg = *((*mi).second);
2707 CDataStream(vMsg) >> tx;
2708 CInv inv(MSG_TX, tx.GetHash());
2710 if (tx.AcceptToMemoryPool(true))
2712 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2713 AddToWalletIfInvolvingMe(tx, NULL, true);
2714 RelayMessage(inv, vMsg);
2715 mapAlreadyAskedFor.erase(inv);
2716 vWorkQueue.push_back(inv.hash);
2721 BOOST_FOREACH(uint256 hash, vWorkQueue)
2722 EraseOrphanTx(hash);
2724 else if (fMissingInputs)
2726 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2732 else if (strCommand == "block")
2737 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2740 CInv inv(MSG_BLOCK, block.GetHash());
2741 pfrom->AddInventoryKnown(inv);
2743 if (ProcessBlock(pfrom, &block))
2744 mapAlreadyAskedFor.erase(inv);
2748 else if (strCommand == "getaddr")
2750 // Nodes rebroadcast an addr every 24 hours
2751 pfrom->vAddrToSend.clear();
2752 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2753 CRITICAL_BLOCK(cs_mapAddresses)
2755 unsigned int nCount = 0;
2756 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2758 const CAddress& addr = item.second;
2759 if (addr.nTime > nSince)
2762 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2764 const CAddress& addr = item.second;
2765 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2766 pfrom->PushAddress(addr);
2772 else if (strCommand == "checkorder")
2777 if (!GetBoolArg("-allowreceivebyip"))
2779 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2786 /// we have a chance to check the order here
2788 // Keep giving the same key to the same ip until they use it
2789 if (!mapReuseKey.count(pfrom->addr.ip))
2790 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2792 // Send back approval of order and pubkey to use
2793 CScript scriptPubKey;
2794 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2795 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2799 else if (strCommand == "submitorder")
2804 if (!GetBoolArg("-allowreceivebyip"))
2806 pfrom->PushMessage("reply", hashReply, (int)2);
2812 wtxNew.fFromMe = false;
2815 if (!wtxNew.AcceptWalletTransaction())
2817 pfrom->PushMessage("reply", hashReply, (int)1);
2818 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2820 wtxNew.fTimeReceivedIsTxTime = true;
2821 AddToWallet(wtxNew);
2822 wtxNew.RelayWalletTransaction();
2823 mapReuseKey.erase(pfrom->addr.ip);
2825 // Send back confirmation
2826 pfrom->PushMessage("reply", hashReply, (int)0);
2830 else if (strCommand == "reply")
2835 CRequestTracker tracker;
2836 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2838 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2839 if (mi != pfrom->mapRequests.end())
2841 tracker = (*mi).second;
2842 pfrom->mapRequests.erase(mi);
2845 if (!tracker.IsNull())
2846 tracker.fn(tracker.param1, vRecv);
2850 else if (strCommand == "ping")
2855 else if (strCommand == "alert")
2860 if (alert.ProcessAlert())
2863 pfrom->setKnown.insert(alert.GetHash());
2864 CRITICAL_BLOCK(cs_vNodes)
2865 BOOST_FOREACH(CNode* pnode, vNodes)
2866 alert.RelayTo(pnode);
2873 // Ignore unknown commands for extensibility
2877 // Update the last seen time for this node's address
2878 if (pfrom->fNetworkNode)
2879 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2880 AddressCurrentlyConnected(pfrom->addr);
2894 bool SendMessages(CNode* pto, bool fSendTrickle)
2896 CRITICAL_BLOCK(cs_main)
2898 // Don't send anything until we get their version message
2899 if (pto->nVersion == 0)
2903 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2904 pto->PushMessage("ping");
2906 // Resend wallet transactions that haven't gotten in a block yet
2907 ResendWalletTransactions();
2909 // Address refresh broadcast
2910 static int64 nLastRebroadcast;
2911 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2913 nLastRebroadcast = GetTime();
2914 CRITICAL_BLOCK(cs_vNodes)
2916 BOOST_FOREACH(CNode* pnode, vNodes)
2918 // Periodically clear setAddrKnown to allow refresh broadcasts
2919 pnode->setAddrKnown.clear();
2921 // Rebroadcast our address
2922 if (addrLocalHost.IsRoutable() && !fUseProxy)
2924 CAddress addr(addrLocalHost);
2925 addr.nTime = GetAdjustedTime();
2926 pnode->PushAddress(addr);
2932 // Clear out old addresses periodically so it's not too much work at once
2933 static int64 nLastClear;
2934 if (nLastClear == 0)
2935 nLastClear = GetTime();
2936 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2938 nLastClear = GetTime();
2939 CRITICAL_BLOCK(cs_mapAddresses)
2942 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2943 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2944 mi != mapAddresses.end();)
2946 const CAddress& addr = (*mi).second;
2947 if (addr.nTime < nSince)
2949 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2951 addrdb.EraseAddress(addr);
2952 mapAddresses.erase(mi++);
2966 vector<CAddress> vAddr;
2967 vAddr.reserve(pto->vAddrToSend.size());
2968 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2970 // returns true if wasn't already contained in the set
2971 if (pto->setAddrKnown.insert(addr).second)
2973 vAddr.push_back(addr);
2974 // receiver rejects addr messages larger than 1000
2975 if (vAddr.size() >= 1000)
2977 pto->PushMessage("addr", vAddr);
2982 pto->vAddrToSend.clear();
2984 pto->PushMessage("addr", vAddr);
2989 // Message: inventory
2992 vector<CInv> vInvWait;
2993 CRITICAL_BLOCK(pto->cs_inventory)
2995 vInv.reserve(pto->vInventoryToSend.size());
2996 vInvWait.reserve(pto->vInventoryToSend.size());
2997 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2999 if (pto->setInventoryKnown.count(inv))
3002 // trickle out tx inv to protect privacy
3003 if (inv.type == MSG_TX && !fSendTrickle)
3005 // 1/4 of tx invs blast to all immediately
3006 static uint256 hashSalt;
3008 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
3009 uint256 hashRand = inv.hash ^ hashSalt;
3010 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3011 bool fTrickleWait = ((hashRand & 3) != 0);
3013 // always trickle our own transactions
3016 TRY_CRITICAL_BLOCK(cs_mapWallet)
3018 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
3019 if (mi != mapWallet.end())
3021 CWalletTx& wtx = (*mi).second;
3023 fTrickleWait = true;
3030 vInvWait.push_back(inv);
3035 // returns true if wasn't already contained in the set
3036 if (pto->setInventoryKnown.insert(inv).second)
3038 vInv.push_back(inv);
3039 if (vInv.size() >= 1000)
3041 pto->PushMessage("inv", vInv);
3046 pto->vInventoryToSend = vInvWait;
3049 pto->PushMessage("inv", vInv);
3055 vector<CInv> vGetData;
3056 int64 nNow = GetTime() * 1000000;
3058 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3060 const CInv& inv = (*pto->mapAskFor.begin()).second;
3061 if (!AlreadyHave(txdb, inv))
3063 printf("sending getdata: %s\n", inv.ToString().c_str());
3064 vGetData.push_back(inv);
3065 if (vGetData.size() >= 1000)
3067 pto->PushMessage("getdata", vGetData);
3071 pto->mapAskFor.erase(pto->mapAskFor.begin());
3073 if (!vGetData.empty())
3074 pto->PushMessage("getdata", vGetData);
3093 //////////////////////////////////////////////////////////////////////////////
3098 void GenerateBitcoins(bool fGenerate)
3100 if (fGenerateBitcoins != fGenerate)
3102 fGenerateBitcoins = fGenerate;
3103 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3106 if (fGenerateBitcoins)
3108 int nProcessors = boost::thread::hardware_concurrency();
3109 printf("%d processors\n", nProcessors);
3110 if (nProcessors < 1)
3112 if (fLimitProcessors && nProcessors > nLimitProcessors)
3113 nProcessors = nLimitProcessors;
3114 int nAddThreads = nProcessors - vnThreadsRunning[3];
3115 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3116 for (int i = 0; i < nAddThreads; i++)
3118 if (!CreateThread(ThreadBitcoinMiner, NULL))
3119 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3125 void ThreadBitcoinMiner(void* parg)
3129 vnThreadsRunning[3]++;
3131 vnThreadsRunning[3]--;
3133 catch (std::exception& e) {
3134 vnThreadsRunning[3]--;
3135 PrintException(&e, "ThreadBitcoinMiner()");
3137 vnThreadsRunning[3]--;
3138 PrintException(NULL, "ThreadBitcoinMiner()");
3140 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3142 if (vnThreadsRunning[3] == 0)
3144 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3148 int FormatHashBlocks(void* pbuffer, unsigned int len)
3150 unsigned char* pdata = (unsigned char*)pbuffer;
3151 unsigned int blocks = 1 + ((len + 8) / 64);
3152 unsigned char* pend = pdata + 64 * blocks;
3153 memset(pdata + len, 0, 64 * blocks - len);
3155 unsigned int bits = len * 8;
3156 pend[-1] = (bits >> 0) & 0xff;
3157 pend[-2] = (bits >> 8) & 0xff;
3158 pend[-3] = (bits >> 16) & 0xff;
3159 pend[-4] = (bits >> 24) & 0xff;
3163 using CryptoPP::ByteReverse;
3165 static const unsigned int pSHA256InitState[8] =
3166 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3168 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3170 memcpy(pstate, pinit, 32);
3171 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3175 // ScanHash scans nonces looking for a hash with at least some zero bits.
3176 // It operates on big endian data. Caller does the byte reversing.
3177 // All input buffers are 16-byte aligned. nNonce is usually preserved
3178 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3179 // the block is rebuilt and nNonce starts over at zero.
3181 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3183 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3187 // Hash pdata using pmidstate as the starting state into
3188 // preformatted buffer phash1, then hash phash1 into phash
3190 SHA256Transform(phash1, pdata, pmidstate);
3191 SHA256Transform(phash, phash1, pSHA256InitState);
3193 // Return the nonce if the hash has at least some zero bits,
3194 // caller will check if it has enough to reach the target
3195 if (((unsigned short*)phash)[14] == 0)
3198 // If nothing found after trying for a while, return -1
3199 if ((nNonce & 0xffff) == 0)
3201 nHashesDone = 0xffff+1;
3212 set<uint256> setDependsOn;
3215 COrphan(CTransaction* ptxIn)
3223 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3224 BOOST_FOREACH(uint256 hash, setDependsOn)
3225 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3230 CBlock* CreateNewBlock(CReserveKey& reservekey)
3232 CBlockIndex* pindexPrev = pindexBest;
3235 auto_ptr<CBlock> pblock(new CBlock());
3239 // Create coinbase tx
3241 txNew.vin.resize(1);
3242 txNew.vin[0].prevout.SetNull();
3243 txNew.vout.resize(1);
3244 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3246 // Add our coinbase tx as first transaction
3247 pblock->vtx.push_back(txNew);
3249 // Collect memory pool transactions into the block
3251 CRITICAL_BLOCK(cs_main)
3252 CRITICAL_BLOCK(cs_mapTransactions)
3256 // Priority order to process transactions
3257 list<COrphan> vOrphan; // list memory doesn't move
3258 map<uint256, vector<COrphan*> > mapDependers;
3259 multimap<double, CTransaction*> mapPriority;
3260 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3262 CTransaction& tx = (*mi).second;
3263 if (tx.IsCoinBase() || !tx.IsFinal())
3266 COrphan* porphan = NULL;
3267 double dPriority = 0;
3268 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3270 // Read prev transaction
3271 CTransaction txPrev;
3273 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3275 // Has to wait for dependencies
3278 // Use list for automatic deletion
3279 vOrphan.push_back(COrphan(&tx));
3280 porphan = &vOrphan.back();
3282 mapDependers[txin.prevout.hash].push_back(porphan);
3283 porphan->setDependsOn.insert(txin.prevout.hash);
3286 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3288 // Read block header
3289 int nConf = txindex.GetDepthInMainChain();
3291 dPriority += (double)nValueIn * nConf;
3293 if (fDebug && GetBoolArg("-printpriority"))
3294 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3297 // Priority is sum(valuein * age) / txsize
3298 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3301 porphan->dPriority = dPriority;
3303 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3305 if (fDebug && GetBoolArg("-printpriority"))
3307 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3314 // Collect transactions into block
3315 map<uint256, CTxIndex> mapTestPool;
3316 uint64 nBlockSize = 1000;
3317 int nBlockSigOps = 100;
3318 while (!mapPriority.empty())
3320 // Take highest priority transaction off priority queue
3321 double dPriority = -(*mapPriority.begin()).first;
3322 CTransaction& tx = *(*mapPriority.begin()).second;
3323 mapPriority.erase(mapPriority.begin());
3326 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3327 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3329 int nTxSigOps = tx.GetSigOpCount();
3330 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3333 // Transaction fee required depends on block size
3334 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3335 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3337 // Connecting shouldn't fail due to dependency on other memory pool transactions
3338 // because we're already processing them in order of dependency
3339 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3340 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3342 swap(mapTestPool, mapTestPoolTmp);
3345 pblock->vtx.push_back(tx);
3346 nBlockSize += nTxSize;
3347 nBlockSigOps += nTxSigOps;
3349 // Add transactions that depend on this one to the priority queue
3350 uint256 hash = tx.GetHash();
3351 if (mapDependers.count(hash))
3353 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3355 if (!porphan->setDependsOn.empty())
3357 porphan->setDependsOn.erase(hash);
3358 if (porphan->setDependsOn.empty())
3359 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3365 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3368 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3369 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3370 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3371 pblock->nBits = GetNextWorkRequired(pindexPrev);
3374 return pblock.release();
3378 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3380 // Update nExtraNonce
3381 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3382 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3387 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3388 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3392 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3395 // Prebuild hash buffers
3402 uint256 hashPrevBlock;
3403 uint256 hashMerkleRoot;
3406 unsigned int nNonce;
3409 unsigned char pchPadding0[64];
3411 unsigned char pchPadding1[64];
3414 memset(&tmp, 0, sizeof(tmp));
3416 tmp.block.nVersion = pblock->nVersion;
3417 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3418 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3419 tmp.block.nTime = pblock->nTime;
3420 tmp.block.nBits = pblock->nBits;
3421 tmp.block.nNonce = pblock->nNonce;
3423 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3424 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3426 // Byte swap all the input buffer
3427 for (int i = 0; i < sizeof(tmp)/4; i++)
3428 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3430 // Precalc the first half of the first hash, which stays constant
3431 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3433 memcpy(pdata, &tmp.block, 128);
3434 memcpy(phash1, &tmp.hash1, 64);
3438 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3440 uint256 hash = pblock->GetHash();
3441 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3443 if (hash > hashTarget)
3447 printf("BitcoinMiner:\n");
3448 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3450 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3451 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3454 CRITICAL_BLOCK(cs_main)
3456 if (pblock->hashPrevBlock != hashBestChain)
3457 return error("BitcoinMiner : generated block is stale");
3459 // Remove key from key pool
3460 reservekey.KeepKey();
3462 // Track how many getdata requests this block gets
3463 CRITICAL_BLOCK(cs_mapRequestCount)
3464 mapRequestCount[pblock->GetHash()] = 0;
3466 // Process this block the same as if we had received it from another node
3467 if (!ProcessBlock(NULL, pblock))
3468 return error("BitcoinMiner : ProcessBlock, block not accepted");
3478 printf("BitcoinMiner started\n");
3479 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3481 // Each thread has its own key and counter
3482 CReserveKey reservekey;
3483 unsigned int nExtraNonce = 0;
3484 int64 nPrevTime = 0;
3486 while (fGenerateBitcoins)
3488 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3492 while (vNodes.empty() || IsInitialBlockDownload())
3497 if (!fGenerateBitcoins)
3505 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3506 CBlockIndex* pindexPrev = pindexBest;
3508 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3511 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3513 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3517 // Prebuild hash buffers
3519 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3520 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3521 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3523 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3525 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3526 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3532 int64 nStart = GetTime();
3533 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3535 uint256& hash = *alignup<16>(hashbuf);
3538 unsigned int nHashesDone = 0;
3539 unsigned int nNonceFound;
3542 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3543 (char*)&hash, nHashesDone);
3545 // Check if something found
3546 if (nNonceFound != -1)
3548 for (int i = 0; i < sizeof(hash)/4; i++)
3549 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3551 if (hash <= hashTarget)
3554 pblock->nNonce = ByteReverse(nNonceFound);
3555 assert(hash == pblock->GetHash());
3557 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3558 CheckWork(pblock.get(), reservekey);
3559 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3565 static int64 nHashCounter;
3566 if (nHPSTimerStart == 0)
3568 nHPSTimerStart = GetTimeMillis();
3572 nHashCounter += nHashesDone;
3573 if (GetTimeMillis() - nHPSTimerStart > 4000)
3575 static CCriticalSection cs;
3578 if (GetTimeMillis() - nHPSTimerStart > 4000)
3580 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3581 nHPSTimerStart = GetTimeMillis();
3583 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3584 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3585 static int64 nLogTime;
3586 if (GetTime() - nLogTime > 30 * 60)
3588 nLogTime = GetTime();
3589 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3590 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3596 // Check for stop or if block needs to be rebuilt
3599 if (!fGenerateBitcoins)
3601 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3605 if (nBlockNonce >= 0xffff0000)
3607 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3609 if (pindexPrev != pindexBest)
3612 // Update nTime every few seconds
3613 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3614 nBlockTime = ByteReverse(pblock->nTime);
3636 //////////////////////////////////////////////////////////////////////////////
3644 int64 nStart = GetTimeMillis();
3647 CRITICAL_BLOCK(cs_mapWallet)
3649 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3651 CWalletTx* pcoin = &(*it).second;
3652 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3654 nTotal += pcoin->GetAvailableCredit();
3658 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3663 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3665 setCoinsRet.clear();
3668 // List of values less than target
3669 pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;
3670 coinLowestLarger.first = INT64_MAX;
3671 coinLowestLarger.second.first = NULL;
3672 vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;
3673 int64 nTotalLower = 0;
3675 CRITICAL_BLOCK(cs_mapWallet)
3677 vector<CWalletTx*> vCoins;
3678 vCoins.reserve(mapWallet.size());
3679 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3680 vCoins.push_back(&(*it).second);
3681 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3683 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
3685 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3688 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3691 int nDepth = pcoin->GetDepthInMainChain();
3692 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3695 for (int i = 0; i < pcoin->vout.size(); i++)
3697 if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())
3700 int64 n = pcoin->vout[i].nValue;
3705 pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
3707 if (n == nTargetValue)
3709 setCoinsRet.insert(coin.second);
3710 nValueRet += coin.first;
3713 else if (n < nTargetValue + CENT)
3715 vValue.push_back(coin);
3718 else if (n < coinLowestLarger.first)
3720 coinLowestLarger = coin;
3726 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
3728 for (int i = 0; i < vValue.size(); ++i)
3730 setCoinsRet.insert(vValue[i].second);
3731 nValueRet += vValue[i].first;
3736 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
3738 if (coinLowestLarger.second.first == NULL)
3740 setCoinsRet.insert(coinLowestLarger.second);
3741 nValueRet += coinLowestLarger.first;
3745 if (nTotalLower >= nTargetValue + CENT)
3746 nTargetValue += CENT;
3748 // Solve subset sum by stochastic approximation
3749 sort(vValue.rbegin(), vValue.rend());
3750 vector<char> vfIncluded;
3751 vector<char> vfBest(vValue.size(), true);
3752 int64 nBest = nTotalLower;
3754 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3756 vfIncluded.assign(vValue.size(), false);
3758 bool fReachedTarget = false;
3759 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3761 for (int i = 0; i < vValue.size(); i++)
3763 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3765 nTotal += vValue[i].first;
3766 vfIncluded[i] = true;
3767 if (nTotal >= nTargetValue)
3769 fReachedTarget = true;
3773 vfBest = vfIncluded;
3775 nTotal -= vValue[i].first;
3776 vfIncluded[i] = false;
3783 // If the next larger is still closer, return it
3784 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
3786 setCoinsRet.insert(coinLowestLarger.second);
3787 nValueRet += coinLowestLarger.first;
3790 for (int i = 0; i < vValue.size(); i++)
3793 setCoinsRet.insert(vValue[i].second);
3794 nValueRet += vValue[i].first;
3798 printf("SelectCoins() best subset: ");
3799 for (int i = 0; i < vValue.size(); i++)
3801 printf("%s ", FormatMoney(vValue[i].first).c_str());
3802 printf("total %s\n", FormatMoney(nBest).c_str());
3808 bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3810 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
3811 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
3812 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
3818 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3821 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3827 if (vecSend.empty() || nValue < 0)
3830 CRITICAL_BLOCK(cs_main)
3832 // txdb must be opened before the mapWallet lock
3834 CRITICAL_BLOCK(cs_mapWallet)
3836 nFeeRet = nTransactionFee;
3840 wtxNew.vout.clear();
3841 wtxNew.fFromMe = true;
3843 int64 nTotalValue = nValue + nFeeRet;
3844 double dPriority = 0;
3845 // vouts to the payees
3846 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3847 wtxNew.vout.push_back(CTxOut(s.second, s.first));
3849 // Choose coins to use
3850 set<pair<CWalletTx*,unsigned int> > setCoins;
3852 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
3854 BOOST_FOREACH(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)
3856 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
3857 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
3860 // Fill a vout back to self with any change
3861 int64 nChange = nValueIn - nTotalValue;
3862 if (nChange >= CENT)
3864 // Note: We use a new key here to keep it from being obvious which side is the change.
3865 // The drawback is that by not reusing a previous key, the change may be lost if a
3866 // backup is restored, if the backup doesn't have the new private key for the change.
3867 // If we reused the old key, it would be possible to add code to look for and
3868 // rediscover unknown transactions that were written with keys of ours to recover
3869 // post-backup change.
3871 // Reserve a new key pair from key pool
3872 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3873 assert(mapKeys.count(vchPubKey));
3875 // Fill a vout to ourself, using same address type as the payment
3876 CScript scriptChange;
3877 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
3878 scriptChange.SetBitcoinAddress(vchPubKey);
3880 scriptChange << vchPubKey << OP_CHECKSIG;
3882 // Insert change txn at random position:
3883 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
3884 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
3887 reservekey.ReturnKey();
3890 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3891 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
3895 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3896 if (!SignSignature(*coin.first, wtxNew, nIn++))
3900 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3901 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3903 dPriority /= nBytes;
3905 // Check that enough fee is included
3906 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3907 bool fAllowFree = CTransaction::AllowFree(dPriority);
3908 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
3909 if (nFeeRet < max(nPayFee, nMinFee))
3911 nFeeRet = max(nPayFee, nMinFee);
3915 // Fill vtxPrev by copying from previous transactions vtxPrev
3916 wtxNew.AddSupportingTransactions(txdb);
3917 wtxNew.fTimeReceivedIsTxTime = true;
3926 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3928 vector< pair<CScript, int64> > vecSend;
3929 vecSend.push_back(make_pair(scriptPubKey, nValue));
3930 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
3933 // Call after CreateTransaction unless you want to abort
3934 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3936 CRITICAL_BLOCK(cs_main)
3938 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3939 CRITICAL_BLOCK(cs_mapWallet)
3941 // This is only to keep the database open to defeat the auto-flush for the
3942 // duration of this scope. This is the only place where this optimization
3943 // maybe makes sense; please don't do it anywhere else.
3944 CWalletDB walletdb("r");
3946 // Take key pair from key pool so it won't be used again
3947 reservekey.KeepKey();
3949 // Add tx to wallet, because if it has change it's also ours,
3950 // otherwise just for transaction history.
3951 AddToWallet(wtxNew);
3953 // Mark old coins as spent
3954 set<CWalletTx*> setCoins;
3955 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3957 CWalletTx &pcoin = mapWallet[txin.prevout.hash];
3958 pcoin.MarkSpent(txin.prevout.n);
3959 pcoin.WriteToDisk();
3960 vWalletUpdated.push_back(pcoin.GetHash());
3964 // Track how many getdata requests our transaction gets
3965 CRITICAL_BLOCK(cs_mapRequestCount)
3966 mapRequestCount[wtxNew.GetHash()] = 0;
3969 if (!wtxNew.AcceptToMemoryPool())
3971 // This must not fail. The transaction has already been signed and recorded.
3972 printf("CommitTransaction() : Error: Transaction not valid");
3975 wtxNew.RelayWalletTransaction();
3984 // requires cs_main lock
3985 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3987 CReserveKey reservekey;
3989 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3992 if (nValue + nFeeRequired > GetBalance())
3993 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());
3995 strError = _("Error: Transaction creation failed ");
3996 printf("SendMoney() : %s", strError.c_str());
4000 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4003 if (!CommitTransaction(wtxNew, reservekey))
4004 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.");
4012 // requires cs_main lock
4013 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4017 return _("Invalid amount");
4018 if (nValue + nTransactionFee > GetBalance())
4019 return _("Insufficient funds");
4021 // Parse bitcoin address
4022 CScript scriptPubKey;
4023 if (!scriptPubKey.SetBitcoinAddress(strAddress))
4024 return _("Invalid bitcoin address");
4026 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);