1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "cryptopp/sha.h"
16 CCriticalSection cs_main;
18 map<uint256, CTransaction> mapTransactions;
19 CCriticalSection cs_mapTransactions;
20 unsigned int nTransactionsUpdated = 0;
21 map<COutPoint, CInPoint> mapNextTx;
23 map<uint256, CBlockIndex*> mapBlockIndex;
24 const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
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;
57 int fGenerateBitcoins = false;
58 int64 nTransactionFee = 0;
59 CAddress addrIncoming;
60 int fLimitProcessors = false;
61 int nLimitProcessors = 1;
62 int fMinimizeToTray = true;
63 int fMinimizeOnClose = true;
70 //////////////////////////////////////////////////////////////////////////////
75 bool AddKey(const CKey& key)
77 CRITICAL_BLOCK(cs_mapKeys)
79 mapKeys[key.GetPubKey()] = key.GetPrivKey();
80 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
82 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
85 vector<unsigned char> GenerateNewKey()
91 throw runtime_error("GenerateNewKey() : AddKey failed\n");
92 return key.GetPubKey();
98 //////////////////////////////////////////////////////////////////////////////
103 bool AddToWallet(const CWalletTx& wtxIn)
105 uint256 hash = wtxIn.GetHash();
106 CRITICAL_BLOCK(cs_mapWallet)
108 // Inserts only if not already there, returns tx inserted or tx found
109 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
110 CWalletTx& wtx = (*ret.first).second;
111 bool fInsertedNew = ret.second;
113 wtx.nTimeReceived = GetAdjustedTime();
115 bool fUpdated = false;
119 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
121 wtx.hashBlock = wtxIn.hashBlock;
124 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
126 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
127 wtx.nIndex = wtxIn.nIndex;
130 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
132 wtx.fFromMe = wtxIn.fFromMe;
135 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
137 wtx.fSpent = wtxIn.fSpent;
143 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
146 if (fInsertedNew || fUpdated)
147 if (!wtx.WriteToDisk())
150 // If default receiving address gets used, replace it with a new one
151 CScript scriptDefaultKey;
152 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
153 foreach(const CTxOut& txout, wtx.vout)
155 if (txout.scriptPubKey == scriptDefaultKey)
158 walletdb.WriteDefaultKey(GenerateNewKey());
159 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
164 vWalletUpdated.push_back(hash);
172 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
174 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
177 // Get merkle branch if transaction was found in a block
179 wtx.SetMerkleBranch(pblock);
180 return AddToWallet(wtx);
185 bool EraseFromWallet(uint256 hash)
187 CRITICAL_BLOCK(cs_mapWallet)
189 if (mapWallet.erase(hash))
190 CWalletDB().EraseTx(hash);
195 void WalletUpdateSpent(const COutPoint& prevout)
197 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
198 // Update the wallet spent flag if it doesn't know due to wallet.dat being
199 // restored from backup or the user making copies of wallet.dat.
200 CRITICAL_BLOCK(cs_mapWallet)
202 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
203 if (mi != mapWallet.end())
205 CWalletTx& wtx = (*mi).second;
206 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
208 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
211 vWalletUpdated.push_back(prevout.hash);
224 //////////////////////////////////////////////////////////////////////////////
226 // mapOrphanTransactions
229 void AddOrphanTx(const CDataStream& vMsg)
232 CDataStream(vMsg) >> tx;
233 uint256 hash = tx.GetHash();
234 if (mapOrphanTransactions.count(hash))
236 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
237 foreach(const CTxIn& txin, tx.vin)
238 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
241 void EraseOrphanTx(uint256 hash)
243 if (!mapOrphanTransactions.count(hash))
245 const CDataStream* pvMsg = mapOrphanTransactions[hash];
247 CDataStream(*pvMsg) >> tx;
248 foreach(const CTxIn& txin, tx.vin)
250 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
251 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
253 if ((*mi).second == pvMsg)
254 mapOrphanTransactionsByPrev.erase(mi++);
260 mapOrphanTransactions.erase(hash);
270 //////////////////////////////////////////////////////////////////////////////
275 bool CTxIn::IsMine() const
277 CRITICAL_BLOCK(cs_mapWallet)
279 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
280 if (mi != mapWallet.end())
282 const CWalletTx& prev = (*mi).second;
283 if (prevout.n < prev.vout.size())
284 if (prev.vout[prevout.n].IsMine())
291 int64 CTxIn::GetDebit() const
293 CRITICAL_BLOCK(cs_mapWallet)
295 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
296 if (mi != mapWallet.end())
298 const CWalletTx& prev = (*mi).second;
299 if (prevout.n < prev.vout.size())
300 if (prev.vout[prevout.n].IsMine())
301 return prev.vout[prevout.n].nValue;
307 int64 CWalletTx::GetTxTime() const
309 if (!fTimeReceivedIsTxTime && hashBlock != 0)
311 // If we did not receive the transaction directly, we rely on the block's
312 // time to figure out when it happened. We use the median over a range
313 // of blocks to try to filter out inaccurate block times.
314 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
315 if (mi != mapBlockIndex.end())
317 CBlockIndex* pindex = (*mi).second;
319 return pindex->GetMedianTime();
322 return nTimeReceived;
325 int CWalletTx::GetRequestCount() const
327 // Returns -1 if it wasn't being tracked
329 CRITICAL_BLOCK(cs_mapRequestCount)
336 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
337 if (mi != mapRequestCount.end())
338 nRequests = (*mi).second;
343 // Did anyone request this transaction?
344 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
345 if (mi != mapRequestCount.end())
347 nRequests = (*mi).second;
349 // How about the block it's in?
350 if (nRequests == 0 && hashBlock != 0)
352 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
353 if (mi != mapRequestCount.end())
354 nRequests = (*mi).second;
356 nRequests = 1; // If it's in someone else's block it must have got out
367 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
379 // Load the block this tx is in
381 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
383 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
388 // Update the tx's hashBlock
389 hashBlock = pblock->GetHash();
391 // Locate the transaction
392 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
393 if (pblock->vtx[nIndex] == *(CTransaction*)this)
395 if (nIndex == pblock->vtx.size())
397 vMerkleBranch.clear();
399 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
403 // Fill in merkle branch
404 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
407 // Is the tx in a block that's in the main chain
408 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
409 if (mi == mapBlockIndex.end())
411 CBlockIndex* pindex = (*mi).second;
412 if (!pindex || !pindex->IsInMainChain())
415 return pindexBest->nHeight - pindex->nHeight + 1;
420 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
424 const int COPY_DEPTH = 3;
425 if (SetMerkleBranch() < COPY_DEPTH)
427 vector<uint256> vWorkQueue;
428 foreach(const CTxIn& txin, vin)
429 vWorkQueue.push_back(txin.prevout.hash);
431 // This critsect is OK because txdb is already open
432 CRITICAL_BLOCK(cs_mapWallet)
434 map<uint256, const CMerkleTx*> mapWalletPrev;
435 set<uint256> setAlreadyDone;
436 for (int i = 0; i < vWorkQueue.size(); i++)
438 uint256 hash = vWorkQueue[i];
439 if (setAlreadyDone.count(hash))
441 setAlreadyDone.insert(hash);
444 if (mapWallet.count(hash))
446 tx = mapWallet[hash];
447 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
448 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
450 else if (mapWalletPrev.count(hash))
452 tx = *mapWalletPrev[hash];
454 else if (!fClient && txdb.ReadDiskTx(hash, tx))
460 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
464 int nDepth = tx.SetMerkleBranch();
465 vtxPrev.push_back(tx);
467 if (nDepth < COPY_DEPTH)
468 foreach(const CTxIn& txin, tx.vin)
469 vWorkQueue.push_back(txin.prevout.hash);
474 reverse(vtxPrev.begin(), vtxPrev.end());
487 bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
490 *pfMissingInputs = false;
492 // Coinbase is only valid in a block, not as a loose transaction
494 return error("AcceptTransaction() : coinbase as individual tx");
496 if (!CheckTransaction())
497 return error("AcceptTransaction() : CheckTransaction failed");
499 // To help v0.1.5 clients who would see it as a negative number
500 if (nLockTime > INT_MAX)
501 return error("AcceptTransaction() : not accepting nLockTime beyond 2038");
503 // Do we already have it?
504 uint256 hash = GetHash();
505 CRITICAL_BLOCK(cs_mapTransactions)
506 if (mapTransactions.count(hash))
509 if (txdb.ContainsTx(hash))
512 // Check for conflicts with in-memory transactions
513 CTransaction* ptxOld = NULL;
514 for (int i = 0; i < vin.size(); i++)
516 COutPoint outpoint = vin[i].prevout;
517 if (mapNextTx.count(outpoint))
519 // Allow replacing with a newer version of the same transaction
522 ptxOld = mapNextTx[outpoint].ptx;
523 if (!IsNewerThan(*ptxOld))
525 for (int i = 0; i < vin.size(); i++)
527 COutPoint outpoint = vin[i].prevout;
528 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
535 // Check against previous transactions
536 map<uint256, CTxIndex> mapUnused;
538 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))
541 *pfMissingInputs = true;
542 return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());
545 // Store transaction in memory
546 CRITICAL_BLOCK(cs_mapTransactions)
550 printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());
551 mapTransactions.erase(ptxOld->GetHash());
556 ///// are we sure this is ok when loading transactions or restoring block txes
557 // If updated, erase old tx from wallet
559 EraseFromWallet(ptxOld->GetHash());
561 printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());
566 bool CTransaction::AddToMemoryPool()
568 // Add to memory pool without checking anything. Don't call this directly,
569 // call AcceptTransaction to properly check the transaction first.
570 CRITICAL_BLOCK(cs_mapTransactions)
572 uint256 hash = GetHash();
573 mapTransactions[hash] = *this;
574 for (int i = 0; i < vin.size(); i++)
575 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
576 nTransactionsUpdated++;
582 bool CTransaction::RemoveFromMemoryPool()
584 // Remove transaction from memory pool
585 CRITICAL_BLOCK(cs_mapTransactions)
587 foreach(const CTxIn& txin, vin)
588 mapNextTx.erase(txin.prevout);
589 mapTransactions.erase(GetHash());
590 nTransactionsUpdated++;
600 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
602 if (hashBlock == 0 || nIndex == -1)
605 // Find the block it claims to be in
606 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
607 if (mi == mapBlockIndex.end())
609 CBlockIndex* pindex = (*mi).second;
610 if (!pindex || !pindex->IsInMainChain())
613 // Make sure the merkle branch connects to this block
614 if (!fMerkleVerified)
616 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
618 fMerkleVerified = true;
621 nHeightRet = pindex->nHeight;
622 return pindexBest->nHeight - pindex->nHeight + 1;
626 int CMerkleTx::GetBlocksToMaturity() const
630 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
634 bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
638 if (!IsInMainChain() && !ClientConnectInputs())
640 return CTransaction::AcceptTransaction(txdb, false);
644 return CTransaction::AcceptTransaction(txdb, fCheckInputs);
650 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
652 CRITICAL_BLOCK(cs_mapTransactions)
654 foreach(CMerkleTx& tx, vtxPrev)
656 if (!tx.IsCoinBase())
658 uint256 hash = tx.GetHash();
659 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
660 tx.AcceptTransaction(txdb, fCheckInputs);
664 return AcceptTransaction(txdb, fCheckInputs);
669 void ReacceptWalletTransactions()
672 CRITICAL_BLOCK(cs_mapWallet)
674 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
676 CWalletTx& wtx = item.second;
677 if (wtx.fSpent && wtx.IsCoinBase())
681 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
683 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
686 if (txindex.vSpent.size() != wtx.vout.size())
688 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
691 for (int i = 0; i < txindex.vSpent.size(); i++)
693 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
695 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
705 // Reaccept any txes of ours that aren't already in a block
706 if (!wtx.IsCoinBase())
707 wtx.AcceptWalletTransaction(txdb, false);
714 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
716 foreach(const CMerkleTx& tx, vtxPrev)
718 if (!tx.IsCoinBase())
720 uint256 hash = tx.GetHash();
721 if (!txdb.ContainsTx(hash))
722 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
727 uint256 hash = GetHash();
728 if (!txdb.ContainsTx(hash))
730 printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());
731 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
736 void ResendWalletTransactions()
738 // Do this infrequently and randomly to avoid giving away
739 // that these are our transactions.
740 static int64 nNextTime;
741 if (GetTime() < nNextTime)
743 bool fFirst = (nNextTime == 0);
744 nNextTime = GetTime() + GetRand(120 * 60);
748 // Rebroadcast any of our txes that aren't in a block yet
749 printf("ResendWalletTransactions()\n");
751 CRITICAL_BLOCK(cs_mapWallet)
753 // Sort them in chronological order
754 multimap<unsigned int, CWalletTx*> mapSorted;
755 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
757 CWalletTx& wtx = item.second;
758 // Don't rebroadcast until it's had plenty of time that
759 // it should have gotten in already by now.
760 if (nTimeBestReceived - wtx.nTimeReceived > 60 * 60)
761 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
763 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
765 CWalletTx& wtx = *item.second;
766 wtx.RelayWalletTransaction(txdb);
780 //////////////////////////////////////////////////////////////////////////////
782 // CBlock and CBlockIndex
785 bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)
787 return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);
790 uint256 GetOrphanRoot(const CBlock* pblock)
792 // Work back to the first block in the orphan chain
793 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
794 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
795 return pblock->GetHash();
798 int64 CBlock::GetBlockValue(int nHeight, int64 nFees) const
800 int64 nSubsidy = 50 * COIN;
802 // Subsidy is cut in half every 4 years
803 nSubsidy >>= (nHeight / 210000);
805 return nSubsidy + nFees;
808 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
810 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
811 const int64 nTargetSpacing = 10 * 60;
812 const int64 nInterval = nTargetTimespan / nTargetSpacing;
815 if (pindexLast == NULL)
816 return bnProofOfWorkLimit.GetCompact();
818 // Only change once per interval
819 if ((pindexLast->nHeight+1) % nInterval != 0)
820 return pindexLast->nBits;
822 // Go back by what we want to be 14 days worth of blocks
823 const CBlockIndex* pindexFirst = pindexLast;
824 for (int i = 0; pindexFirst && i < nInterval-1; i++)
825 pindexFirst = pindexFirst->pprev;
828 // Limit adjustment step
829 int64 nActualTimespan = (int64)pindexLast->nTime - (int64)pindexFirst->nTime;
830 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
831 if (nActualTimespan < nTargetTimespan/4)
832 nActualTimespan = nTargetTimespan/4;
833 if (nActualTimespan > nTargetTimespan*4)
834 nActualTimespan = nTargetTimespan*4;
838 bnNew.SetCompact(pindexLast->nBits);
839 bnNew *= nActualTimespan;
840 bnNew /= nTargetTimespan;
842 if (bnNew > bnProofOfWorkLimit)
843 bnNew = bnProofOfWorkLimit;
846 printf("GetNextWorkRequired RETARGET\n");
847 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
848 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
849 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
851 return bnNew.GetCompact();
854 bool IsInitialBlockDownload()
856 if (pindexBest == NULL)
858 static int64 nLastUpdate;
859 static CBlockIndex* pindexLastBest;
860 if (pindexBest != pindexLastBest)
862 pindexLastBest = pindexBest;
863 nLastUpdate = GetTime();
865 return (GetTime() - nLastUpdate < 10 &&
866 pindexBest->nTime < GetTime() - 24 * 60 * 60);
873 return (bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6);
876 void Lockdown(CBlockIndex* pindexNew)
878 if (pindexNew->bnChainWork > bnBestInvalidWork)
880 bnBestInvalidWork = pindexNew->bnChainWork;
881 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
884 printf("Lockdown: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,22).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
885 printf("Lockdown: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
886 printf("Lockdown: IsLockdown()=%d\n", (IsLockdown() ? 1 : 0));
888 printf("Lockdown: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
898 bool CTransaction::DisconnectInputs(CTxDB& txdb)
900 // Relinquish previous transactions' spent pointers
903 foreach(const CTxIn& txin, vin)
905 COutPoint prevout = txin.prevout;
907 // Get prev txindex from disk
909 if (!txdb.ReadTxIndex(prevout.hash, txindex))
910 return error("DisconnectInputs() : ReadTxIndex failed");
912 if (prevout.n >= txindex.vSpent.size())
913 return error("DisconnectInputs() : prevout.n out of range");
915 // Mark outpoint as not spent
916 txindex.vSpent[prevout.n].SetNull();
919 txdb.UpdateTxIndex(prevout.hash, txindex);
923 // Remove transaction from index
924 if (!txdb.EraseTxIndex(*this))
925 return error("DisconnectInputs() : EraseTxPos failed");
931 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
933 // Take over previous transactions' spent pointers
937 for (int i = 0; i < vin.size(); i++)
939 COutPoint prevout = vin[i].prevout;
944 if (fMiner && mapTestPool.count(prevout.hash))
946 // Get txindex from current proposed changes
947 txindex = mapTestPool[prevout.hash];
951 // Read txindex from txdb
952 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
954 if (!fFound && (fBlock || fMiner))
955 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
959 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
961 // Get prev tx from single transactions in memory
962 CRITICAL_BLOCK(cs_mapTransactions)
964 if (!mapTransactions.count(prevout.hash))
965 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
966 txPrev = mapTransactions[prevout.hash];
969 txindex.vSpent.resize(txPrev.vout.size());
973 // Get prev tx from disk
974 if (!txPrev.ReadFromDisk(txindex.pos))
975 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
978 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
979 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,6).c_str(), txPrev.ToString().c_str());
981 // If prev is coinbase, check that it's matured
982 if (txPrev.IsCoinBase())
983 for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)
984 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
985 return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);
988 if (!VerifySignature(txPrev, *this, i))
989 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
991 // Check for conflicts
992 if (!txindex.vSpent[prevout.n].IsNull())
993 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,6).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
995 // Mark outpoints as spent
996 txindex.vSpent[prevout.n] = posThisTx;
1000 txdb.UpdateTxIndex(prevout.hash, txindex);
1002 mapTestPool[prevout.hash] = txindex;
1004 nValueIn += txPrev.vout[prevout.n].nValue;
1007 // Tally transaction fees
1008 int64 nTxFee = nValueIn - GetValueOut();
1010 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
1011 if (nTxFee < nMinFee)
1018 // Add transaction to disk index
1019 if (!txdb.AddTxIndex(*this, posThisTx, nHeight))
1020 return error("ConnectInputs() : AddTxPos failed");
1024 // Add transaction to test pool
1025 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1032 bool CTransaction::ClientConnectInputs()
1037 // Take over previous transactions' spent pointers
1038 CRITICAL_BLOCK(cs_mapTransactions)
1041 for (int i = 0; i < vin.size(); i++)
1043 // Get prev tx from single transactions in memory
1044 COutPoint prevout = vin[i].prevout;
1045 if (!mapTransactions.count(prevout.hash))
1047 CTransaction& txPrev = mapTransactions[prevout.hash];
1049 if (prevout.n >= txPrev.vout.size())
1053 if (!VerifySignature(txPrev, *this, i))
1054 return error("ConnectInputs() : VerifySignature failed");
1056 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1057 ///// this has to go away now that posNext is gone
1058 // // Check for conflicts
1059 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1060 // return error("ConnectInputs() : prev tx already used");
1062 // // Flag outpoints as used
1063 // txPrev.vout[prevout.n].posNext = posThisTx;
1065 nValueIn += txPrev.vout[prevout.n].nValue;
1067 if (GetValueOut() > nValueIn)
1077 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1079 // Disconnect in reverse order
1080 for (int i = vtx.size()-1; i >= 0; i--)
1081 if (!vtx[i].DisconnectInputs(txdb))
1084 // Update block index on disk without changing it in memory.
1085 // The memory index structure will be changed after the db commits.
1088 CDiskBlockIndex blockindexPrev(pindex->pprev);
1089 blockindexPrev.hashNext = 0;
1090 txdb.WriteBlockIndex(blockindexPrev);
1096 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1098 //// issue here: it doesn't know the version
1099 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1101 map<uint256, CTxIndex> mapUnused;
1103 foreach(CTransaction& tx, vtx)
1105 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1106 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1108 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))
1112 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1115 // Update block index on disk without changing it in memory.
1116 // The memory index structure will be changed after the db commits.
1119 CDiskBlockIndex blockindexPrev(pindex->pprev);
1120 blockindexPrev.hashNext = pindex->GetBlockHash();
1121 txdb.WriteBlockIndex(blockindexPrev);
1124 // Watch for transactions paying to me
1125 foreach(CTransaction& tx, vtx)
1126 AddToWalletIfMine(tx, this);
1133 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1135 printf("REORGANIZE\n");
1138 CBlockIndex* pfork = pindexBest;
1139 CBlockIndex* plonger = pindexNew;
1140 while (pfork != plonger)
1142 while (plonger->nHeight > pfork->nHeight)
1143 if (!(plonger = plonger->pprev))
1144 return error("Reorganize() : plonger->pprev is null");
1145 if (pfork == plonger)
1147 if (!(pfork = pfork->pprev))
1148 return error("Reorganize() : pfork->pprev is null");
1151 // List of what to disconnect
1152 vector<CBlockIndex*> vDisconnect;
1153 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1154 vDisconnect.push_back(pindex);
1156 // List of what to connect
1157 vector<CBlockIndex*> vConnect;
1158 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1159 vConnect.push_back(pindex);
1160 reverse(vConnect.begin(), vConnect.end());
1162 // Disconnect shorter branch
1163 vector<CTransaction> vResurrect;
1164 foreach(CBlockIndex* pindex, vDisconnect)
1167 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1168 return error("Reorganize() : ReadFromDisk for disconnect failed");
1169 if (!block.DisconnectBlock(txdb, pindex))
1170 return error("Reorganize() : DisconnectBlock failed");
1172 // Queue memory transactions to resurrect
1173 foreach(const CTransaction& tx, block.vtx)
1174 if (!tx.IsCoinBase())
1175 vResurrect.push_back(tx);
1178 // Connect longer branch
1179 vector<CTransaction> vDelete;
1180 for (int i = 0; i < vConnect.size(); i++)
1182 CBlockIndex* pindex = vConnect[i];
1184 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1185 return error("Reorganize() : ReadFromDisk for connect failed");
1186 if (!block.ConnectBlock(txdb, pindex))
1190 return error("Reorganize() : ConnectBlock failed");
1193 // Queue memory transactions to delete
1194 foreach(const CTransaction& tx, block.vtx)
1195 vDelete.push_back(tx);
1197 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1198 return error("Reorganize() : WriteHashBestChain failed");
1200 // Commit now because resurrecting could take some time
1203 // Disconnect shorter branch
1204 foreach(CBlockIndex* pindex, vDisconnect)
1206 pindex->pprev->pnext = NULL;
1208 // Connect longer branch
1209 foreach(CBlockIndex* pindex, vConnect)
1211 pindex->pprev->pnext = pindex;
1213 // Resurrect memory transactions that were in the disconnected branch
1214 foreach(CTransaction& tx, vResurrect)
1215 tx.AcceptTransaction(txdb, false);
1217 // Delete redundant memory transactions that are in the connected branch
1218 foreach(CTransaction& tx, vDelete)
1219 tx.RemoveFromMemoryPool();
1225 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1227 // Check for duplicate
1228 uint256 hash = GetHash();
1229 if (mapBlockIndex.count(hash))
1230 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());
1232 // Construct new block index object
1233 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1235 return error("AddToBlockIndex() : new CBlockIndex failed");
1236 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1237 pindexNew->phashBlock = &((*mi).first);
1238 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1239 if (miPrev != mapBlockIndex.end())
1241 pindexNew->pprev = (*miPrev).second;
1242 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1244 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1247 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1250 if (pindexNew->bnChainWork > bnBestChainWork)
1253 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1255 pindexGenesisBlock = pindexNew;
1256 txdb.WriteHashBestChain(hash);
1258 else if (hashPrevBlock == hashBestChain)
1260 // Adding to current best branch
1261 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1264 Lockdown(pindexNew);
1265 return error("AddToBlockIndex() : ConnectBlock failed");
1268 pindexNew->pprev->pnext = pindexNew;
1270 // Delete redundant memory transactions
1271 foreach(CTransaction& tx, vtx)
1272 tx.RemoveFromMemoryPool();
1277 if (!Reorganize(txdb, pindexNew))
1280 Lockdown(pindexNew);
1281 return error("AddToBlockIndex() : Reorganize failed");
1287 hashBestChain = hash;
1288 pindexBest = pindexNew;
1289 nBestHeight = pindexBest->nHeight;
1290 bnBestChainWork = pindexNew->bnChainWork;
1291 nTimeBestReceived = GetTime();
1292 nTransactionsUpdated++;
1293 printf("AddToBlockIndex: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1298 if (pindexNew == pindexBest)
1300 // Notify UI to display prev block's coinbase if it was ours
1301 static uint256 hashPrevBestCoinBase;
1302 CRITICAL_BLOCK(cs_mapWallet)
1303 vWalletUpdated.push_back(hashPrevBestCoinBase);
1304 hashPrevBestCoinBase = vtx[0].GetHash();
1314 bool CBlock::CheckBlock() const
1316 // These are checks that are independent of context
1317 // that can be verified before saving an orphan block.
1320 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
1321 return error("CheckBlock() : size limits failed");
1324 if (nTime > GetAdjustedTime() + 2 * 60 * 60)
1325 return error("CheckBlock() : block timestamp too far in the future");
1327 // First transaction must be coinbase, the rest must not be
1328 if (vtx.empty() || !vtx[0].IsCoinBase())
1329 return error("CheckBlock() : first tx is not coinbase");
1330 for (int i = 1; i < vtx.size(); i++)
1331 if (vtx[i].IsCoinBase())
1332 return error("CheckBlock() : more than one coinbase");
1334 // Check transactions
1335 foreach(const CTransaction& tx, vtx)
1336 if (!tx.CheckTransaction())
1337 return error("CheckBlock() : CheckTransaction failed");
1339 // Check proof of work matches claimed amount
1340 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
1341 return error("CheckBlock() : nBits below minimum work");
1342 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
1343 return error("CheckBlock() : hash doesn't match nBits");
1346 if (hashMerkleRoot != BuildMerkleTree())
1347 return error("CheckBlock() : hashMerkleRoot mismatch");
1352 bool CBlock::AcceptBlock()
1354 // Check for duplicate
1355 uint256 hash = GetHash();
1356 if (mapBlockIndex.count(hash))
1357 return error("AcceptBlock() : block already in mapBlockIndex");
1359 // Get prev block index
1360 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1361 if (mi == mapBlockIndex.end())
1362 return error("AcceptBlock() : prev block not found");
1363 CBlockIndex* pindexPrev = (*mi).second;
1365 // Check timestamp against prev
1366 if (nTime <= pindexPrev->GetMedianTimePast())
1367 return error("AcceptBlock() : block's timestamp is too early");
1369 // Check that all transactions are finalized
1370 foreach(const CTransaction& tx, vtx)
1371 if (!tx.IsFinal(pindexPrev->nHeight+1, nTime))
1372 return error("AcceptBlock() : contains a non-final transaction");
1374 // Check proof of work
1375 if (nBits != GetNextWorkRequired(pindexPrev))
1376 return error("AcceptBlock() : incorrect proof of work");
1378 // Check that the block chain matches the known block chain up to a checkpoint
1379 if (pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
1380 return error("AcceptBlock() : rejected by checkpoint lockin at 11111");
1381 if (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
1382 return error("AcceptBlock() : rejected by checkpoint lockin at 33333");
1383 if (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a"))
1384 return error("AcceptBlock() : rejected by checkpoint lockin at 68555");
1385 if (pindexPrev->nHeight+1 == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a"))
1386 return error("AcceptBlock() : rejected by checkpoint lockin at 70567");
1388 // Write block to history file
1389 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1390 return error("AcceptBlock() : out of disk space");
1392 unsigned int nBlockPos;
1393 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1394 return error("AcceptBlock() : WriteToDisk failed");
1395 if (!AddToBlockIndex(nFile, nBlockPos))
1396 return error("AcceptBlock() : AddToBlockIndex failed");
1398 // Relay inventory, but don't relay old inventory during initial block download
1399 if (hashBestChain == hash)
1400 CRITICAL_BLOCK(cs_vNodes)
1401 foreach(CNode* pnode, vNodes)
1402 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1403 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1408 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1410 // Check for duplicate
1411 uint256 hash = pblock->GetHash();
1412 if (mapBlockIndex.count(hash))
1413 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());
1414 if (mapOrphanBlocks.count(hash))
1415 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());
1417 // Preliminary checks
1418 if (!pblock->CheckBlock())
1421 return error("ProcessBlock() : CheckBlock FAILED");
1424 // If don't already have its previous block, shunt it off to holding area until we get it
1425 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1427 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());
1428 mapOrphanBlocks.insert(make_pair(hash, pblock));
1429 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1431 // Ask this guy to fill in what we're missing
1433 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1438 if (!pblock->AcceptBlock())
1441 return error("ProcessBlock() : AcceptBlock FAILED");
1445 // Recursively process any orphan blocks that depended on this one
1446 vector<uint256> vWorkQueue;
1447 vWorkQueue.push_back(hash);
1448 for (int i = 0; i < vWorkQueue.size(); i++)
1450 uint256 hashPrev = vWorkQueue[i];
1451 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1452 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1455 CBlock* pblockOrphan = (*mi).second;
1456 if (pblockOrphan->AcceptBlock())
1457 vWorkQueue.push_back(pblockOrphan->GetHash());
1458 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1459 delete pblockOrphan;
1461 mapOrphanBlocksByPrev.erase(hashPrev);
1464 printf("ProcessBlock: ACCEPTED\n");
1475 template<typename Stream>
1476 bool ScanMessageStart(Stream& s)
1478 // Scan ahead to the next pchMessageStart, which should normally be immediately
1479 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1481 short prevmask = s.exceptions(0);
1482 const char* p = BEGIN(pchMessageStart);
1492 s.exceptions(prevmask);
1496 p = BEGIN(pchMessageStart);
1499 if (++p == END(pchMessageStart))
1502 s.exceptions(prevmask);
1511 s.exceptions(prevmask);
1516 bool CheckDiskSpace(int64 nAdditionalBytes)
1518 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1520 // Check for 15MB because database could create another 10MB log file at any time
1521 if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)
1524 printf("*** %s***\n", _("Warning: Disk space is low "));
1526 ThreadSafeMessageBox(_("Warning: Disk space is low "), "Bitcoin", wxOK | wxICON_EXCLAMATION);
1528 CreateThread(Shutdown, NULL);
1534 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1538 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1541 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1543 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1552 static unsigned int nCurrentBlockFile = 1;
1554 FILE* AppendBlockFile(unsigned int& nFileRet)
1559 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1562 if (fseek(file, 0, SEEK_END) != 0)
1564 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1565 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1567 nFileRet = nCurrentBlockFile;
1571 nCurrentBlockFile++;
1575 bool LoadBlockIndex(bool fAllowNew)
1581 if (!txdb.LoadBlockIndex())
1586 // Init with genesis block
1588 if (mapBlockIndex.empty())
1595 // GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
1596 // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
1597 // txNew.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
1598 // txNew.vout[0].nValue = 5000000000
1599 // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG
1600 // block.nVersion = 1
1601 // block.nTime = 1231006505
1602 // block.nBits = 0x1d00ffff
1603 // block.nNonce = 2083236893
1604 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1605 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1606 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1607 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1608 // vMerkleTree: 4a5e1e
1611 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1613 txNew.vin.resize(1);
1614 txNew.vout.resize(1);
1615 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1616 txNew.vout[0].nValue = 50 * COIN;
1618 bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");
1619 txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;
1621 block.vtx.push_back(txNew);
1622 block.hashPrevBlock = 0;
1623 block.hashMerkleRoot = block.BuildMerkleTree();
1625 block.nTime = 1231006505;
1626 block.nBits = 0x1d00ffff;
1627 block.nNonce = 2083236893;
1630 printf("%s\n", block.GetHash().ToString().c_str());
1631 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1632 printf("%s\n", hashGenesisBlock.ToString().c_str());
1633 txNew.vout[0].scriptPubKey.print();
1635 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1637 assert(block.GetHash() == hashGenesisBlock);
1639 // Start new block file
1641 unsigned int nBlockPos;
1642 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1643 return error("LoadBlockIndex() : writing genesis block to disk failed");
1644 if (!block.AddToBlockIndex(nFile, nBlockPos))
1645 return error("LoadBlockIndex() : genesis block not accepted");
1653 void PrintBlockTree()
1655 // precompute tree structure
1656 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1657 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1659 CBlockIndex* pindex = (*mi).second;
1660 mapNext[pindex->pprev].push_back(pindex);
1662 //while (rand() % 3 == 0)
1663 // mapNext[pindex->pprev].push_back(pindex);
1666 vector<pair<int, CBlockIndex*> > vStack;
1667 vStack.push_back(make_pair(0, pindexGenesisBlock));
1670 while (!vStack.empty())
1672 int nCol = vStack.back().first;
1673 CBlockIndex* pindex = vStack.back().second;
1676 // print split or gap
1677 if (nCol > nPrevCol)
1679 for (int i = 0; i < nCol-1; i++)
1683 else if (nCol < nPrevCol)
1685 for (int i = 0; i < nCol; i++)
1692 for (int i = 0; i < nCol; i++)
1697 block.ReadFromDisk(pindex);
1698 printf("%d (%u,%u) %s %s tx %d",
1702 block.GetHash().ToString().substr(0,16).c_str(),
1703 DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),
1706 CRITICAL_BLOCK(cs_mapWallet)
1708 if (mapWallet.count(block.vtx[0].GetHash()))
1710 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1711 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1717 // put the main timechain first
1718 vector<CBlockIndex*>& vNext = mapNext[pindex];
1719 for (int i = 0; i < vNext.size(); i++)
1721 if (vNext[i]->pnext)
1723 swap(vNext[0], vNext[i]);
1729 for (int i = 0; i < vNext.size(); i++)
1730 vStack.push_back(make_pair(nCol+i, vNext[i]));
1743 //////////////////////////////////////////////////////////////////////////////
1749 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1753 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1754 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1756 // Don't know what it is, just say we already got one
1766 bool ProcessMessages(CNode* pfrom)
1768 CDataStream& vRecv = pfrom->vRecv;
1772 // printf("ProcessMessages(%d bytes)\n", vRecv.size());
1776 // (4) message start
1785 // Scan for message start
1786 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
1787 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
1788 if (vRecv.end() - pstart < nHeaderSize)
1790 if (vRecv.size() > nHeaderSize)
1792 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
1793 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
1797 if (pstart - vRecv.begin() > 0)
1798 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
1799 vRecv.erase(vRecv.begin(), pstart);
1802 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
1807 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
1810 string strCommand = hdr.GetCommand();
1813 unsigned int nMessageSize = hdr.nMessageSize;
1814 if (nMessageSize > vRecv.size())
1816 // Rewind and wait for rest of message
1817 ///// need a mechanism to give up waiting for overlong message size error
1818 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
1822 // Copy message to its own buffer
1823 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
1824 vRecv.ignore(nMessageSize);
1827 if (vRecv.GetVersion() >= 209)
1829 uint256 hash = Hash(vMsg.begin(), vMsg.end());
1830 unsigned int nChecksum = 0;
1831 memcpy(&nChecksum, &hash, sizeof(nChecksum));
1832 if (nChecksum != hdr.nChecksum)
1834 printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
1835 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
1844 CRITICAL_BLOCK(cs_main)
1845 fRet = ProcessMessage(pfrom, strCommand, vMsg);
1849 catch (std::ios_base::failure& e)
1851 if (strstr(e.what(), "CDataStream::read() : end of data"))
1853 // Allow exceptions from underlength message on vRecv
1854 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
1856 else if (strstr(e.what(), ": size too large"))
1858 // Allow exceptions from overlong size
1859 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
1863 PrintException(&e, "ProcessMessage()");
1866 catch (std::exception& e) {
1867 PrintException(&e, "ProcessMessage()");
1869 PrintException(NULL, "ProcessMessage()");
1873 printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);
1883 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1885 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1886 RandAddSeedPerfmon();
1888 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1889 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1890 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1892 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1900 if (strCommand == "version")
1902 // Each connection can only send one version message
1903 if (pfrom->nVersion != 0)
1911 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1912 if (pfrom->nVersion == 10300)
1913 pfrom->nVersion = 300;
1914 if (pfrom->nVersion >= 106 && !vRecv.empty())
1915 vRecv >> addrFrom >> nNonce;
1916 if (pfrom->nVersion >= 106 && !vRecv.empty())
1918 if (pfrom->nVersion >= 209 && !vRecv.empty())
1919 vRecv >> pfrom->nStartingHeight;
1921 if (pfrom->nVersion == 0)
1924 // Disconnect if we connected to ourself
1925 if (nNonce == nLocalHostNonce && nNonce > 1)
1927 pfrom->fDisconnect = true;
1931 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1934 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
1935 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
1938 AddTimeData(pfrom->addr.ip, nTime);
1941 if (pfrom->nVersion >= 209)
1942 pfrom->PushMessage("verack");
1943 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1944 if (pfrom->nVersion < 209)
1945 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1947 // Ask the first connected node for block updates
1948 static int nAskedForBlocks;
1949 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1952 pfrom->PushGetBlocks(pindexBest, uint256(0));
1955 pfrom->fSuccessfullyConnected = true;
1957 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1961 else if (pfrom->nVersion == 0)
1963 // Must have a version message before anything else
1968 else if (strCommand == "verack")
1970 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1974 else if (strCommand == "addr")
1976 vector<CAddress> vAddr;
1978 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
1980 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
1982 if (vAddr.size() > 1000)
1983 return error("message addr size() = %d", vAddr.size());
1985 // Store the new addresses
1986 foreach(CAddress& addr, vAddr)
1990 // ignore IPv6 for now, since it isn't implemented anyway
1993 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
1994 if (pfrom->fGetAddr || vAddr.size() > 10)
1995 addr.nTime -= 5 * 24 * 60 * 60;
1997 pfrom->AddAddressKnown(addr);
1998 if (!pfrom->fGetAddr && addr.IsRoutable())
2000 // Relay to a limited number of other nodes
2001 CRITICAL_BLOCK(cs_vNodes)
2003 // Use deterministic randomness to send to
2004 // the same places for 12 hours at a time
2005 static uint256 hashSalt;
2007 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2008 uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
2009 multimap<uint256, CNode*> mapMix;
2010 foreach(CNode* pnode, vNodes)
2011 mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
2012 int nRelayNodes = 4;
2013 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2014 ((*mi).second)->PushAddress(addr);
2018 if (vAddr.size() < 1000)
2019 pfrom->fGetAddr = false;
2023 else if (strCommand == "inv")
2027 if (vInv.size() > 50000)
2028 return error("message inv size() = %d", vInv.size());
2031 foreach(const CInv& inv, vInv)
2035 pfrom->AddInventoryKnown(inv);
2037 bool fAlreadyHave = AlreadyHave(txdb, inv);
2038 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2042 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2043 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2045 // Track requests for our stuff
2046 CRITICAL_BLOCK(cs_mapRequestCount)
2048 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2049 if (mi != mapRequestCount.end())
2056 else if (strCommand == "getdata")
2060 if (vInv.size() > 50000)
2061 return error("message getdata size() = %d", vInv.size());
2063 foreach(const CInv& inv, vInv)
2067 printf("received getdata for: %s\n", inv.ToString().c_str());
2069 if (inv.type == MSG_BLOCK)
2071 // Send block from disk
2072 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2073 if (mi != mapBlockIndex.end())
2075 //// could optimize this to send header straight from blockindex for client
2077 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2078 pfrom->PushMessage("block", block);
2080 // Trigger them to send a getblocks request for the next batch of inventory
2081 if (inv.hash == pfrom->hashContinue)
2083 // Bypass PushInventory, this must send even if redundant,
2084 // and we want it right after the last block so they don't
2085 // wait for other stuff first.
2087 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2088 pfrom->PushMessage("inv", vInv);
2089 pfrom->hashContinue = 0;
2093 else if (inv.IsKnownType())
2095 // Send stream from relay memory
2096 CRITICAL_BLOCK(cs_mapRelay)
2098 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2099 if (mi != mapRelay.end())
2100 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2104 // Track requests for our stuff
2105 CRITICAL_BLOCK(cs_mapRequestCount)
2107 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2108 if (mi != mapRequestCount.end())
2115 else if (strCommand == "getblocks")
2117 CBlockLocator locator;
2119 vRecv >> locator >> hashStop;
2121 // Find the first block the caller has in the main chain
2122 CBlockIndex* pindex = locator.GetBlockIndex();
2124 // Send the rest of the chain
2126 pindex = pindex->pnext;
2127 int nLimit = 500 + locator.GetDistanceBack();
2128 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);
2129 for (; pindex; pindex = pindex->pnext)
2131 if (pindex->GetBlockHash() == hashStop)
2133 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2136 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2139 // When this block is requested, we'll send an inv that'll make them
2140 // getblocks the next batch of inventory.
2141 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2142 pfrom->hashContinue = pindex->GetBlockHash();
2149 else if (strCommand == "tx")
2151 vector<uint256> vWorkQueue;
2152 CDataStream vMsg(vRecv);
2156 CInv inv(MSG_TX, tx.GetHash());
2157 pfrom->AddInventoryKnown(inv);
2159 bool fMissingInputs = false;
2160 if (tx.AcceptTransaction(true, &fMissingInputs))
2162 AddToWalletIfMine(tx, NULL);
2163 RelayMessage(inv, vMsg);
2164 mapAlreadyAskedFor.erase(inv);
2165 vWorkQueue.push_back(inv.hash);
2167 // Recursively process any orphan transactions that depended on this one
2168 for (int i = 0; i < vWorkQueue.size(); i++)
2170 uint256 hashPrev = vWorkQueue[i];
2171 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2172 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2175 const CDataStream& vMsg = *((*mi).second);
2177 CDataStream(vMsg) >> tx;
2178 CInv inv(MSG_TX, tx.GetHash());
2180 if (tx.AcceptTransaction(true))
2182 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2183 AddToWalletIfMine(tx, NULL);
2184 RelayMessage(inv, vMsg);
2185 mapAlreadyAskedFor.erase(inv);
2186 vWorkQueue.push_back(inv.hash);
2191 foreach(uint256 hash, vWorkQueue)
2192 EraseOrphanTx(hash);
2194 else if (fMissingInputs)
2196 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2202 else if (strCommand == "block")
2204 auto_ptr<CBlock> pblock(new CBlock);
2208 printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());
2211 CInv inv(MSG_BLOCK, pblock->GetHash());
2212 pfrom->AddInventoryKnown(inv);
2214 if (ProcessBlock(pfrom, pblock.release()))
2215 mapAlreadyAskedFor.erase(inv);
2219 else if (strCommand == "getaddr")
2221 // This includes all nodes that are currently online,
2222 // since they rebroadcast an addr every 24 hours
2223 pfrom->vAddrToSend.clear();
2224 int64 nSince = GetAdjustedTime() - 24 * 60 * 60; // in the last 24 hours
2225 CRITICAL_BLOCK(cs_mapAddresses)
2227 unsigned int nSize = mapAddresses.size();
2228 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2232 const CAddress& addr = item.second;
2233 if (addr.nTime > nSince)
2234 pfrom->PushAddress(addr);
2240 else if (strCommand == "checkorder")
2244 vRecv >> hashReply >> order;
2246 /// we have a chance to check the order here
2248 // Keep giving the same key to the same ip until they use it
2249 if (!mapReuseKey.count(pfrom->addr.ip))
2250 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
2252 // Send back approval of order and pubkey to use
2253 CScript scriptPubKey;
2254 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2255 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2259 else if (strCommand == "submitorder")
2263 vRecv >> hashReply >> wtxNew;
2264 wtxNew.fFromMe = false;
2267 if (!wtxNew.AcceptWalletTransaction())
2269 pfrom->PushMessage("reply", hashReply, (int)1);
2270 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2272 wtxNew.fTimeReceivedIsTxTime = true;
2273 AddToWallet(wtxNew);
2274 wtxNew.RelayWalletTransaction();
2275 mapReuseKey.erase(pfrom->addr.ip);
2277 // Send back confirmation
2278 pfrom->PushMessage("reply", hashReply, (int)0);
2282 else if (strCommand == "reply")
2287 CRequestTracker tracker;
2288 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2290 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2291 if (mi != pfrom->mapRequests.end())
2293 tracker = (*mi).second;
2294 pfrom->mapRequests.erase(mi);
2297 if (!tracker.IsNull())
2298 tracker.fn(tracker.param1, vRecv);
2302 else if (strCommand == "ping")
2309 // Ignore unknown commands for extensibility
2313 // Update the last seen time for this node's address
2314 if (pfrom->fNetworkNode)
2315 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2316 AddressCurrentlyConnected(pfrom->addr);
2330 bool SendMessages(CNode* pto, bool fSendTrickle)
2332 CRITICAL_BLOCK(cs_main)
2334 // Don't send anything until we get their version message
2335 if (pto->nVersion == 0)
2339 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2340 pto->PushMessage("ping");
2342 // Address refresh broadcast
2343 static int64 nLastRebroadcast;
2344 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2346 nLastRebroadcast = GetTime();
2347 CRITICAL_BLOCK(cs_vNodes)
2349 foreach(CNode* pnode, vNodes)
2351 // Periodically clear setAddrKnown to allow refresh broadcasts
2352 pnode->setAddrKnown.clear();
2354 // Rebroadcast our address
2355 if (addrLocalHost.IsRoutable() && !fUseProxy)
2356 pnode->PushAddress(addrLocalHost);
2361 // Resend wallet transactions that haven't gotten in a block yet
2362 ResendWalletTransactions();
2370 vector<CAddress> vAddr;
2371 vAddr.reserve(pto->vAddrToSend.size());
2372 foreach(const CAddress& addr, pto->vAddrToSend)
2374 // returns true if wasn't already contained in the set
2375 if (pto->setAddrKnown.insert(addr).second)
2377 vAddr.push_back(addr);
2378 // receiver rejects addr messages larger than 1000
2379 if (vAddr.size() >= 1000)
2381 pto->PushMessage("addr", vAddr);
2386 pto->vAddrToSend.clear();
2388 pto->PushMessage("addr", vAddr);
2393 // Message: inventory
2396 vector<CInv> vInvWait;
2397 CRITICAL_BLOCK(pto->cs_inventory)
2399 vInv.reserve(pto->vInventoryToSend.size());
2400 vInvWait.reserve(pto->vInventoryToSend.size());
2401 foreach(const CInv& inv, pto->vInventoryToSend)
2403 if (pto->setInventoryKnown.count(inv))
2406 // trickle out tx inv to protect privacy
2407 if (inv.type == MSG_TX && !fSendTrickle)
2409 // 1/4 of tx invs blast to all immediately
2410 static uint256 hashSalt;
2412 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2413 uint256 hashRand = inv.hash ^ hashSalt;
2414 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2415 bool fTrickleWait = ((hashRand & 3) != 0);
2417 // always trickle our own transactions
2420 TRY_CRITICAL_BLOCK(cs_mapWallet)
2422 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2423 if (mi != mapWallet.end())
2425 CWalletTx& wtx = (*mi).second;
2427 fTrickleWait = true;
2434 vInvWait.push_back(inv);
2439 // returns true if wasn't already contained in the set
2440 if (pto->setInventoryKnown.insert(inv).second)
2442 vInv.push_back(inv);
2443 if (vInv.size() >= 1000)
2445 pto->PushMessage("inv", vInv);
2450 pto->vInventoryToSend = vInvWait;
2453 pto->PushMessage("inv", vInv);
2459 vector<CInv> vGetData;
2460 int64 nNow = GetTime() * 1000000;
2462 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2464 const CInv& inv = (*pto->mapAskFor.begin()).second;
2465 if (!AlreadyHave(txdb, inv))
2467 printf("sending getdata: %s\n", inv.ToString().c_str());
2468 vGetData.push_back(inv);
2469 if (vGetData.size() >= 1000)
2471 pto->PushMessage("getdata", vGetData);
2475 pto->mapAskFor.erase(pto->mapAskFor.begin());
2477 if (!vGetData.empty())
2478 pto->PushMessage("getdata", vGetData);
2497 //////////////////////////////////////////////////////////////////////////////
2502 void GenerateBitcoins(bool fGenerate)
2504 if (fGenerateBitcoins != fGenerate)
2506 fGenerateBitcoins = fGenerate;
2507 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2510 if (fGenerateBitcoins)
2512 int nProcessors = boost::thread::hardware_concurrency();
2513 printf("%d processors\n", nProcessors);
2514 if (nProcessors < 1)
2516 if (fLimitProcessors && nProcessors > nLimitProcessors)
2517 nProcessors = nLimitProcessors;
2518 int nAddThreads = nProcessors - vnThreadsRunning[3];
2519 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2520 for (int i = 0; i < nAddThreads; i++)
2522 if (!CreateThread(ThreadBitcoinMiner, NULL))
2523 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2529 void ThreadBitcoinMiner(void* parg)
2533 vnThreadsRunning[3]++;
2535 vnThreadsRunning[3]--;
2537 catch (std::exception& e) {
2538 vnThreadsRunning[3]--;
2539 PrintException(&e, "ThreadBitcoinMiner()");
2541 vnThreadsRunning[3]--;
2542 PrintException(NULL, "ThreadBitcoinMiner()");
2544 UIThreadCall(bind(CalledSetStatusBar, "", 0));
2545 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2548 int FormatHashBlocks(void* pbuffer, unsigned int len)
2550 unsigned char* pdata = (unsigned char*)pbuffer;
2551 unsigned int blocks = 1 + ((len + 8) / 64);
2552 unsigned char* pend = pdata + 64 * blocks;
2553 memset(pdata + len, 0, 64 * blocks - len);
2555 unsigned int bits = len * 8;
2556 pend[-1] = (bits >> 0) & 0xff;
2557 pend[-2] = (bits >> 8) & 0xff;
2558 pend[-3] = (bits >> 16) & 0xff;
2559 pend[-4] = (bits >> 24) & 0xff;
2563 using CryptoPP::ByteReverse;
2565 static const unsigned int pSHA256InitState[8] =
2566 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2568 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2570 memcpy(pstate, pinit, 32);
2571 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2580 printf("BitcoinMiner started\n");
2581 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2585 CBigNum bnExtraNonce = 0;
2586 while (fGenerateBitcoins)
2591 while (vNodes.empty() || IsInitialBlockDownload())
2596 if (!fGenerateBitcoins)
2600 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2601 CBlockIndex* pindexPrev = pindexBest;
2602 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2606 // Create coinbase tx
2609 txNew.vin.resize(1);
2610 txNew.vin[0].prevout.SetNull();
2611 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
2612 txNew.vout.resize(1);
2613 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
2619 auto_ptr<CBlock> pblock(new CBlock());
2623 // Add our coinbase tx as first transaction
2624 pblock->vtx.push_back(txNew);
2626 // Collect the latest transactions into the block
2628 CRITICAL_BLOCK(cs_main)
2629 CRITICAL_BLOCK(cs_mapTransactions)
2632 map<uint256, CTxIndex> mapTestPool;
2633 vector<char> vfAlreadyAdded(mapTransactions.size());
2634 bool fFoundSomething = true;
2635 unsigned int nBlockSize = 0;
2636 while (fFoundSomething && nBlockSize < MAX_SIZE/2)
2638 fFoundSomething = false;
2640 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
2642 if (vfAlreadyAdded[n])
2644 CTransaction& tx = (*mi).second;
2645 if (tx.IsCoinBase() || !tx.IsFinal())
2647 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2648 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)
2651 // Transaction fee based on block size
2652 int64 nMinFee = tx.GetMinFee(nBlockSize);
2654 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2655 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))
2657 swap(mapTestPool, mapTestPoolTmp);
2659 pblock->vtx.push_back(tx);
2660 nBlockSize += nTxSize;
2661 vfAlreadyAdded[n] = true;
2662 fFoundSomething = true;
2666 pblock->nBits = nBits;
2667 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(pindexPrev->nHeight+1, nFees);
2668 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2672 // Prebuild hash buffer
2679 uint256 hashPrevBlock;
2680 uint256 hashMerkleRoot;
2683 unsigned int nNonce;
2686 unsigned char pchPadding0[64];
2688 unsigned char pchPadding1[64];
2690 char tmpbuf[sizeof(tmpworkspace)+16];
2691 tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
2693 tmp.block.nVersion = pblock->nVersion;
2694 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
2695 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2696 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
2697 tmp.block.nBits = pblock->nBits = nBits;
2698 tmp.block.nNonce = pblock->nNonce = 0;
2700 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2701 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2703 // Byte swap all the input buffer
2704 for (int i = 0; i < sizeof(tmp)/4; i++)
2705 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2707 // Precalc the first half of the first hash, which stays constant
2708 uint256 midstatebuf[2];
2709 uint256& midstate = *alignup<16>(midstatebuf);
2710 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
2716 int64 nStart = GetTime();
2717 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2719 uint256& hash = *alignup<16>(hashbuf);
2722 SHA256Transform(&tmp.hash1, (char*)&tmp.block + 64, &midstate);
2723 SHA256Transform(&hash, &tmp.hash1, pSHA256InitState);
2725 if (((unsigned short*)&hash)[14] == 0)
2727 // Byte swap the result after preliminary check
2728 for (int i = 0; i < sizeof(hash)/4; i++)
2729 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
2731 if (hash <= hashTarget)
2733 pblock->nNonce = ByteReverse(tmp.block.nNonce);
2734 assert(hash == pblock->GetHash());
2737 printf("BitcoinMiner:\n");
2738 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2740 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2741 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2743 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2744 CRITICAL_BLOCK(cs_main)
2746 if (pindexPrev == pindexBest)
2753 // Track how many getdata requests this block gets
2754 CRITICAL_BLOCK(cs_mapRequestCount)
2755 mapRequestCount[pblock->GetHash()] = 0;
2757 // Process this block the same as if we had received it from another node
2758 if (!ProcessBlock(NULL, pblock.release()))
2759 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
2762 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2769 // Update nTime every few seconds
2770 const unsigned int nMask = 0xffff;
2771 if ((++tmp.block.nNonce & nMask) == 0)
2774 static int64 nTimerStart;
2775 static int nHashCounter;
2776 if (nTimerStart == 0)
2777 nTimerStart = GetTimeMillis();
2780 if (GetTimeMillis() - nTimerStart > 4000)
2782 static CCriticalSection cs;
2785 if (GetTimeMillis() - nTimerStart > 4000)
2787 double dHashesPerSec = 1000.0 * (nMask+1) * nHashCounter / (GetTimeMillis() - nTimerStart);
2788 nTimerStart = GetTimeMillis();
2790 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
2791 UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));
2792 static int64 nLogTime;
2793 if (GetTime() - nLogTime > 30 * 60)
2795 nLogTime = GetTime();
2796 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2797 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
2803 // Check for stop or if block needs to be rebuilt
2806 if (!fGenerateBitcoins)
2808 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
2812 if (tmp.block.nNonce == 0)
2814 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2816 if (pindexPrev != pindexBest)
2819 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2820 tmp.block.nTime = ByteReverse(pblock->nTime);
2843 //////////////////////////////////////////////////////////////////////////////
2851 int64 nStart = GetTimeMillis();
2854 CRITICAL_BLOCK(cs_mapWallet)
2856 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2858 CWalletTx* pcoin = &(*it).second;
2859 if (!pcoin->IsFinal() || pcoin->fSpent)
2861 nTotal += pcoin->GetCredit(true);
2865 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
2870 int GetRandInt(int nMax)
2872 return GetRand(nMax);
2875 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
2877 setCoinsRet.clear();
2879 // List of values less than target
2880 int64 nLowestLarger = INT64_MAX;
2881 CWalletTx* pcoinLowestLarger = NULL;
2882 vector<pair<int64, CWalletTx*> > vValue;
2883 int64 nTotalLower = 0;
2885 CRITICAL_BLOCK(cs_mapWallet)
2887 vector<CWalletTx*> vCoins;
2888 vCoins.reserve(mapWallet.size());
2889 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2890 vCoins.push_back(&(*it).second);
2891 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2893 foreach(CWalletTx* pcoin, vCoins)
2895 if (!pcoin->IsFinal() || pcoin->fSpent)
2897 int64 n = pcoin->GetCredit();
2900 if (n < nTargetValue)
2902 vValue.push_back(make_pair(n, pcoin));
2905 else if (n == nTargetValue)
2907 setCoinsRet.insert(pcoin);
2910 else if (n < nLowestLarger)
2913 pcoinLowestLarger = pcoin;
2918 if (nTotalLower < nTargetValue)
2920 if (pcoinLowestLarger == NULL)
2922 setCoinsRet.insert(pcoinLowestLarger);
2926 // Solve subset sum by stochastic approximation
2927 sort(vValue.rbegin(), vValue.rend());
2928 vector<char> vfIncluded;
2929 vector<char> vfBest(vValue.size(), true);
2930 int64 nBest = nTotalLower;
2932 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
2934 vfIncluded.assign(vValue.size(), false);
2936 bool fReachedTarget = false;
2937 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2939 for (int i = 0; i < vValue.size(); i++)
2941 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
2943 nTotal += vValue[i].first;
2944 vfIncluded[i] = true;
2945 if (nTotal >= nTargetValue)
2947 fReachedTarget = true;
2951 vfBest = vfIncluded;
2953 nTotal -= vValue[i].first;
2954 vfIncluded[i] = false;
2961 // If the next larger is still closer, return it
2962 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
2963 setCoinsRet.insert(pcoinLowestLarger);
2966 for (int i = 0; i < vValue.size(); i++)
2968 setCoinsRet.insert(vValue[i].second);
2971 printf("SelectCoins() best subset: ");
2972 for (int i = 0; i < vValue.size(); i++)
2974 printf("%s ", FormatMoney(vValue[i].first).c_str());
2975 printf("total %s\n", FormatMoney(nBest).c_str());
2984 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
2986 nFeeRequiredRet = 0;
2987 CRITICAL_BLOCK(cs_main)
2989 // txdb must be opened before the mapWallet lock
2991 CRITICAL_BLOCK(cs_mapWallet)
2993 int64 nFee = nTransactionFee;
2997 wtxNew.vout.clear();
2998 wtxNew.fFromMe = true;
3001 int64 nValueOut = nValue;
3002 int64 nTotalValue = nValue + nFee;
3004 // Choose coins to use
3005 set<CWalletTx*> setCoins;
3006 if (!SelectCoins(nTotalValue, setCoins))
3009 foreach(CWalletTx* pcoin, setCoins)
3010 nValueIn += pcoin->GetCredit();
3012 // Fill a vout to the payee
3013 bool fChangeFirst = GetRand(2);
3015 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3017 // Fill a vout back to self with any change
3018 if (nValueIn > nTotalValue)
3020 // Note: We use a new key here to keep it from being obvious which side is the change.
3021 // The drawback is that by not reusing a previous key, the change may be lost if a
3022 // backup is restored, if the backup doesn't have the new private key for the change.
3023 // If we reused the old key, it would be possible to add code to look for and
3024 // rediscover unknown transactions that were written with keys of ours to recover
3025 // post-backup change.
3028 if (keyRet.IsNull())
3029 keyRet.MakeNewKey();
3031 // Fill a vout to ourself, using same address type as the payment
3032 CScript scriptChange;
3033 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3034 scriptChange.SetBitcoinAddress(keyRet.GetPubKey());
3036 scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;
3037 wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));
3040 // Fill a vout to the payee
3042 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3045 foreach(CWalletTx* pcoin, setCoins)
3046 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3047 if (pcoin->vout[nOut].IsMine())
3048 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3052 foreach(CWalletTx* pcoin, setCoins)
3053 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3054 if (pcoin->vout[nOut].IsMine())
3055 if (!SignSignature(*pcoin, wtxNew, nIn++))
3058 // Check that enough fee is included
3059 if (nFee < wtxNew.GetMinFee())
3061 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3065 // Fill vtxPrev by copying from previous transactions vtxPrev
3066 wtxNew.AddSupportingTransactions(txdb);
3067 wtxNew.fTimeReceivedIsTxTime = true;
3076 // Call after CreateTransaction unless you want to abort
3077 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)
3079 CRITICAL_BLOCK(cs_main)
3081 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3082 CRITICAL_BLOCK(cs_mapWallet)
3084 // This is only to keep the database open to defeat the auto-flush for the
3085 // duration of this scope. This is the only place where this optimization
3086 // maybe makes sense; please don't do it anywhere else.
3087 CWalletDB walletdb("r");
3089 // Add the change's private key to wallet
3090 if (!key.IsNull() && !AddKey(key))
3091 throw runtime_error("CommitTransaction() : AddKey failed\n");
3093 // Add tx to wallet, because if it has change it's also ours,
3094 // otherwise just for transaction history.
3095 AddToWallet(wtxNew);
3097 // Mark old coins as spent
3098 set<CWalletTx*> setCoins;
3099 foreach(const CTxIn& txin, wtxNew.vin)
3100 setCoins.insert(&mapWallet[txin.prevout.hash]);
3101 foreach(CWalletTx* pcoin, setCoins)
3103 pcoin->fSpent = true;
3104 pcoin->WriteToDisk();
3105 vWalletUpdated.push_back(pcoin->GetHash());
3109 // Track how many getdata requests our transaction gets
3110 CRITICAL_BLOCK(cs_mapRequestCount)
3111 mapRequestCount[wtxNew.GetHash()] = 0;
3114 if (!wtxNew.AcceptTransaction())
3116 // This must not fail. The transaction has already been signed and recorded.
3117 printf("CommitTransaction() : Error: Transaction not valid");
3120 wtxNew.RelayWalletTransaction();
3129 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3131 CRITICAL_BLOCK(cs_main)
3135 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
3138 if (nValue + nFeeRequired > GetBalance())
3139 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3141 strError = _("Error: Transaction creation failed ");
3142 printf("SendMoney() : %s", strError.c_str());
3146 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3149 if (!CommitTransaction(wtxNew, key))
3150 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.");
3158 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3162 return _("Invalid amount");
3163 if (nValue + nTransactionFee > GetBalance())
3164 return _("Insufficient funds");
3166 // Parse bitcoin address
3167 CScript scriptPubKey;
3168 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3169 return _("Invalid bitcoin address");
3171 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);