1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "cryptopp/sha.h"
15 CCriticalSection cs_main;
17 map<uint256, CTransaction> mapTransactions;
18 CCriticalSection cs_mapTransactions;
19 unsigned int nTransactionsUpdated = 0;
20 map<COutPoint, CInPoint> mapNextTx;
22 map<uint256, CBlockIndex*> mapBlockIndex;
23 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
24 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
25 CBlockIndex* pindexGenesisBlock = NULL;
27 CBigNum bnBestChainWork = 0;
28 CBigNum bnBestInvalidWork = 0;
29 uint256 hashBestChain = 0;
30 CBlockIndex* pindexBest = NULL;
31 int64 nTimeBestReceived = 0;
33 map<uint256, CBlock*> mapOrphanBlocks;
34 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
36 map<uint256, CDataStream*> mapOrphanTransactions;
37 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
39 map<uint256, CWalletTx> mapWallet;
40 vector<uint256> vWalletUpdated;
41 CCriticalSection cs_mapWallet;
43 map<vector<unsigned char>, CPrivKey> mapKeys;
44 map<uint160, vector<unsigned char> > mapPubKeys;
45 CCriticalSection cs_mapKeys;
48 map<uint256, int> mapRequestCount;
49 CCriticalSection cs_mapRequestCount;
51 map<string, string> mapAddressBook;
52 CCriticalSection cs_mapAddressBook;
54 vector<unsigned char> vchDefaultKey;
60 int fGenerateBitcoins = false;
61 int64 nTransactionFee = 0;
62 CAddress addrIncoming;
63 int fLimitProcessors = false;
64 int nLimitProcessors = 1;
65 int fMinimizeToTray = true;
66 int fMinimizeOnClose = true;
79 //////////////////////////////////////////////////////////////////////////////
84 bool AddKey(const CKey& key)
86 CRITICAL_BLOCK(cs_mapKeys)
88 mapKeys[key.GetPubKey()] = key.GetPrivKey();
89 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
91 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
94 vector<unsigned char> GenerateNewKey()
100 throw runtime_error("GenerateNewKey() : AddKey failed");
101 return key.GetPubKey();
107 //////////////////////////////////////////////////////////////////////////////
112 bool AddToWallet(const CWalletTx& wtxIn)
114 uint256 hash = wtxIn.GetHash();
115 CRITICAL_BLOCK(cs_mapWallet)
117 // Inserts only if not already there, returns tx inserted or tx found
118 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
119 CWalletTx& wtx = (*ret.first).second;
120 bool fInsertedNew = ret.second;
122 wtx.nTimeReceived = GetAdjustedTime();
124 bool fUpdated = false;
128 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
130 wtx.hashBlock = wtxIn.hashBlock;
133 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
135 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
136 wtx.nIndex = wtxIn.nIndex;
139 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
141 wtx.fFromMe = wtxIn.fFromMe;
144 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
148 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
151 if (fInsertedNew || fUpdated)
152 if (!wtx.WriteToDisk())
155 // If default receiving address gets used, replace it with a new one
156 CScript scriptDefaultKey;
157 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
158 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
160 if (txout.scriptPubKey == scriptDefaultKey)
163 vchDefaultKey = GetKeyFromKeyPool();
164 walletdb.WriteDefaultKey(vchDefaultKey);
165 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
170 vWalletUpdated.push_back(hash);
178 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false)
180 uint256 hash = tx.GetHash();
181 bool fExisted = mapWallet.count(hash);
182 if (fExisted && !fUpdate) return false;
183 if (fExisted || tx.IsMine() || tx.IsFromMe())
186 // Get merkle branch if transaction was found in a block
188 wtx.SetMerkleBranch(pblock);
189 return AddToWallet(wtx);
194 bool EraseFromWallet(uint256 hash)
196 CRITICAL_BLOCK(cs_mapWallet)
198 if (mapWallet.erase(hash))
199 CWalletDB().EraseTx(hash);
204 void WalletUpdateSpent(const COutPoint& prevout)
206 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
207 // Update the wallet spent flag if it doesn't know due to wallet.dat being
208 // restored from backup or the user making copies of wallet.dat.
209 CRITICAL_BLOCK(cs_mapWallet)
211 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
212 if (mi != mapWallet.end())
214 CWalletTx& wtx = (*mi).second;
215 if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())
217 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
218 wtx.MarkSpent(prevout.n);
220 vWalletUpdated.push_back(prevout.hash);
233 //////////////////////////////////////////////////////////////////////////////
235 // mapOrphanTransactions
238 void AddOrphanTx(const CDataStream& vMsg)
241 CDataStream(vMsg) >> tx;
242 uint256 hash = tx.GetHash();
243 if (mapOrphanTransactions.count(hash))
245 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
246 BOOST_FOREACH(const CTxIn& txin, tx.vin)
247 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
250 void EraseOrphanTx(uint256 hash)
252 if (!mapOrphanTransactions.count(hash))
254 const CDataStream* pvMsg = mapOrphanTransactions[hash];
256 CDataStream(*pvMsg) >> tx;
257 BOOST_FOREACH(const CTxIn& txin, tx.vin)
259 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
260 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
262 if ((*mi).second == pvMsg)
263 mapOrphanTransactionsByPrev.erase(mi++);
269 mapOrphanTransactions.erase(hash);
279 //////////////////////////////////////////////////////////////////////////////
281 // CTransaction and CTxIndex
284 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
287 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
289 if (!ReadFromDisk(txindexRet.pos))
291 if (prevout.n >= vout.size())
299 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
302 return ReadFromDisk(txdb, prevout, txindex);
305 bool CTransaction::ReadFromDisk(COutPoint prevout)
309 return ReadFromDisk(txdb, prevout, txindex);
312 bool CTxIn::IsMine() const
314 CRITICAL_BLOCK(cs_mapWallet)
316 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
317 if (mi != mapWallet.end())
319 const CWalletTx& prev = (*mi).second;
320 if (prevout.n < prev.vout.size())
321 if (prev.vout[prevout.n].IsMine())
328 int64 CTxIn::GetDebit() const
330 CRITICAL_BLOCK(cs_mapWallet)
332 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
333 if (mi != mapWallet.end())
335 const CWalletTx& prev = (*mi).second;
336 if (prevout.n < prev.vout.size())
337 if (prev.vout[prevout.n].IsMine())
338 return prev.vout[prevout.n].nValue;
344 int64 CWalletTx::GetTxTime() const
346 if (!fTimeReceivedIsTxTime && hashBlock != 0)
348 // If we did not receive the transaction directly, we rely on the block's
349 // time to figure out when it happened. We use the median over a range
350 // of blocks to try to filter out inaccurate block times.
351 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
352 if (mi != mapBlockIndex.end())
354 CBlockIndex* pindex = (*mi).second;
356 return pindex->GetMedianTime();
359 return nTimeReceived;
362 int CWalletTx::GetRequestCount() const
364 // Returns -1 if it wasn't being tracked
366 CRITICAL_BLOCK(cs_mapRequestCount)
373 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
374 if (mi != mapRequestCount.end())
375 nRequests = (*mi).second;
380 // Did anyone request this transaction?
381 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
382 if (mi != mapRequestCount.end())
384 nRequests = (*mi).second;
386 // How about the block it's in?
387 if (nRequests == 0 && hashBlock != 0)
389 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
390 if (mi != mapRequestCount.end())
391 nRequests = (*mi).second;
393 nRequests = 1; // If it's in someone else's block it must have got out
401 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
402 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
404 nGeneratedImmature = nGeneratedMature = nFee = 0;
405 listReceived.clear();
407 strSentAccount = strFromAccount;
411 if (GetBlocksToMaturity() > 0)
412 nGeneratedImmature = CTransaction::GetCredit();
414 nGeneratedMature = GetCredit();
419 int64 nDebit = GetDebit();
420 if (nDebit > 0) // debit>0 means we signed/sent this transaction
422 int64 nValueOut = GetValueOut();
423 nFee = nDebit - nValueOut;
426 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
427 // but non-standard clients might (so return a list of address/amount pairs)
428 BOOST_FOREACH(const CTxOut& txout, vout)
432 vector<unsigned char> vchPubKey;
433 if (ExtractHash160(txout.scriptPubKey, hash160))
434 address = Hash160ToAddress(hash160);
435 else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))
436 address = PubKeyToAddress(vchPubKey);
439 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
440 this->GetHash().ToString().c_str());
441 address = " unknown ";
444 // Don't report 'change' txouts
445 if (nDebit > 0 && txout.IsChange())
449 listSent.push_back(make_pair(address, txout.nValue));
452 listReceived.push_back(make_pair(address, txout.nValue));
457 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
458 int64& nSent, int64& nFee) const
460 nGenerated = nReceived = nSent = nFee = 0;
462 int64 allGeneratedImmature, allGeneratedMature, allFee;
463 allGeneratedImmature = allGeneratedMature = allFee = 0;
464 string strSentAccount;
465 list<pair<string, int64> > listReceived;
466 list<pair<string, int64> > listSent;
467 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
469 if (strAccount == "")
470 nGenerated = allGeneratedMature;
471 if (strAccount == strSentAccount)
473 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
477 CRITICAL_BLOCK(cs_mapAddressBook)
479 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
481 if (mapAddressBook.count(r.first))
483 if (mapAddressBook[r.first] == strAccount)
485 nReceived += r.second;
488 else if (strAccount.empty())
490 nReceived += r.second;
498 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
510 // Load the block this tx is in
512 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
514 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
519 // Update the tx's hashBlock
520 hashBlock = pblock->GetHash();
522 // Locate the transaction
523 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
524 if (pblock->vtx[nIndex] == *(CTransaction*)this)
526 if (nIndex == pblock->vtx.size())
528 vMerkleBranch.clear();
530 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
534 // Fill in merkle branch
535 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
538 // Is the tx in a block that's in the main chain
539 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
540 if (mi == mapBlockIndex.end())
542 CBlockIndex* pindex = (*mi).second;
543 if (!pindex || !pindex->IsInMainChain())
546 return pindexBest->nHeight - pindex->nHeight + 1;
551 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
555 const int COPY_DEPTH = 3;
556 if (SetMerkleBranch() < COPY_DEPTH)
558 vector<uint256> vWorkQueue;
559 BOOST_FOREACH(const CTxIn& txin, vin)
560 vWorkQueue.push_back(txin.prevout.hash);
562 // This critsect is OK because txdb is already open
563 CRITICAL_BLOCK(cs_mapWallet)
565 map<uint256, const CMerkleTx*> mapWalletPrev;
566 set<uint256> setAlreadyDone;
567 for (int i = 0; i < vWorkQueue.size(); i++)
569 uint256 hash = vWorkQueue[i];
570 if (setAlreadyDone.count(hash))
572 setAlreadyDone.insert(hash);
575 if (mapWallet.count(hash))
577 tx = mapWallet[hash];
578 BOOST_FOREACH(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
579 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
581 else if (mapWalletPrev.count(hash))
583 tx = *mapWalletPrev[hash];
585 else if (!fClient && txdb.ReadDiskTx(hash, tx))
591 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
595 int nDepth = tx.SetMerkleBranch();
596 vtxPrev.push_back(tx);
598 if (nDepth < COPY_DEPTH)
599 BOOST_FOREACH(const CTxIn& txin, tx.vin)
600 vWorkQueue.push_back(txin.prevout.hash);
605 reverse(vtxPrev.begin(), vtxPrev.end());
618 bool CTransaction::CheckTransaction() const
620 // Basic checks that don't depend on any context
621 if (vin.empty() || vout.empty())
622 return error("CTransaction::CheckTransaction() : vin or vout empty");
625 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
626 return error("CTransaction::CheckTransaction() : size limits failed");
628 // Check for negative or overflow output values
630 BOOST_FOREACH(const CTxOut& txout, vout)
632 if (txout.nValue < 0)
633 return error("CTransaction::CheckTransaction() : txout.nValue negative");
634 if (txout.nValue > MAX_MONEY)
635 return error("CTransaction::CheckTransaction() : txout.nValue too high");
636 nValueOut += txout.nValue;
637 if (!MoneyRange(nValueOut))
638 return error("CTransaction::CheckTransaction() : txout total out of range");
643 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
644 return error("CTransaction::CheckTransaction() : coinbase script size");
648 BOOST_FOREACH(const CTxIn& txin, vin)
649 if (txin.prevout.IsNull())
650 return error("CTransaction::CheckTransaction() : prevout is null");
656 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
659 *pfMissingInputs = false;
661 if (!CheckTransaction())
662 return error("AcceptToMemoryPool() : CheckTransaction failed");
664 // Coinbase is only valid in a block, not as a loose transaction
666 return error("AcceptToMemoryPool() : coinbase as individual tx");
668 // To help v0.1.5 clients who would see it as a negative number
669 if ((int64)nLockTime > INT_MAX)
670 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
673 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
674 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
675 // attacks disallow transactions with more than one SigOp per 34 bytes.
676 // 34 bytes because a TxOut is:
677 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
678 if (GetSigOpCount() > nSize / 34 || nSize < 100)
679 return error("AcceptToMemoryPool() : nonstandard transaction");
681 // Rather not work on nonstandard transactions (unless -testnet)
682 if (!fTestNet && !IsStandard())
683 return error("AcceptToMemoryPool() : nonstandard transaction type");
685 // Do we already have it?
686 uint256 hash = GetHash();
687 CRITICAL_BLOCK(cs_mapTransactions)
688 if (mapTransactions.count(hash))
691 if (txdb.ContainsTx(hash))
694 // Check for conflicts with in-memory transactions
695 CTransaction* ptxOld = NULL;
696 for (int i = 0; i < vin.size(); i++)
698 COutPoint outpoint = vin[i].prevout;
699 if (mapNextTx.count(outpoint))
701 // Disable replacement feature for now
704 // Allow replacing with a newer version of the same transaction
707 ptxOld = mapNextTx[outpoint].ptx;
708 if (ptxOld->IsFinal())
710 if (!IsNewerThan(*ptxOld))
712 for (int i = 0; i < vin.size(); i++)
714 COutPoint outpoint = vin[i].prevout;
715 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
724 // Check against previous transactions
725 map<uint256, CTxIndex> mapUnused;
727 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
730 *pfMissingInputs = true;
731 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
734 // Don't accept it if it can't get into a block
735 if (nFees < GetMinFee(1000))
736 return error("AcceptToMemoryPool() : not enough fees");
738 // Continuously rate-limit free transactions
739 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
740 // be annoying or make other's transactions take longer to confirm.
741 if (nFees < MIN_TX_FEE)
743 static CCriticalSection cs;
744 static double dFreeCount;
745 static int64 nLastTime;
746 int64 nNow = GetTime();
750 // Use an exponentially decaying ~10-minute window:
751 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
753 // -limitfreerelay unit is thousand-bytes-per-minute
754 // At default rate it would take over a month to fill 1GB
755 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())
756 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
758 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
764 // Store transaction in memory
765 CRITICAL_BLOCK(cs_mapTransactions)
769 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
770 ptxOld->RemoveFromMemoryPool();
772 AddToMemoryPoolUnchecked();
775 ///// are we sure this is ok when loading transactions or restoring block txes
776 // If updated, erase old tx from wallet
778 EraseFromWallet(ptxOld->GetHash());
780 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
785 bool CTransaction::AddToMemoryPoolUnchecked()
787 // Add to memory pool without checking anything. Don't call this directly,
788 // call AcceptToMemoryPool to properly check the transaction first.
789 CRITICAL_BLOCK(cs_mapTransactions)
791 uint256 hash = GetHash();
792 mapTransactions[hash] = *this;
793 for (int i = 0; i < vin.size(); i++)
794 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
795 nTransactionsUpdated++;
801 bool CTransaction::RemoveFromMemoryPool()
803 // Remove transaction from memory pool
804 CRITICAL_BLOCK(cs_mapTransactions)
806 BOOST_FOREACH(const CTxIn& txin, vin)
807 mapNextTx.erase(txin.prevout);
808 mapTransactions.erase(GetHash());
809 nTransactionsUpdated++;
819 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
821 if (hashBlock == 0 || nIndex == -1)
824 // Find the block it claims to be in
825 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
826 if (mi == mapBlockIndex.end())
828 CBlockIndex* pindex = (*mi).second;
829 if (!pindex || !pindex->IsInMainChain())
832 // Make sure the merkle branch connects to this block
833 if (!fMerkleVerified)
835 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
837 fMerkleVerified = true;
840 nHeightRet = pindex->nHeight;
841 return pindexBest->nHeight - pindex->nHeight + 1;
845 int CMerkleTx::GetBlocksToMaturity() const
849 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
853 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
857 if (!IsInMainChain() && !ClientConnectInputs())
859 return CTransaction::AcceptToMemoryPool(txdb, false);
863 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
869 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
871 CRITICAL_BLOCK(cs_mapTransactions)
873 // Add previous supporting transactions first
874 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
876 if (!tx.IsCoinBase())
878 uint256 hash = tx.GetHash();
879 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
880 tx.AcceptToMemoryPool(txdb, fCheckInputs);
883 return AcceptToMemoryPool(txdb, fCheckInputs);
888 int ScanForWalletTransactions(CBlockIndex* pindexStart)
892 CBlockIndex* pindex = pindexStart;
893 CRITICAL_BLOCK(cs_mapWallet)
898 block.ReadFromDisk(pindex, true);
899 BOOST_FOREACH(CTransaction& tx, block.vtx)
901 if (AddToWalletIfInvolvingMe(tx, &block))
904 pindex = pindex->pnext;
910 void ReacceptWalletTransactions()
914 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
917 vector<CDiskTxPos> vMissingTx;
918 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
920 CWalletTx& wtx = item.second;
921 if (wtx.IsCoinBase() && wtx.IsSpent(0))
925 bool fUpdated = false;
926 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
928 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
929 if (txindex.vSpent.size() != wtx.vout.size())
931 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
934 for (int i = 0; i < txindex.vSpent.size(); i++)
938 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
942 vMissingTx.push_back(txindex.vSpent[i]);
947 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
954 // Reaccept any txes of ours that aren't already in a block
955 if (!wtx.IsCoinBase())
956 wtx.AcceptWalletTransaction(txdb, false);
959 if (!vMissingTx.empty())
961 // TODO: optimize this to scan just part of the block chain?
962 if (ScanForWalletTransactions(pindexGenesisBlock))
963 fRepeat = true; // Found missing transactions: re-do Reaccept.
969 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
971 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
973 if (!tx.IsCoinBase())
975 uint256 hash = tx.GetHash();
976 if (!txdb.ContainsTx(hash))
977 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
982 uint256 hash = GetHash();
983 if (!txdb.ContainsTx(hash))
985 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
986 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
991 void ResendWalletTransactions()
993 // Do this infrequently and randomly to avoid giving away
994 // that these are our transactions.
995 static int64 nNextTime;
996 if (GetTime() < nNextTime)
998 bool fFirst = (nNextTime == 0);
999 nNextTime = GetTime() + GetRand(30 * 60);
1003 // Only do it if there's been a new block since last time
1004 static int64 nLastTime;
1005 if (nTimeBestReceived < nLastTime)
1007 nLastTime = GetTime();
1009 // Rebroadcast any of our txes that aren't in a block yet
1010 printf("ResendWalletTransactions()\n");
1012 CRITICAL_BLOCK(cs_mapWallet)
1014 // Sort them in chronological order
1015 multimap<unsigned int, CWalletTx*> mapSorted;
1016 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1018 CWalletTx& wtx = item.second;
1019 // Don't rebroadcast until it's had plenty of time that
1020 // it should have gotten in already by now.
1021 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1022 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1024 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1026 CWalletTx& wtx = *item.second;
1027 wtx.RelayWalletTransaction(txdb);
1032 int CTxIndex::GetDepthInMainChain() const
1034 // Read block header
1036 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
1038 // Find the block in the index
1039 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
1040 if (mi == mapBlockIndex.end())
1042 CBlockIndex* pindex = (*mi).second;
1043 if (!pindex || !pindex->IsInMainChain())
1045 return 1 + nBestHeight - pindex->nHeight;
1057 //////////////////////////////////////////////////////////////////////////////
1059 // CBlock and CBlockIndex
1062 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1064 if (!fReadTransactions)
1066 *this = pindex->GetBlockHeader();
1069 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1071 if (GetHash() != pindex->GetBlockHash())
1072 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1076 uint256 GetOrphanRoot(const CBlock* pblock)
1078 // Work back to the first block in the orphan chain
1079 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1080 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1081 return pblock->GetHash();
1084 int64 GetBlockValue(int nHeight, int64 nFees)
1086 int64 nSubsidy = 50 * COIN;
1088 // Subsidy is cut in half every 4 years
1089 nSubsidy >>= (nHeight / 210000);
1091 return nSubsidy + nFees;
1094 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1096 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1097 const int64 nTargetSpacing = 10 * 60;
1098 const int64 nInterval = nTargetTimespan / nTargetSpacing;
1101 if (pindexLast == NULL)
1102 return bnProofOfWorkLimit.GetCompact();
1104 // Only change once per interval
1105 if ((pindexLast->nHeight+1) % nInterval != 0)
1106 return pindexLast->nBits;
1108 // Go back by what we want to be 14 days worth of blocks
1109 const CBlockIndex* pindexFirst = pindexLast;
1110 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1111 pindexFirst = pindexFirst->pprev;
1112 assert(pindexFirst);
1114 // Limit adjustment step
1115 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1116 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1117 if (nActualTimespan < nTargetTimespan/4)
1118 nActualTimespan = nTargetTimespan/4;
1119 if (nActualTimespan > nTargetTimespan*4)
1120 nActualTimespan = nTargetTimespan*4;
1124 bnNew.SetCompact(pindexLast->nBits);
1125 bnNew *= nActualTimespan;
1126 bnNew /= nTargetTimespan;
1128 if (bnNew > bnProofOfWorkLimit)
1129 bnNew = bnProofOfWorkLimit;
1132 printf("GetNextWorkRequired RETARGET\n");
1133 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1134 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1135 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1137 return bnNew.GetCompact();
1140 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1143 bnTarget.SetCompact(nBits);
1146 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1147 return error("CheckProofOfWork() : nBits below minimum work");
1149 // Check proof of work matches claimed amount
1150 if (hash > bnTarget.getuint256())
1151 return error("CheckProofOfWork() : hash doesn't match nBits");
1156 bool IsInitialBlockDownload()
1158 if (pindexBest == NULL || (!fTestNet && nBestHeight < 118000))
1160 static int64 nLastUpdate;
1161 static CBlockIndex* pindexLastBest;
1162 if (pindexBest != pindexLastBest)
1164 pindexLastBest = pindexBest;
1165 nLastUpdate = GetTime();
1167 return (GetTime() - nLastUpdate < 10 &&
1168 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1171 void InvalidChainFound(CBlockIndex* pindexNew)
1173 if (pindexNew->bnChainWork > bnBestInvalidWork)
1175 bnBestInvalidWork = pindexNew->bnChainWork;
1176 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1179 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());
1180 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1181 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1182 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1195 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1197 // Relinquish previous transactions' spent pointers
1200 BOOST_FOREACH(const CTxIn& txin, vin)
1202 COutPoint prevout = txin.prevout;
1204 // Get prev txindex from disk
1206 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1207 return error("DisconnectInputs() : ReadTxIndex failed");
1209 if (prevout.n >= txindex.vSpent.size())
1210 return error("DisconnectInputs() : prevout.n out of range");
1212 // Mark outpoint as not spent
1213 txindex.vSpent[prevout.n].SetNull();
1216 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1217 return error("DisconnectInputs() : UpdateTxIndex failed");
1221 // Remove transaction from index
1222 if (!txdb.EraseTxIndex(*this))
1223 return error("DisconnectInputs() : EraseTxPos failed");
1229 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1230 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1232 // Take over previous transactions' spent pointers
1236 for (int i = 0; i < vin.size(); i++)
1238 COutPoint prevout = vin[i].prevout;
1243 if (fMiner && mapTestPool.count(prevout.hash))
1245 // Get txindex from current proposed changes
1246 txindex = mapTestPool[prevout.hash];
1250 // Read txindex from txdb
1251 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1253 if (!fFound && (fBlock || fMiner))
1254 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());
1257 CTransaction txPrev;
1258 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1260 // Get prev tx from single transactions in memory
1261 CRITICAL_BLOCK(cs_mapTransactions)
1263 if (!mapTransactions.count(prevout.hash))
1264 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1265 txPrev = mapTransactions[prevout.hash];
1268 txindex.vSpent.resize(txPrev.vout.size());
1272 // Get prev tx from disk
1273 if (!txPrev.ReadFromDisk(txindex.pos))
1274 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1277 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1278 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());
1280 // If prev is coinbase, check that it's matured
1281 if (txPrev.IsCoinBase())
1282 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1283 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1284 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1287 if (!VerifySignature(txPrev, *this, i))
1288 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1290 // Check for conflicts
1291 if (!txindex.vSpent[prevout.n].IsNull())
1292 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());
1294 // Check for negative or overflow input values
1295 nValueIn += txPrev.vout[prevout.n].nValue;
1296 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1297 return error("ConnectInputs() : txin values out of range");
1299 // Mark outpoints as spent
1300 txindex.vSpent[prevout.n] = posThisTx;
1305 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1306 return error("ConnectInputs() : UpdateTxIndex failed");
1310 mapTestPool[prevout.hash] = txindex;
1314 if (nValueIn < GetValueOut())
1315 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1317 // Tally transaction fees
1318 int64 nTxFee = nValueIn - GetValueOut();
1320 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1321 if (nTxFee < nMinFee)
1324 if (!MoneyRange(nFees))
1325 return error("ConnectInputs() : nFees out of range");
1330 // Add transaction to disk index
1331 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1332 return error("ConnectInputs() : AddTxPos failed");
1336 // Add transaction to test pool
1337 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1344 bool CTransaction::ClientConnectInputs()
1349 // Take over previous transactions' spent pointers
1350 CRITICAL_BLOCK(cs_mapTransactions)
1353 for (int i = 0; i < vin.size(); i++)
1355 // Get prev tx from single transactions in memory
1356 COutPoint prevout = vin[i].prevout;
1357 if (!mapTransactions.count(prevout.hash))
1359 CTransaction& txPrev = mapTransactions[prevout.hash];
1361 if (prevout.n >= txPrev.vout.size())
1365 if (!VerifySignature(txPrev, *this, i))
1366 return error("ConnectInputs() : VerifySignature failed");
1368 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1369 ///// this has to go away now that posNext is gone
1370 // // Check for conflicts
1371 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1372 // return error("ConnectInputs() : prev tx already used");
1374 // // Flag outpoints as used
1375 // txPrev.vout[prevout.n].posNext = posThisTx;
1377 nValueIn += txPrev.vout[prevout.n].nValue;
1379 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1380 return error("ClientConnectInputs() : txin values out of range");
1382 if (GetValueOut() > nValueIn)
1392 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1394 // Disconnect in reverse order
1395 for (int i = vtx.size()-1; i >= 0; i--)
1396 if (!vtx[i].DisconnectInputs(txdb))
1399 // Update block index on disk without changing it in memory.
1400 // The memory index structure will be changed after the db commits.
1403 CDiskBlockIndex blockindexPrev(pindex->pprev);
1404 blockindexPrev.hashNext = 0;
1405 if (!txdb.WriteBlockIndex(blockindexPrev))
1406 return error("DisconnectBlock() : WriteBlockIndex failed");
1412 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1414 // Check it again in case a previous version let a bad block in
1418 //// issue here: it doesn't know the version
1419 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1421 map<uint256, CTxIndex> mapUnused;
1423 BOOST_FOREACH(CTransaction& tx, vtx)
1425 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1426 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1428 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1432 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1435 // Update block index on disk without changing it in memory.
1436 // The memory index structure will be changed after the db commits.
1439 CDiskBlockIndex blockindexPrev(pindex->pprev);
1440 blockindexPrev.hashNext = pindex->GetBlockHash();
1441 if (!txdb.WriteBlockIndex(blockindexPrev))
1442 return error("ConnectBlock() : WriteBlockIndex failed");
1445 // Watch for transactions paying to me
1446 BOOST_FOREACH(CTransaction& tx, vtx)
1447 AddToWalletIfInvolvingMe(tx, this, true);
1452 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1454 printf("REORGANIZE\n");
1457 CBlockIndex* pfork = pindexBest;
1458 CBlockIndex* plonger = pindexNew;
1459 while (pfork != plonger)
1461 while (plonger->nHeight > pfork->nHeight)
1462 if (!(plonger = plonger->pprev))
1463 return error("Reorganize() : plonger->pprev is null");
1464 if (pfork == plonger)
1466 if (!(pfork = pfork->pprev))
1467 return error("Reorganize() : pfork->pprev is null");
1470 // List of what to disconnect
1471 vector<CBlockIndex*> vDisconnect;
1472 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1473 vDisconnect.push_back(pindex);
1475 // List of what to connect
1476 vector<CBlockIndex*> vConnect;
1477 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1478 vConnect.push_back(pindex);
1479 reverse(vConnect.begin(), vConnect.end());
1481 // Disconnect shorter branch
1482 vector<CTransaction> vResurrect;
1483 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1486 if (!block.ReadFromDisk(pindex))
1487 return error("Reorganize() : ReadFromDisk for disconnect failed");
1488 if (!block.DisconnectBlock(txdb, pindex))
1489 return error("Reorganize() : DisconnectBlock failed");
1491 // Queue memory transactions to resurrect
1492 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1493 if (!tx.IsCoinBase())
1494 vResurrect.push_back(tx);
1497 // Connect longer branch
1498 vector<CTransaction> vDelete;
1499 for (int i = 0; i < vConnect.size(); i++)
1501 CBlockIndex* pindex = vConnect[i];
1503 if (!block.ReadFromDisk(pindex))
1504 return error("Reorganize() : ReadFromDisk for connect failed");
1505 if (!block.ConnectBlock(txdb, pindex))
1509 return error("Reorganize() : ConnectBlock failed");
1512 // Queue memory transactions to delete
1513 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1514 vDelete.push_back(tx);
1516 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1517 return error("Reorganize() : WriteHashBestChain failed");
1519 // Make sure it's successfully written to disk before changing memory structure
1520 if (!txdb.TxnCommit())
1521 return error("Reorganize() : TxnCommit failed");
1523 // Disconnect shorter branch
1524 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1526 pindex->pprev->pnext = NULL;
1528 // Connect longer branch
1529 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1531 pindex->pprev->pnext = pindex;
1533 // Resurrect memory transactions that were in the disconnected branch
1534 BOOST_FOREACH(CTransaction& tx, vResurrect)
1535 tx.AcceptToMemoryPool(txdb, false);
1537 // Delete redundant memory transactions that are in the connected branch
1538 BOOST_FOREACH(CTransaction& tx, vDelete)
1539 tx.RemoveFromMemoryPool();
1545 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1547 uint256 hash = GetHash();
1550 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1552 txdb.WriteHashBestChain(hash);
1553 if (!txdb.TxnCommit())
1554 return error("SetBestChain() : TxnCommit failed");
1555 pindexGenesisBlock = pindexNew;
1557 else if (hashPrevBlock == hashBestChain)
1559 // Adding to current best branch
1560 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1563 InvalidChainFound(pindexNew);
1564 return error("SetBestChain() : ConnectBlock failed");
1566 if (!txdb.TxnCommit())
1567 return error("SetBestChain() : TxnCommit failed");
1569 // Add to current best branch
1570 pindexNew->pprev->pnext = pindexNew;
1572 // Delete redundant memory transactions
1573 BOOST_FOREACH(CTransaction& tx, vtx)
1574 tx.RemoveFromMemoryPool();
1579 if (!Reorganize(txdb, pindexNew))
1582 InvalidChainFound(pindexNew);
1583 return error("SetBestChain() : Reorganize failed");
1587 // Update best block in wallet (so we can detect restored wallets)
1588 if (!IsInitialBlockDownload())
1591 const CBlockLocator locator(pindexNew);
1592 if (!walletdb.WriteBestBlock(locator))
1593 return error("SetBestChain() : WriteWalletBest failed");
1597 hashBestChain = hash;
1598 pindexBest = pindexNew;
1599 nBestHeight = pindexBest->nHeight;
1600 bnBestChainWork = pindexNew->bnChainWork;
1601 nTimeBestReceived = GetTime();
1602 nTransactionsUpdated++;
1603 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1609 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1611 // Check for duplicate
1612 uint256 hash = GetHash();
1613 if (mapBlockIndex.count(hash))
1614 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1616 // Construct new block index object
1617 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1619 return error("AddToBlockIndex() : new CBlockIndex failed");
1620 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1621 pindexNew->phashBlock = &((*mi).first);
1622 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1623 if (miPrev != mapBlockIndex.end())
1625 pindexNew->pprev = (*miPrev).second;
1626 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1628 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1632 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1633 if (!txdb.TxnCommit())
1637 if (pindexNew->bnChainWork > bnBestChainWork)
1638 if (!SetBestChain(txdb, pindexNew))
1643 if (pindexNew == pindexBest)
1645 // Notify UI to display prev block's coinbase if it was ours
1646 static uint256 hashPrevBestCoinBase;
1647 CRITICAL_BLOCK(cs_mapWallet)
1648 vWalletUpdated.push_back(hashPrevBestCoinBase);
1649 hashPrevBestCoinBase = vtx[0].GetHash();
1659 bool CBlock::CheckBlock() const
1661 // These are checks that are independent of context
1662 // that can be verified before saving an orphan block.
1665 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1666 return error("CheckBlock() : size limits failed");
1668 // Check proof of work matches claimed amount
1669 if (!CheckProofOfWork(GetHash(), nBits))
1670 return error("CheckBlock() : proof of work failed");
1673 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1674 return error("CheckBlock() : block timestamp too far in the future");
1676 // First transaction must be coinbase, the rest must not be
1677 if (vtx.empty() || !vtx[0].IsCoinBase())
1678 return error("CheckBlock() : first tx is not coinbase");
1679 for (int i = 1; i < vtx.size(); i++)
1680 if (vtx[i].IsCoinBase())
1681 return error("CheckBlock() : more than one coinbase");
1683 // Check transactions
1684 BOOST_FOREACH(const CTransaction& tx, vtx)
1685 if (!tx.CheckTransaction())
1686 return error("CheckBlock() : CheckTransaction failed");
1688 // Check that it's not full of nonstandard transactions
1689 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1690 return error("CheckBlock() : too many nonstandard transactions");
1693 if (hashMerkleRoot != BuildMerkleTree())
1694 return error("CheckBlock() : hashMerkleRoot mismatch");
1699 bool CBlock::AcceptBlock()
1701 // Check for duplicate
1702 uint256 hash = GetHash();
1703 if (mapBlockIndex.count(hash))
1704 return error("AcceptBlock() : block already in mapBlockIndex");
1706 // Get prev block index
1707 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1708 if (mi == mapBlockIndex.end())
1709 return error("AcceptBlock() : prev block not found");
1710 CBlockIndex* pindexPrev = (*mi).second;
1711 int nHeight = pindexPrev->nHeight+1;
1713 // Check proof of work
1714 if (nBits != GetNextWorkRequired(pindexPrev))
1715 return error("AcceptBlock() : incorrect proof of work");
1717 // Check timestamp against prev
1718 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1719 return error("AcceptBlock() : block's timestamp is too early");
1721 // Check that all transactions are finalized
1722 BOOST_FOREACH(const CTransaction& tx, vtx)
1723 if (!tx.IsFinal(nHeight, GetBlockTime()))
1724 return error("AcceptBlock() : contains a non-final transaction");
1726 // Check that the block chain matches the known block chain up to a checkpoint
1728 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1729 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1730 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1731 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1732 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1733 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1734 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))
1735 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1737 // Write block to history file
1738 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1739 return error("AcceptBlock() : out of disk space");
1740 unsigned int nFile = -1;
1741 unsigned int nBlockPos = 0;
1742 if (!WriteToDisk(nFile, nBlockPos))
1743 return error("AcceptBlock() : WriteToDisk failed");
1744 if (!AddToBlockIndex(nFile, nBlockPos))
1745 return error("AcceptBlock() : AddToBlockIndex failed");
1747 // Relay inventory, but don't relay old inventory during initial block download
1748 if (hashBestChain == hash)
1749 CRITICAL_BLOCK(cs_vNodes)
1750 BOOST_FOREACH(CNode* pnode, vNodes)
1751 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
1752 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1757 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1759 // Check for duplicate
1760 uint256 hash = pblock->GetHash();
1761 if (mapBlockIndex.count(hash))
1762 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1763 if (mapOrphanBlocks.count(hash))
1764 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1766 // Preliminary checks
1767 if (!pblock->CheckBlock())
1768 return error("ProcessBlock() : CheckBlock FAILED");
1770 // If don't already have its previous block, shunt it off to holding area until we get it
1771 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1773 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1774 CBlock* pblock2 = new CBlock(*pblock);
1775 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1776 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1778 // Ask this guy to fill in what we're missing
1780 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1785 if (!pblock->AcceptBlock())
1786 return error("ProcessBlock() : AcceptBlock FAILED");
1788 // Recursively process any orphan blocks that depended on this one
1789 vector<uint256> vWorkQueue;
1790 vWorkQueue.push_back(hash);
1791 for (int i = 0; i < vWorkQueue.size(); i++)
1793 uint256 hashPrev = vWorkQueue[i];
1794 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1795 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1798 CBlock* pblockOrphan = (*mi).second;
1799 if (pblockOrphan->AcceptBlock())
1800 vWorkQueue.push_back(pblockOrphan->GetHash());
1801 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1802 delete pblockOrphan;
1804 mapOrphanBlocksByPrev.erase(hashPrev);
1807 printf("ProcessBlock: ACCEPTED\n");
1818 template<typename Stream>
1819 bool ScanMessageStart(Stream& s)
1821 // Scan ahead to the next pchMessageStart, which should normally be immediately
1822 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1824 short prevmask = s.exceptions(0);
1825 const char* p = BEGIN(pchMessageStart);
1835 s.exceptions(prevmask);
1839 p = BEGIN(pchMessageStart);
1842 if (++p == END(pchMessageStart))
1845 s.exceptions(prevmask);
1854 s.exceptions(prevmask);
1859 bool CheckDiskSpace(uint64 nAdditionalBytes)
1861 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1863 // Check for 15MB because database could create another 10MB log file at any time
1864 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1867 string strMessage = _("Warning: Disk space is low ");
1868 strMiscWarning = strMessage;
1869 printf("*** %s\n", strMessage.c_str());
1870 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1871 CreateThread(Shutdown, NULL);
1877 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1881 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1884 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1886 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1895 static unsigned int nCurrentBlockFile = 1;
1897 FILE* AppendBlockFile(unsigned int& nFileRet)
1902 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1905 if (fseek(file, 0, SEEK_END) != 0)
1907 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1908 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1910 nFileRet = nCurrentBlockFile;
1914 nCurrentBlockFile++;
1918 bool LoadBlockIndex(bool fAllowNew)
1922 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1923 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1924 pchMessageStart[0] = 0xfa;
1925 pchMessageStart[1] = 0xbf;
1926 pchMessageStart[2] = 0xb5;
1927 pchMessageStart[3] = 0xda;
1934 if (!txdb.LoadBlockIndex())
1939 // Init with genesis block
1941 if (mapBlockIndex.empty())
1947 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1948 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1949 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1950 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1951 // vMerkleTree: 4a5e1e
1954 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1956 txNew.vin.resize(1);
1957 txNew.vout.resize(1);
1958 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1959 txNew.vout[0].nValue = 50 * COIN;
1960 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1962 block.vtx.push_back(txNew);
1963 block.hashPrevBlock = 0;
1964 block.hashMerkleRoot = block.BuildMerkleTree();
1966 block.nTime = 1231006505;
1967 block.nBits = 0x1d00ffff;
1968 block.nNonce = 2083236893;
1972 block.nTime = 1296688602;
1973 block.nBits = 0x1d07fff8;
1974 block.nNonce = 384568319;
1978 printf("%s\n", block.GetHash().ToString().c_str());
1979 printf("%s\n", hashGenesisBlock.ToString().c_str());
1980 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1981 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1983 assert(block.GetHash() == hashGenesisBlock);
1985 // Start new block file
1987 unsigned int nBlockPos;
1988 if (!block.WriteToDisk(nFile, nBlockPos))
1989 return error("LoadBlockIndex() : writing genesis block to disk failed");
1990 if (!block.AddToBlockIndex(nFile, nBlockPos))
1991 return error("LoadBlockIndex() : genesis block not accepted");
1999 void PrintBlockTree()
2001 // precompute tree structure
2002 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2003 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2005 CBlockIndex* pindex = (*mi).second;
2006 mapNext[pindex->pprev].push_back(pindex);
2008 //while (rand() % 3 == 0)
2009 // mapNext[pindex->pprev].push_back(pindex);
2012 vector<pair<int, CBlockIndex*> > vStack;
2013 vStack.push_back(make_pair(0, pindexGenesisBlock));
2016 while (!vStack.empty())
2018 int nCol = vStack.back().first;
2019 CBlockIndex* pindex = vStack.back().second;
2022 // print split or gap
2023 if (nCol > nPrevCol)
2025 for (int i = 0; i < nCol-1; i++)
2029 else if (nCol < nPrevCol)
2031 for (int i = 0; i < nCol; i++)
2038 for (int i = 0; i < nCol; i++)
2043 block.ReadFromDisk(pindex);
2044 printf("%d (%u,%u) %s %s tx %d",
2048 block.GetHash().ToString().substr(0,20).c_str(),
2049 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2052 CRITICAL_BLOCK(cs_mapWallet)
2054 if (mapWallet.count(block.vtx[0].GetHash()))
2056 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2057 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2063 // put the main timechain first
2064 vector<CBlockIndex*>& vNext = mapNext[pindex];
2065 for (int i = 0; i < vNext.size(); i++)
2067 if (vNext[i]->pnext)
2069 swap(vNext[0], vNext[i]);
2075 for (int i = 0; i < vNext.size(); i++)
2076 vStack.push_back(make_pair(nCol+i, vNext[i]));
2089 //////////////////////////////////////////////////////////////////////////////
2094 map<uint256, CAlert> mapAlerts;
2095 CCriticalSection cs_mapAlerts;
2097 string GetWarnings(string strFor)
2100 string strStatusBar;
2102 if (GetBoolArg("-testsafemode"))
2105 // Misc warnings like out of disk space and clock is wrong
2106 if (strMiscWarning != "")
2109 strStatusBar = strMiscWarning;
2112 // Longer invalid proof-of-work chain
2113 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2116 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2120 CRITICAL_BLOCK(cs_mapAlerts)
2122 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2124 const CAlert& alert = item.second;
2125 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2127 nPriority = alert.nPriority;
2128 strStatusBar = alert.strStatusBar;
2133 if (strFor == "statusbar")
2134 return strStatusBar;
2135 else if (strFor == "rpc")
2137 assert(("GetWarnings() : invalid parameter", false));
2141 bool CAlert::ProcessAlert()
2143 if (!CheckSignature())
2148 CRITICAL_BLOCK(cs_mapAlerts)
2150 // Cancel previous alerts
2151 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2153 const CAlert& alert = (*mi).second;
2156 printf("cancelling alert %d\n", alert.nID);
2157 mapAlerts.erase(mi++);
2159 else if (!alert.IsInEffect())
2161 printf("expiring alert %d\n", alert.nID);
2162 mapAlerts.erase(mi++);
2168 // Check if this alert has been cancelled
2169 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2171 const CAlert& alert = item.second;
2172 if (alert.Cancels(*this))
2174 printf("alert already cancelled by %d\n", alert.nID);
2180 mapAlerts.insert(make_pair(GetHash(), *this));
2183 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2195 //////////////////////////////////////////////////////////////////////////////
2201 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2205 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2206 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2208 // Don't know what it is, just say we already got one
2215 // The message start string is designed to be unlikely to occur in normal data.
2216 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2217 // a large 4-byte int at any alignment.
2218 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2221 bool ProcessMessages(CNode* pfrom)
2223 CDataStream& vRecv = pfrom->vRecv;
2227 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2231 // (4) message start
2240 // Scan for message start
2241 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2242 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2243 if (vRecv.end() - pstart < nHeaderSize)
2245 if (vRecv.size() > nHeaderSize)
2247 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2248 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2252 if (pstart - vRecv.begin() > 0)
2253 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2254 vRecv.erase(vRecv.begin(), pstart);
2257 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2262 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2265 string strCommand = hdr.GetCommand();
2268 unsigned int nMessageSize = hdr.nMessageSize;
2269 if (nMessageSize > MAX_SIZE)
2271 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2274 if (nMessageSize > vRecv.size())
2276 // Rewind and wait for rest of message
2277 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2282 if (vRecv.GetVersion() >= 209)
2284 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2285 unsigned int nChecksum = 0;
2286 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2287 if (nChecksum != hdr.nChecksum)
2289 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2290 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2295 // Copy message to its own buffer
2296 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2297 vRecv.ignore(nMessageSize);
2303 CRITICAL_BLOCK(cs_main)
2304 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2308 catch (std::ios_base::failure& e)
2310 if (strstr(e.what(), "end of data"))
2312 // Allow exceptions from underlength message on vRecv
2313 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());
2315 else if (strstr(e.what(), "size too large"))
2317 // Allow exceptions from overlong size
2318 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2322 PrintExceptionContinue(&e, "ProcessMessage()");
2325 catch (std::exception& e) {
2326 PrintExceptionContinue(&e, "ProcessMessage()");
2328 PrintExceptionContinue(NULL, "ProcessMessage()");
2332 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2342 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2344 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2345 RandAddSeedPerfmon();
2347 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2348 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2349 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2351 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2359 if (strCommand == "version")
2361 // Each connection can only send one version message
2362 if (pfrom->nVersion != 0)
2369 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2370 if (pfrom->nVersion == 10300)
2371 pfrom->nVersion = 300;
2372 if (pfrom->nVersion >= 106 && !vRecv.empty())
2373 vRecv >> addrFrom >> nNonce;
2374 if (pfrom->nVersion >= 106 && !vRecv.empty())
2375 vRecv >> pfrom->strSubVer;
2376 if (pfrom->nVersion >= 209 && !vRecv.empty())
2377 vRecv >> pfrom->nStartingHeight;
2379 if (pfrom->nVersion == 0)
2382 // Disconnect if we connected to ourself
2383 if (nNonce == nLocalHostNonce && nNonce > 1)
2385 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2386 pfrom->fDisconnect = true;
2390 // Be shy and don't send version until we hear
2391 if (pfrom->fInbound)
2392 pfrom->PushVersion();
2394 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2396 AddTimeData(pfrom->addr.ip, nTime);
2399 if (pfrom->nVersion >= 209)
2400 pfrom->PushMessage("verack");
2401 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2402 if (pfrom->nVersion < 209)
2403 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2405 if (!pfrom->fInbound)
2407 // Advertise our address
2408 if (addrLocalHost.IsRoutable() && !fUseProxy)
2410 CAddress addr(addrLocalHost);
2411 addr.nTime = GetAdjustedTime();
2412 pfrom->PushAddress(addr);
2415 // Get recent addresses
2416 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2418 pfrom->PushMessage("getaddr");
2419 pfrom->fGetAddr = true;
2423 // Ask the first connected node for block updates
2424 static int nAskedForBlocks;
2425 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2428 pfrom->PushGetBlocks(pindexBest, uint256(0));
2432 CRITICAL_BLOCK(cs_mapAlerts)
2433 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2434 item.second.RelayTo(pfrom);
2436 pfrom->fSuccessfullyConnected = true;
2438 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2442 else if (pfrom->nVersion == 0)
2444 // Must have a version message before anything else
2449 else if (strCommand == "verack")
2451 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2455 else if (strCommand == "addr")
2457 vector<CAddress> vAddr;
2460 // Don't want addr from older versions unless seeding
2461 if (pfrom->nVersion < 209)
2463 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2465 if (vAddr.size() > 1000)
2466 return error("message addr size() = %d", vAddr.size());
2468 // Store the new addresses
2469 int64 nNow = GetAdjustedTime();
2470 int64 nSince = nNow - 10 * 60;
2471 BOOST_FOREACH(CAddress& addr, vAddr)
2475 // ignore IPv6 for now, since it isn't implemented anyway
2478 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2479 addr.nTime = nNow - 5 * 24 * 60 * 60;
2480 AddAddress(addr, 2 * 60 * 60);
2481 pfrom->AddAddressKnown(addr);
2482 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2484 // Relay to a limited number of other nodes
2485 CRITICAL_BLOCK(cs_vNodes)
2487 // Use deterministic randomness to send to the same nodes for 24 hours
2488 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2489 static uint256 hashSalt;
2491 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2492 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2493 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2494 multimap<uint256, CNode*> mapMix;
2495 BOOST_FOREACH(CNode* pnode, vNodes)
2497 if (pnode->nVersion < 31402)
2499 unsigned int nPointer;
2500 memcpy(&nPointer, &pnode, sizeof(nPointer));
2501 uint256 hashKey = hashRand ^ nPointer;
2502 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2503 mapMix.insert(make_pair(hashKey, pnode));
2505 int nRelayNodes = 2;
2506 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2507 ((*mi).second)->PushAddress(addr);
2511 if (vAddr.size() < 1000)
2512 pfrom->fGetAddr = false;
2516 else if (strCommand == "inv")
2520 if (vInv.size() > 50000)
2521 return error("message inv size() = %d", vInv.size());
2524 BOOST_FOREACH(const CInv& inv, vInv)
2528 pfrom->AddInventoryKnown(inv);
2530 bool fAlreadyHave = AlreadyHave(txdb, inv);
2531 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2535 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2536 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2538 // Track requests for our stuff
2539 CRITICAL_BLOCK(cs_mapRequestCount)
2541 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2542 if (mi != mapRequestCount.end())
2549 else if (strCommand == "getdata")
2553 if (vInv.size() > 50000)
2554 return error("message getdata size() = %d", vInv.size());
2556 BOOST_FOREACH(const CInv& inv, vInv)
2560 printf("received getdata for: %s\n", inv.ToString().c_str());
2562 if (inv.type == MSG_BLOCK)
2564 // Send block from disk
2565 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2566 if (mi != mapBlockIndex.end())
2569 block.ReadFromDisk((*mi).second);
2570 pfrom->PushMessage("block", block);
2572 // Trigger them to send a getblocks request for the next batch of inventory
2573 if (inv.hash == pfrom->hashContinue)
2575 // Bypass PushInventory, this must send even if redundant,
2576 // and we want it right after the last block so they don't
2577 // wait for other stuff first.
2579 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2580 pfrom->PushMessage("inv", vInv);
2581 pfrom->hashContinue = 0;
2585 else if (inv.IsKnownType())
2587 // Send stream from relay memory
2588 CRITICAL_BLOCK(cs_mapRelay)
2590 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2591 if (mi != mapRelay.end())
2592 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2596 // Track requests for our stuff
2597 CRITICAL_BLOCK(cs_mapRequestCount)
2599 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2600 if (mi != mapRequestCount.end())
2607 else if (strCommand == "getblocks")
2609 CBlockLocator locator;
2611 vRecv >> locator >> hashStop;
2613 // Find the last block the caller has in the main chain
2614 CBlockIndex* pindex = locator.GetBlockIndex();
2616 // Send the rest of the chain
2618 pindex = pindex->pnext;
2619 int nLimit = 500 + locator.GetDistanceBack();
2620 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2621 for (; pindex; pindex = pindex->pnext)
2623 if (pindex->GetBlockHash() == hashStop)
2625 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2628 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2631 // When this block is requested, we'll send an inv that'll make them
2632 // getblocks the next batch of inventory.
2633 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2634 pfrom->hashContinue = pindex->GetBlockHash();
2641 else if (strCommand == "getheaders")
2643 CBlockLocator locator;
2645 vRecv >> locator >> hashStop;
2647 CBlockIndex* pindex = NULL;
2648 if (locator.IsNull())
2650 // If locator is null, return the hashStop block
2651 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2652 if (mi == mapBlockIndex.end())
2654 pindex = (*mi).second;
2658 // Find the last block the caller has in the main chain
2659 pindex = locator.GetBlockIndex();
2661 pindex = pindex->pnext;
2664 vector<CBlock> vHeaders;
2665 int nLimit = 2000 + locator.GetDistanceBack();
2666 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2667 for (; pindex; pindex = pindex->pnext)
2669 vHeaders.push_back(pindex->GetBlockHeader());
2670 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2673 pfrom->PushMessage("headers", vHeaders);
2677 else if (strCommand == "tx")
2679 vector<uint256> vWorkQueue;
2680 CDataStream vMsg(vRecv);
2684 CInv inv(MSG_TX, tx.GetHash());
2685 pfrom->AddInventoryKnown(inv);
2687 bool fMissingInputs = false;
2688 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2690 AddToWalletIfInvolvingMe(tx, NULL, true);
2691 RelayMessage(inv, vMsg);
2692 mapAlreadyAskedFor.erase(inv);
2693 vWorkQueue.push_back(inv.hash);
2695 // Recursively process any orphan transactions that depended on this one
2696 for (int i = 0; i < vWorkQueue.size(); i++)
2698 uint256 hashPrev = vWorkQueue[i];
2699 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2700 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2703 const CDataStream& vMsg = *((*mi).second);
2705 CDataStream(vMsg) >> tx;
2706 CInv inv(MSG_TX, tx.GetHash());
2708 if (tx.AcceptToMemoryPool(true))
2710 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2711 AddToWalletIfInvolvingMe(tx, NULL, true);
2712 RelayMessage(inv, vMsg);
2713 mapAlreadyAskedFor.erase(inv);
2714 vWorkQueue.push_back(inv.hash);
2719 BOOST_FOREACH(uint256 hash, vWorkQueue)
2720 EraseOrphanTx(hash);
2722 else if (fMissingInputs)
2724 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2730 else if (strCommand == "block")
2735 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2738 CInv inv(MSG_BLOCK, block.GetHash());
2739 pfrom->AddInventoryKnown(inv);
2741 if (ProcessBlock(pfrom, &block))
2742 mapAlreadyAskedFor.erase(inv);
2746 else if (strCommand == "getaddr")
2748 // Nodes rebroadcast an addr every 24 hours
2749 pfrom->vAddrToSend.clear();
2750 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2751 CRITICAL_BLOCK(cs_mapAddresses)
2753 unsigned int nCount = 0;
2754 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2756 const CAddress& addr = item.second;
2757 if (addr.nTime > nSince)
2760 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2762 const CAddress& addr = item.second;
2763 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2764 pfrom->PushAddress(addr);
2770 else if (strCommand == "checkorder")
2775 if (!GetBoolArg("-allowreceivebyip"))
2777 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2784 /// we have a chance to check the order here
2786 // Keep giving the same key to the same ip until they use it
2787 if (!mapReuseKey.count(pfrom->addr.ip))
2788 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2790 // Send back approval of order and pubkey to use
2791 CScript scriptPubKey;
2792 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2793 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2797 else if (strCommand == "submitorder")
2802 if (!GetBoolArg("-allowreceivebyip"))
2804 pfrom->PushMessage("reply", hashReply, (int)2);
2810 wtxNew.fFromMe = false;
2813 if (!wtxNew.AcceptWalletTransaction())
2815 pfrom->PushMessage("reply", hashReply, (int)1);
2816 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2818 wtxNew.fTimeReceivedIsTxTime = true;
2819 AddToWallet(wtxNew);
2820 wtxNew.RelayWalletTransaction();
2821 mapReuseKey.erase(pfrom->addr.ip);
2823 // Send back confirmation
2824 pfrom->PushMessage("reply", hashReply, (int)0);
2828 else if (strCommand == "reply")
2833 CRequestTracker tracker;
2834 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2836 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2837 if (mi != pfrom->mapRequests.end())
2839 tracker = (*mi).second;
2840 pfrom->mapRequests.erase(mi);
2843 if (!tracker.IsNull())
2844 tracker.fn(tracker.param1, vRecv);
2848 else if (strCommand == "ping")
2853 else if (strCommand == "alert")
2858 if (alert.ProcessAlert())
2861 pfrom->setKnown.insert(alert.GetHash());
2862 CRITICAL_BLOCK(cs_vNodes)
2863 BOOST_FOREACH(CNode* pnode, vNodes)
2864 alert.RelayTo(pnode);
2871 // Ignore unknown commands for extensibility
2875 // Update the last seen time for this node's address
2876 if (pfrom->fNetworkNode)
2877 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2878 AddressCurrentlyConnected(pfrom->addr);
2892 bool SendMessages(CNode* pto, bool fSendTrickle)
2894 CRITICAL_BLOCK(cs_main)
2896 // Don't send anything until we get their version message
2897 if (pto->nVersion == 0)
2901 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2902 pto->PushMessage("ping");
2904 // Resend wallet transactions that haven't gotten in a block yet
2905 ResendWalletTransactions();
2907 // Address refresh broadcast
2908 static int64 nLastRebroadcast;
2909 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2911 nLastRebroadcast = GetTime();
2912 CRITICAL_BLOCK(cs_vNodes)
2914 BOOST_FOREACH(CNode* pnode, vNodes)
2916 // Periodically clear setAddrKnown to allow refresh broadcasts
2917 pnode->setAddrKnown.clear();
2919 // Rebroadcast our address
2920 if (addrLocalHost.IsRoutable() && !fUseProxy)
2922 CAddress addr(addrLocalHost);
2923 addr.nTime = GetAdjustedTime();
2924 pnode->PushAddress(addr);
2930 // Clear out old addresses periodically so it's not too much work at once
2931 static int64 nLastClear;
2932 if (nLastClear == 0)
2933 nLastClear = GetTime();
2934 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2936 nLastClear = GetTime();
2937 CRITICAL_BLOCK(cs_mapAddresses)
2940 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2941 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2942 mi != mapAddresses.end();)
2944 const CAddress& addr = (*mi).second;
2945 if (addr.nTime < nSince)
2947 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2949 addrdb.EraseAddress(addr);
2950 mapAddresses.erase(mi++);
2964 vector<CAddress> vAddr;
2965 vAddr.reserve(pto->vAddrToSend.size());
2966 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2968 // returns true if wasn't already contained in the set
2969 if (pto->setAddrKnown.insert(addr).second)
2971 vAddr.push_back(addr);
2972 // receiver rejects addr messages larger than 1000
2973 if (vAddr.size() >= 1000)
2975 pto->PushMessage("addr", vAddr);
2980 pto->vAddrToSend.clear();
2982 pto->PushMessage("addr", vAddr);
2987 // Message: inventory
2990 vector<CInv> vInvWait;
2991 CRITICAL_BLOCK(pto->cs_inventory)
2993 vInv.reserve(pto->vInventoryToSend.size());
2994 vInvWait.reserve(pto->vInventoryToSend.size());
2995 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2997 if (pto->setInventoryKnown.count(inv))
3000 // trickle out tx inv to protect privacy
3001 if (inv.type == MSG_TX && !fSendTrickle)
3003 // 1/4 of tx invs blast to all immediately
3004 static uint256 hashSalt;
3006 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
3007 uint256 hashRand = inv.hash ^ hashSalt;
3008 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3009 bool fTrickleWait = ((hashRand & 3) != 0);
3011 // always trickle our own transactions
3014 TRY_CRITICAL_BLOCK(cs_mapWallet)
3016 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
3017 if (mi != mapWallet.end())
3019 CWalletTx& wtx = (*mi).second;
3021 fTrickleWait = true;
3028 vInvWait.push_back(inv);
3033 // returns true if wasn't already contained in the set
3034 if (pto->setInventoryKnown.insert(inv).second)
3036 vInv.push_back(inv);
3037 if (vInv.size() >= 1000)
3039 pto->PushMessage("inv", vInv);
3044 pto->vInventoryToSend = vInvWait;
3047 pto->PushMessage("inv", vInv);
3053 vector<CInv> vGetData;
3054 int64 nNow = GetTime() * 1000000;
3056 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3058 const CInv& inv = (*pto->mapAskFor.begin()).second;
3059 if (!AlreadyHave(txdb, inv))
3061 printf("sending getdata: %s\n", inv.ToString().c_str());
3062 vGetData.push_back(inv);
3063 if (vGetData.size() >= 1000)
3065 pto->PushMessage("getdata", vGetData);
3069 pto->mapAskFor.erase(pto->mapAskFor.begin());
3071 if (!vGetData.empty())
3072 pto->PushMessage("getdata", vGetData);
3091 //////////////////////////////////////////////////////////////////////////////
3096 void GenerateBitcoins(bool fGenerate)
3098 if (fGenerateBitcoins != fGenerate)
3100 fGenerateBitcoins = fGenerate;
3101 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3104 if (fGenerateBitcoins)
3106 int nProcessors = boost::thread::hardware_concurrency();
3107 printf("%d processors\n", nProcessors);
3108 if (nProcessors < 1)
3110 if (fLimitProcessors && nProcessors > nLimitProcessors)
3111 nProcessors = nLimitProcessors;
3112 int nAddThreads = nProcessors - vnThreadsRunning[3];
3113 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3114 for (int i = 0; i < nAddThreads; i++)
3116 if (!CreateThread(ThreadBitcoinMiner, NULL))
3117 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3123 void ThreadBitcoinMiner(void* parg)
3127 vnThreadsRunning[3]++;
3129 vnThreadsRunning[3]--;
3131 catch (std::exception& e) {
3132 vnThreadsRunning[3]--;
3133 PrintException(&e, "ThreadBitcoinMiner()");
3135 vnThreadsRunning[3]--;
3136 PrintException(NULL, "ThreadBitcoinMiner()");
3138 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3140 if (vnThreadsRunning[3] == 0)
3142 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3146 int FormatHashBlocks(void* pbuffer, unsigned int len)
3148 unsigned char* pdata = (unsigned char*)pbuffer;
3149 unsigned int blocks = 1 + ((len + 8) / 64);
3150 unsigned char* pend = pdata + 64 * blocks;
3151 memset(pdata + len, 0, 64 * blocks - len);
3153 unsigned int bits = len * 8;
3154 pend[-1] = (bits >> 0) & 0xff;
3155 pend[-2] = (bits >> 8) & 0xff;
3156 pend[-3] = (bits >> 16) & 0xff;
3157 pend[-4] = (bits >> 24) & 0xff;
3161 using CryptoPP::ByteReverse;
3163 static const unsigned int pSHA256InitState[8] =
3164 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3166 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3168 memcpy(pstate, pinit, 32);
3169 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3173 // ScanHash scans nonces looking for a hash with at least some zero bits.
3174 // It operates on big endian data. Caller does the byte reversing.
3175 // All input buffers are 16-byte aligned. nNonce is usually preserved
3176 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3177 // the block is rebuilt and nNonce starts over at zero.
3179 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3181 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3185 // Hash pdata using pmidstate as the starting state into
3186 // preformatted buffer phash1, then hash phash1 into phash
3188 SHA256Transform(phash1, pdata, pmidstate);
3189 SHA256Transform(phash, phash1, pSHA256InitState);
3191 // Return the nonce if the hash has at least some zero bits,
3192 // caller will check if it has enough to reach the target
3193 if (((unsigned short*)phash)[14] == 0)
3196 // If nothing found after trying for a while, return -1
3197 if ((nNonce & 0xffff) == 0)
3199 nHashesDone = 0xffff+1;
3210 set<uint256> setDependsOn;
3213 COrphan(CTransaction* ptxIn)
3221 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3222 BOOST_FOREACH(uint256 hash, setDependsOn)
3223 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3228 CBlock* CreateNewBlock(CReserveKey& reservekey)
3230 CBlockIndex* pindexPrev = pindexBest;
3233 auto_ptr<CBlock> pblock(new CBlock());
3237 // Create coinbase tx
3239 txNew.vin.resize(1);
3240 txNew.vin[0].prevout.SetNull();
3241 txNew.vout.resize(1);
3242 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3244 // Add our coinbase tx as first transaction
3245 pblock->vtx.push_back(txNew);
3247 // Collect memory pool transactions into the block
3249 CRITICAL_BLOCK(cs_main)
3250 CRITICAL_BLOCK(cs_mapTransactions)
3254 // Priority order to process transactions
3255 list<COrphan> vOrphan; // list memory doesn't move
3256 map<uint256, vector<COrphan*> > mapDependers;
3257 multimap<double, CTransaction*> mapPriority;
3258 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3260 CTransaction& tx = (*mi).second;
3261 if (tx.IsCoinBase() || !tx.IsFinal())
3264 COrphan* porphan = NULL;
3265 double dPriority = 0;
3266 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3268 // Read prev transaction
3269 CTransaction txPrev;
3271 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3273 // Has to wait for dependencies
3276 // Use list for automatic deletion
3277 vOrphan.push_back(COrphan(&tx));
3278 porphan = &vOrphan.back();
3280 mapDependers[txin.prevout.hash].push_back(porphan);
3281 porphan->setDependsOn.insert(txin.prevout.hash);
3284 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3286 // Read block header
3287 int nConf = txindex.GetDepthInMainChain();
3289 dPriority += (double)nValueIn * nConf;
3291 if (fDebug && GetBoolArg("-printpriority"))
3292 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3295 // Priority is sum(valuein * age) / txsize
3296 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3299 porphan->dPriority = dPriority;
3301 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3303 if (fDebug && GetBoolArg("-printpriority"))
3305 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3312 // Collect transactions into block
3313 map<uint256, CTxIndex> mapTestPool;
3314 uint64 nBlockSize = 1000;
3315 int nBlockSigOps = 100;
3316 while (!mapPriority.empty())
3318 // Take highest priority transaction off priority queue
3319 double dPriority = -(*mapPriority.begin()).first;
3320 CTransaction& tx = *(*mapPriority.begin()).second;
3321 mapPriority.erase(mapPriority.begin());
3324 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3325 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3327 int nTxSigOps = tx.GetSigOpCount();
3328 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3331 // Transaction fee required depends on block size
3332 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3333 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3335 // Connecting shouldn't fail due to dependency on other memory pool transactions
3336 // because we're already processing them in order of dependency
3337 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3338 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3340 swap(mapTestPool, mapTestPoolTmp);
3343 pblock->vtx.push_back(tx);
3344 nBlockSize += nTxSize;
3345 nBlockSigOps += nTxSigOps;
3347 // Add transactions that depend on this one to the priority queue
3348 uint256 hash = tx.GetHash();
3349 if (mapDependers.count(hash))
3351 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3353 if (!porphan->setDependsOn.empty())
3355 porphan->setDependsOn.erase(hash);
3356 if (porphan->setDependsOn.empty())
3357 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3363 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3366 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3367 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3368 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3369 pblock->nBits = GetNextWorkRequired(pindexPrev);
3372 return pblock.release();
3376 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3378 // Update nExtraNonce
3379 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3380 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3385 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3386 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3390 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3393 // Prebuild hash buffers
3400 uint256 hashPrevBlock;
3401 uint256 hashMerkleRoot;
3404 unsigned int nNonce;
3407 unsigned char pchPadding0[64];
3409 unsigned char pchPadding1[64];
3412 memset(&tmp, 0, sizeof(tmp));
3414 tmp.block.nVersion = pblock->nVersion;
3415 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3416 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3417 tmp.block.nTime = pblock->nTime;
3418 tmp.block.nBits = pblock->nBits;
3419 tmp.block.nNonce = pblock->nNonce;
3421 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3422 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3424 // Byte swap all the input buffer
3425 for (int i = 0; i < sizeof(tmp)/4; i++)
3426 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3428 // Precalc the first half of the first hash, which stays constant
3429 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3431 memcpy(pdata, &tmp.block, 128);
3432 memcpy(phash1, &tmp.hash1, 64);
3436 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3438 uint256 hash = pblock->GetHash();
3439 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3441 if (hash > hashTarget)
3445 printf("BitcoinMiner:\n");
3446 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3448 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3449 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3452 CRITICAL_BLOCK(cs_main)
3454 if (pblock->hashPrevBlock != hashBestChain)
3455 return error("BitcoinMiner : generated block is stale");
3457 // Remove key from key pool
3458 reservekey.KeepKey();
3460 // Track how many getdata requests this block gets
3461 CRITICAL_BLOCK(cs_mapRequestCount)
3462 mapRequestCount[pblock->GetHash()] = 0;
3464 // Process this block the same as if we had received it from another node
3465 if (!ProcessBlock(NULL, pblock))
3466 return error("BitcoinMiner : ProcessBlock, block not accepted");
3476 printf("BitcoinMiner started\n");
3477 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3479 // Each thread has its own key and counter
3480 CReserveKey reservekey;
3481 unsigned int nExtraNonce = 0;
3482 int64 nPrevTime = 0;
3484 while (fGenerateBitcoins)
3486 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3490 while (vNodes.empty() || IsInitialBlockDownload())
3495 if (!fGenerateBitcoins)
3503 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3504 CBlockIndex* pindexPrev = pindexBest;
3506 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3509 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3511 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3515 // Prebuild hash buffers
3517 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3518 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3519 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3521 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3523 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3524 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3530 int64 nStart = GetTime();
3531 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3533 uint256& hash = *alignup<16>(hashbuf);
3536 unsigned int nHashesDone = 0;
3537 unsigned int nNonceFound;
3540 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3541 (char*)&hash, nHashesDone);
3543 // Check if something found
3544 if (nNonceFound != -1)
3546 for (int i = 0; i < sizeof(hash)/4; i++)
3547 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3549 if (hash <= hashTarget)
3552 pblock->nNonce = ByteReverse(nNonceFound);
3553 assert(hash == pblock->GetHash());
3555 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3556 CheckWork(pblock.get(), reservekey);
3557 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3563 static int64 nHashCounter;
3564 if (nHPSTimerStart == 0)
3566 nHPSTimerStart = GetTimeMillis();
3570 nHashCounter += nHashesDone;
3571 if (GetTimeMillis() - nHPSTimerStart > 4000)
3573 static CCriticalSection cs;
3576 if (GetTimeMillis() - nHPSTimerStart > 4000)
3578 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3579 nHPSTimerStart = GetTimeMillis();
3581 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3582 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3583 static int64 nLogTime;
3584 if (GetTime() - nLogTime > 30 * 60)
3586 nLogTime = GetTime();
3587 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3588 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3594 // Check for stop or if block needs to be rebuilt
3597 if (!fGenerateBitcoins)
3599 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3603 if (nBlockNonce >= 0xffff0000)
3605 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3607 if (pindexPrev != pindexBest)
3610 // Update nTime every few seconds
3611 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3612 nBlockTime = ByteReverse(pblock->nTime);
3634 //////////////////////////////////////////////////////////////////////////////
3642 int64 nStart = GetTimeMillis();
3645 CRITICAL_BLOCK(cs_mapWallet)
3647 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3649 CWalletTx* pcoin = &(*it).second;
3650 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3652 nTotal += pcoin->GetAvailableCredit();
3656 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3661 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3663 setCoinsRet.clear();
3666 // List of values less than target
3667 pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;
3668 coinLowestLarger.first = INT64_MAX;
3669 coinLowestLarger.second.first = NULL;
3670 vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;
3671 int64 nTotalLower = 0;
3673 CRITICAL_BLOCK(cs_mapWallet)
3675 vector<CWalletTx*> vCoins;
3676 vCoins.reserve(mapWallet.size());
3677 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3678 vCoins.push_back(&(*it).second);
3679 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3681 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
3683 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3686 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3689 int nDepth = pcoin->GetDepthInMainChain();
3690 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3693 for (int i = 0; i < pcoin->vout.size(); i++)
3695 if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())
3698 int64 n = pcoin->vout[i].nValue;
3703 pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
3705 if (n == nTargetValue)
3707 setCoinsRet.insert(coin.second);
3708 nValueRet += coin.first;
3711 else if (n < nTargetValue + CENT)
3713 vValue.push_back(coin);
3716 else if (n < coinLowestLarger.first)
3718 coinLowestLarger = coin;
3724 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
3726 for (int i = 0; i < vValue.size(); ++i)
3728 setCoinsRet.insert(vValue[i].second);
3729 nValueRet += vValue[i].first;
3734 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
3736 if (coinLowestLarger.second.first == NULL)
3738 setCoinsRet.insert(coinLowestLarger.second);
3739 nValueRet += coinLowestLarger.first;
3743 if (nTotalLower >= nTargetValue + CENT)
3744 nTargetValue += CENT;
3746 // Solve subset sum by stochastic approximation
3747 sort(vValue.rbegin(), vValue.rend());
3748 vector<char> vfIncluded;
3749 vector<char> vfBest(vValue.size(), true);
3750 int64 nBest = nTotalLower;
3752 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3754 vfIncluded.assign(vValue.size(), false);
3756 bool fReachedTarget = false;
3757 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3759 for (int i = 0; i < vValue.size(); i++)
3761 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3763 nTotal += vValue[i].first;
3764 vfIncluded[i] = true;
3765 if (nTotal >= nTargetValue)
3767 fReachedTarget = true;
3771 vfBest = vfIncluded;
3773 nTotal -= vValue[i].first;
3774 vfIncluded[i] = false;
3781 // If the next larger is still closer, return it
3782 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
3784 setCoinsRet.insert(coinLowestLarger.second);
3785 nValueRet += coinLowestLarger.first;
3788 for (int i = 0; i < vValue.size(); i++)
3791 setCoinsRet.insert(vValue[i].second);
3792 nValueRet += vValue[i].first;
3796 printf("SelectCoins() best subset: ");
3797 for (int i = 0; i < vValue.size(); i++)
3799 printf("%s ", FormatMoney(vValue[i].first).c_str());
3800 printf("total %s\n", FormatMoney(nBest).c_str());
3806 bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3808 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
3809 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
3810 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
3816 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3819 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3825 if (vecSend.empty() || nValue < 0)
3828 CRITICAL_BLOCK(cs_main)
3830 // txdb must be opened before the mapWallet lock
3832 CRITICAL_BLOCK(cs_mapWallet)
3834 nFeeRet = nTransactionFee;
3838 wtxNew.vout.clear();
3839 wtxNew.fFromMe = true;
3841 int64 nTotalValue = nValue + nFeeRet;
3842 double dPriority = 0;
3843 // vouts to the payees
3844 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3845 wtxNew.vout.push_back(CTxOut(s.second, s.first));
3847 // Choose coins to use
3848 set<pair<CWalletTx*,unsigned int> > setCoins;
3850 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
3852 BOOST_FOREACH(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)
3854 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
3855 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
3858 // Fill a vout back to self with any change
3859 int64 nChange = nValueIn - nTotalValue;
3860 if (nChange >= CENT)
3862 // Note: We use a new key here to keep it from being obvious which side is the change.
3863 // The drawback is that by not reusing a previous key, the change may be lost if a
3864 // backup is restored, if the backup doesn't have the new private key for the change.
3865 // If we reused the old key, it would be possible to add code to look for and
3866 // rediscover unknown transactions that were written with keys of ours to recover
3867 // post-backup change.
3869 // Reserve a new key pair from key pool
3870 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3871 assert(mapKeys.count(vchPubKey));
3873 // Fill a vout to ourself, using same address type as the payment
3874 CScript scriptChange;
3875 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
3876 scriptChange.SetBitcoinAddress(vchPubKey);
3878 scriptChange << vchPubKey << OP_CHECKSIG;
3880 // Insert change txn at random position:
3881 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
3882 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
3885 reservekey.ReturnKey();
3888 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3889 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
3893 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3894 if (!SignSignature(*coin.first, wtxNew, nIn++))
3898 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3899 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3901 dPriority /= nBytes;
3903 // Check that enough fee is included
3904 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3905 bool fAllowFree = CTransaction::AllowFree(dPriority);
3906 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
3907 if (nFeeRet < max(nPayFee, nMinFee))
3909 nFeeRet = max(nPayFee, nMinFee);
3913 // Fill vtxPrev by copying from previous transactions vtxPrev
3914 wtxNew.AddSupportingTransactions(txdb);
3915 wtxNew.fTimeReceivedIsTxTime = true;
3924 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3926 vector< pair<CScript, int64> > vecSend;
3927 vecSend.push_back(make_pair(scriptPubKey, nValue));
3928 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
3931 // Call after CreateTransaction unless you want to abort
3932 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3934 CRITICAL_BLOCK(cs_main)
3936 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3937 CRITICAL_BLOCK(cs_mapWallet)
3939 // This is only to keep the database open to defeat the auto-flush for the
3940 // duration of this scope. This is the only place where this optimization
3941 // maybe makes sense; please don't do it anywhere else.
3942 CWalletDB walletdb("r");
3944 // Take key pair from key pool so it won't be used again
3945 reservekey.KeepKey();
3947 // Add tx to wallet, because if it has change it's also ours,
3948 // otherwise just for transaction history.
3949 AddToWallet(wtxNew);
3951 // Mark old coins as spent
3952 set<CWalletTx*> setCoins;
3953 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3955 CWalletTx &pcoin = mapWallet[txin.prevout.hash];
3956 pcoin.MarkSpent(txin.prevout.n);
3957 pcoin.WriteToDisk();
3958 vWalletUpdated.push_back(pcoin.GetHash());
3962 // Track how many getdata requests our transaction gets
3963 CRITICAL_BLOCK(cs_mapRequestCount)
3964 mapRequestCount[wtxNew.GetHash()] = 0;
3967 if (!wtxNew.AcceptToMemoryPool())
3969 // This must not fail. The transaction has already been signed and recorded.
3970 printf("CommitTransaction() : Error: Transaction not valid");
3973 wtxNew.RelayWalletTransaction();
3982 // requires cs_main lock
3983 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3985 CReserveKey reservekey;
3987 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3990 if (nValue + nFeeRequired > GetBalance())
3991 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());
3993 strError = _("Error: Transaction creation failed ");
3994 printf("SendMoney() : %s", strError.c_str());
3998 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4001 if (!CommitTransaction(wtxNew, reservekey))
4002 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.");
4010 // requires cs_main lock
4011 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4015 return _("Invalid amount");
4016 if (nValue + nTransactionFee > GetBalance())
4017 return _("Insufficient funds");
4019 // Parse bitcoin address
4020 CScript scriptPubKey;
4021 if (!scriptPubKey.SetBitcoinAddress(strAddress))
4022 return _("Invalid bitcoin address");
4024 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);