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.
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 uint256 hashBestChain = 0;
29 CBlockIndex* pindexBest = NULL;
30 int64 nTimeBestReceived = 0;
32 map<uint256, CBlock*> mapOrphanBlocks;
33 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
35 map<uint256, CDataStream*> mapOrphanTransactions;
36 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
38 map<uint256, CWalletTx> mapWallet;
39 vector<uint256> vWalletUpdated;
40 CCriticalSection cs_mapWallet;
42 map<vector<unsigned char>, CPrivKey> mapKeys;
43 map<uint160, vector<unsigned char> > mapPubKeys;
44 CCriticalSection cs_mapKeys;
47 map<uint256, int> mapRequestCount;
48 CCriticalSection cs_mapRequestCount;
50 map<string, string> mapAddressBook;
51 CCriticalSection cs_mapAddressBook;
53 vector<unsigned char> vchDefaultKey;
56 int fGenerateBitcoins = false;
57 int64 nTransactionFee = 0;
58 CAddress addrIncoming;
59 int fLimitProcessors = false;
60 int nLimitProcessors = 1;
61 int fMinimizeToTray = true;
62 int fMinimizeOnClose = true;
69 //////////////////////////////////////////////////////////////////////////////
74 bool AddKey(const CKey& key)
76 CRITICAL_BLOCK(cs_mapKeys)
78 mapKeys[key.GetPubKey()] = key.GetPrivKey();
79 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
81 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
84 vector<unsigned char> GenerateNewKey()
90 throw runtime_error("GenerateNewKey() : AddKey failed\n");
91 return key.GetPubKey();
97 //////////////////////////////////////////////////////////////////////////////
102 bool AddToWallet(const CWalletTx& wtxIn)
104 uint256 hash = wtxIn.GetHash();
105 CRITICAL_BLOCK(cs_mapWallet)
107 // Inserts only if not already there, returns tx inserted or tx found
108 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
109 CWalletTx& wtx = (*ret.first).second;
110 bool fInsertedNew = ret.second;
112 wtx.nTimeReceived = GetAdjustedTime();
114 bool fUpdated = false;
118 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
120 wtx.hashBlock = wtxIn.hashBlock;
123 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
125 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
126 wtx.nIndex = wtxIn.nIndex;
129 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
131 wtx.fFromMe = wtxIn.fFromMe;
134 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
136 wtx.fSpent = wtxIn.fSpent;
142 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
145 if (fInsertedNew || fUpdated)
146 if (!wtx.WriteToDisk())
149 // If default receiving address gets used, replace it with a new one
150 CScript scriptDefaultKey;
151 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
152 foreach(const CTxOut& txout, wtx.vout)
154 if (txout.scriptPubKey == scriptDefaultKey)
157 walletdb.WriteDefaultKey(GenerateNewKey());
158 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
163 vWalletUpdated.push_back(hash);
171 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
173 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
176 // Get merkle branch if transaction was found in a block
178 wtx.SetMerkleBranch(pblock);
179 return AddToWallet(wtx);
184 bool EraseFromWallet(uint256 hash)
186 CRITICAL_BLOCK(cs_mapWallet)
188 if (mapWallet.erase(hash))
189 CWalletDB().EraseTx(hash);
194 void WalletUpdateSpent(const COutPoint& prevout)
196 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
197 // Update the wallet spent flag if it doesn't know due to wallet.dat being
198 // restored from backup or the user making copies of wallet.dat.
199 CRITICAL_BLOCK(cs_mapWallet)
201 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
202 if (mi != mapWallet.end())
204 CWalletTx& wtx = (*mi).second;
205 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
207 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
210 vWalletUpdated.push_back(prevout.hash);
223 //////////////////////////////////////////////////////////////////////////////
225 // mapOrphanTransactions
228 void AddOrphanTx(const CDataStream& vMsg)
231 CDataStream(vMsg) >> tx;
232 uint256 hash = tx.GetHash();
233 if (mapOrphanTransactions.count(hash))
235 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
236 foreach(const CTxIn& txin, tx.vin)
237 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
240 void EraseOrphanTx(uint256 hash)
242 if (!mapOrphanTransactions.count(hash))
244 const CDataStream* pvMsg = mapOrphanTransactions[hash];
246 CDataStream(*pvMsg) >> tx;
247 foreach(const CTxIn& txin, tx.vin)
249 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
250 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
252 if ((*mi).second == pvMsg)
253 mapOrphanTransactionsByPrev.erase(mi++);
259 mapOrphanTransactions.erase(hash);
269 //////////////////////////////////////////////////////////////////////////////
274 bool CTxIn::IsMine() const
276 CRITICAL_BLOCK(cs_mapWallet)
278 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
279 if (mi != mapWallet.end())
281 const CWalletTx& prev = (*mi).second;
282 if (prevout.n < prev.vout.size())
283 if (prev.vout[prevout.n].IsMine())
290 int64 CTxIn::GetDebit() const
292 CRITICAL_BLOCK(cs_mapWallet)
294 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
295 if (mi != mapWallet.end())
297 const CWalletTx& prev = (*mi).second;
298 if (prevout.n < prev.vout.size())
299 if (prev.vout[prevout.n].IsMine())
300 return prev.vout[prevout.n].nValue;
306 int64 CWalletTx::GetTxTime() const
308 if (!fTimeReceivedIsTxTime && hashBlock != 0)
310 // If we did not receive the transaction directly, we rely on the block's
311 // time to figure out when it happened. We use the median over a range
312 // of blocks to try to filter out inaccurate block times.
313 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
314 if (mi != mapBlockIndex.end())
316 CBlockIndex* pindex = (*mi).second;
318 return pindex->GetMedianTime();
321 return nTimeReceived;
324 int CWalletTx::GetRequestCount() const
326 // Returns -1 if it wasn't being tracked
328 CRITICAL_BLOCK(cs_mapRequestCount)
335 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
336 if (mi != mapRequestCount.end())
337 nRequests = (*mi).second;
342 // Did anyone request this transaction?
343 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
344 if (mi != mapRequestCount.end())
346 nRequests = (*mi).second;
348 // How about the block it's in?
349 if (nRequests == 0 && hashBlock != 0)
351 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
352 if (mi != mapRequestCount.end())
353 nRequests = (*mi).second;
355 nRequests = 1; // If it's in someone else's block it must have got out
366 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
378 // Load the block this tx is in
380 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
382 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
387 // Update the tx's hashBlock
388 hashBlock = pblock->GetHash();
390 // Locate the transaction
391 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
392 if (pblock->vtx[nIndex] == *(CTransaction*)this)
394 if (nIndex == pblock->vtx.size())
396 vMerkleBranch.clear();
398 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
402 // Fill in merkle branch
403 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
406 // Is the tx in a block that's in the main chain
407 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
408 if (mi == mapBlockIndex.end())
410 CBlockIndex* pindex = (*mi).second;
411 if (!pindex || !pindex->IsInMainChain())
414 return pindexBest->nHeight - pindex->nHeight + 1;
419 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
423 const int COPY_DEPTH = 3;
424 if (SetMerkleBranch() < COPY_DEPTH)
426 vector<uint256> vWorkQueue;
427 foreach(const CTxIn& txin, vin)
428 vWorkQueue.push_back(txin.prevout.hash);
430 // This critsect is OK because txdb is already open
431 CRITICAL_BLOCK(cs_mapWallet)
433 map<uint256, const CMerkleTx*> mapWalletPrev;
434 set<uint256> setAlreadyDone;
435 for (int i = 0; i < vWorkQueue.size(); i++)
437 uint256 hash = vWorkQueue[i];
438 if (setAlreadyDone.count(hash))
440 setAlreadyDone.insert(hash);
443 if (mapWallet.count(hash))
445 tx = mapWallet[hash];
446 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
447 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
449 else if (mapWalletPrev.count(hash))
451 tx = *mapWalletPrev[hash];
453 else if (!fClient && txdb.ReadDiskTx(hash, tx))
459 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
463 int nDepth = tx.SetMerkleBranch();
464 vtxPrev.push_back(tx);
466 if (nDepth < COPY_DEPTH)
467 foreach(const CTxIn& txin, tx.vin)
468 vWorkQueue.push_back(txin.prevout.hash);
473 reverse(vtxPrev.begin(), vtxPrev.end());
486 bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
489 *pfMissingInputs = false;
491 // Coinbase is only valid in a block, not as a loose transaction
493 return error("AcceptTransaction() : coinbase as individual tx");
495 if (!CheckTransaction())
496 return error("AcceptTransaction() : CheckTransaction failed");
498 // To help v0.1.5 clients who would see it as a negative number
499 if (nLockTime > INT_MAX)
500 return error("AcceptTransaction() : not accepting nLockTime beyond 2038");
502 // Do we already have it?
503 uint256 hash = GetHash();
504 CRITICAL_BLOCK(cs_mapTransactions)
505 if (mapTransactions.count(hash))
508 if (txdb.ContainsTx(hash))
511 // Check for conflicts with in-memory transactions
512 CTransaction* ptxOld = NULL;
513 for (int i = 0; i < vin.size(); i++)
515 COutPoint outpoint = vin[i].prevout;
516 if (mapNextTx.count(outpoint))
518 // Allow replacing with a newer version of the same transaction
521 ptxOld = mapNextTx[outpoint].ptx;
522 if (!IsNewerThan(*ptxOld))
524 for (int i = 0; i < vin.size(); i++)
526 COutPoint outpoint = vin[i].prevout;
527 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
534 // Check against previous transactions
535 map<uint256, CTxIndex> mapUnused;
537 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))
540 *pfMissingInputs = true;
541 return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());
544 // Store transaction in memory
545 CRITICAL_BLOCK(cs_mapTransactions)
549 printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());
550 mapTransactions.erase(ptxOld->GetHash());
555 ///// are we sure this is ok when loading transactions or restoring block txes
556 // If updated, erase old tx from wallet
558 EraseFromWallet(ptxOld->GetHash());
560 printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());
565 bool CTransaction::AddToMemoryPool()
567 // Add to memory pool without checking anything. Don't call this directly,
568 // call AcceptTransaction to properly check the transaction first.
569 CRITICAL_BLOCK(cs_mapTransactions)
571 uint256 hash = GetHash();
572 mapTransactions[hash] = *this;
573 for (int i = 0; i < vin.size(); i++)
574 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
575 nTransactionsUpdated++;
581 bool CTransaction::RemoveFromMemoryPool()
583 // Remove transaction from memory pool
584 CRITICAL_BLOCK(cs_mapTransactions)
586 foreach(const CTxIn& txin, vin)
587 mapNextTx.erase(txin.prevout);
588 mapTransactions.erase(GetHash());
589 nTransactionsUpdated++;
599 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
601 if (hashBlock == 0 || nIndex == -1)
604 // Find the block it claims to be in
605 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
606 if (mi == mapBlockIndex.end())
608 CBlockIndex* pindex = (*mi).second;
609 if (!pindex || !pindex->IsInMainChain())
612 // Make sure the merkle branch connects to this block
613 if (!fMerkleVerified)
615 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
617 fMerkleVerified = true;
620 nHeightRet = pindex->nHeight;
621 return pindexBest->nHeight - pindex->nHeight + 1;
625 int CMerkleTx::GetBlocksToMaturity() const
629 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
633 bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
637 if (!IsInMainChain() && !ClientConnectInputs())
639 return CTransaction::AcceptTransaction(txdb, false);
643 return CTransaction::AcceptTransaction(txdb, fCheckInputs);
649 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
651 CRITICAL_BLOCK(cs_mapTransactions)
653 foreach(CMerkleTx& tx, vtxPrev)
655 if (!tx.IsCoinBase())
657 uint256 hash = tx.GetHash();
658 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
659 tx.AcceptTransaction(txdb, fCheckInputs);
663 return AcceptTransaction(txdb, fCheckInputs);
668 void ReacceptWalletTransactions()
671 CRITICAL_BLOCK(cs_mapWallet)
673 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
675 CWalletTx& wtx = item.second;
676 if (wtx.fSpent && wtx.IsCoinBase())
680 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
682 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
685 if (txindex.vSpent.size() != wtx.vout.size())
687 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
690 for (int i = 0; i < txindex.vSpent.size(); i++)
692 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
694 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
704 // Reaccept any txes of ours that aren't already in a block
705 if (!wtx.IsCoinBase())
706 wtx.AcceptWalletTransaction(txdb, false);
713 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
715 foreach(const CMerkleTx& tx, vtxPrev)
717 if (!tx.IsCoinBase())
719 uint256 hash = tx.GetHash();
720 if (!txdb.ContainsTx(hash))
721 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
726 uint256 hash = GetHash();
727 if (!txdb.ContainsTx(hash))
729 printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());
730 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
735 void ResendWalletTransactions()
737 // Do this infrequently and randomly to avoid giving away
738 // that these are our transactions.
739 static int64 nNextTime;
740 if (GetTime() < nNextTime)
742 bool fFirst = (nNextTime == 0);
743 nNextTime = GetTime() + GetRand(120 * 60);
747 // Rebroadcast any of our txes that aren't in a block yet
748 printf("ResendWalletTransactions()\n");
750 CRITICAL_BLOCK(cs_mapWallet)
752 // Sort them in chronological order
753 multimap<unsigned int, CWalletTx*> mapSorted;
754 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
756 CWalletTx& wtx = item.second;
757 // Don't rebroadcast until it's had plenty of time that
758 // it should have gotten in already by now.
759 if (nTimeBestReceived - wtx.nTimeReceived > 60 * 60)
760 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
762 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
764 CWalletTx& wtx = *item.second;
765 wtx.RelayWalletTransaction(txdb);
779 //////////////////////////////////////////////////////////////////////////////
781 // CBlock and CBlockIndex
784 bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)
786 return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);
789 uint256 GetOrphanRoot(const CBlock* pblock)
791 // Work back to the first block in the orphan chain
792 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
793 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
794 return pblock->GetHash();
797 int64 CBlock::GetBlockValue(int64 nFees) const
799 int64 nSubsidy = 50 * COIN;
801 // Subsidy is cut in half every 4 years
802 nSubsidy >>= (nBestHeight / 210000);
804 return nSubsidy + nFees;
807 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
809 const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
810 const unsigned int nTargetSpacing = 10 * 60;
811 const unsigned int nInterval = nTargetTimespan / nTargetSpacing;
814 if (pindexLast == NULL)
815 return bnProofOfWorkLimit.GetCompact();
817 // Only change once per interval
818 if ((pindexLast->nHeight+1) % nInterval != 0)
819 return pindexLast->nBits;
821 // Go back by what we want to be 14 days worth of blocks
822 const CBlockIndex* pindexFirst = pindexLast;
823 for (int i = 0; pindexFirst && i < nInterval-1; i++)
824 pindexFirst = pindexFirst->pprev;
827 // Limit adjustment step
828 unsigned int nActualTimespan = pindexLast->nTime - pindexFirst->nTime;
829 printf(" nActualTimespan = %d before bounds\n", nActualTimespan);
830 if (nActualTimespan < nTargetTimespan/4)
831 nActualTimespan = nTargetTimespan/4;
832 if (nActualTimespan > nTargetTimespan*4)
833 nActualTimespan = nTargetTimespan*4;
837 bnNew.SetCompact(pindexLast->nBits);
838 bnNew *= nActualTimespan;
839 bnNew /= nTargetTimespan;
841 if (bnNew > bnProofOfWorkLimit)
842 bnNew = bnProofOfWorkLimit;
845 printf("GetNextWorkRequired RETARGET\n");
846 printf("nTargetTimespan = %d nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);
847 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
848 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
850 return bnNew.GetCompact();
853 vector<int> vStartingHeight;
854 void AddStartingHeight(int nStartingHeight)
856 if (nStartingHeight != -1)
858 vStartingHeight.push_back(nStartingHeight);
859 sort(vStartingHeight.begin(), vStartingHeight.end());
863 bool IsInitialBlockDownload()
866 if (vStartingHeight.size() >= 5)
867 nMedian = vStartingHeight[vStartingHeight.size()/2];
868 return nBestHeight < nMedian-1000;
878 bool CTransaction::DisconnectInputs(CTxDB& txdb)
880 // Relinquish previous transactions' spent pointers
883 foreach(const CTxIn& txin, vin)
885 COutPoint prevout = txin.prevout;
887 // Get prev txindex from disk
889 if (!txdb.ReadTxIndex(prevout.hash, txindex))
890 return error("DisconnectInputs() : ReadTxIndex failed");
892 if (prevout.n >= txindex.vSpent.size())
893 return error("DisconnectInputs() : prevout.n out of range");
895 // Mark outpoint as not spent
896 txindex.vSpent[prevout.n].SetNull();
899 txdb.UpdateTxIndex(prevout.hash, txindex);
903 // Remove transaction from index
904 if (!txdb.EraseTxIndex(*this))
905 return error("DisconnectInputs() : EraseTxPos failed");
911 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
913 // Take over previous transactions' spent pointers
917 for (int i = 0; i < vin.size(); i++)
919 COutPoint prevout = vin[i].prevout;
924 if (fMiner && mapTestPool.count(prevout.hash))
926 // Get txindex from current proposed changes
927 txindex = mapTestPool[prevout.hash];
931 // Read txindex from txdb
932 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
934 if (!fFound && (fBlock || fMiner))
935 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());
939 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
941 // Get prev tx from single transactions in memory
942 CRITICAL_BLOCK(cs_mapTransactions)
944 if (!mapTransactions.count(prevout.hash))
945 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
946 txPrev = mapTransactions[prevout.hash];
949 txindex.vSpent.resize(txPrev.vout.size());
953 // Get prev tx from disk
954 if (!txPrev.ReadFromDisk(txindex.pos))
955 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
958 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
959 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());
961 // If prev is coinbase, check that it's matured
962 if (txPrev.IsCoinBase())
963 for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)
964 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
965 return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);
968 if (!VerifySignature(txPrev, *this, i))
969 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
971 // Check for conflicts
972 if (!txindex.vSpent[prevout.n].IsNull())
973 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());
975 // Mark outpoints as spent
976 txindex.vSpent[prevout.n] = posThisTx;
980 txdb.UpdateTxIndex(prevout.hash, txindex);
982 mapTestPool[prevout.hash] = txindex;
984 nValueIn += txPrev.vout[prevout.n].nValue;
987 // Tally transaction fees
988 int64 nTxFee = nValueIn - GetValueOut();
990 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
991 if (nTxFee < nMinFee)
998 // Add transaction to disk index
999 if (!txdb.AddTxIndex(*this, posThisTx, nHeight))
1000 return error("ConnectInputs() : AddTxPos failed");
1004 // Add transaction to test pool
1005 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1012 bool CTransaction::ClientConnectInputs()
1017 // Take over previous transactions' spent pointers
1018 CRITICAL_BLOCK(cs_mapTransactions)
1021 for (int i = 0; i < vin.size(); i++)
1023 // Get prev tx from single transactions in memory
1024 COutPoint prevout = vin[i].prevout;
1025 if (!mapTransactions.count(prevout.hash))
1027 CTransaction& txPrev = mapTransactions[prevout.hash];
1029 if (prevout.n >= txPrev.vout.size())
1033 if (!VerifySignature(txPrev, *this, i))
1034 return error("ConnectInputs() : VerifySignature failed");
1036 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1037 ///// this has to go away now that posNext is gone
1038 // // Check for conflicts
1039 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1040 // return error("ConnectInputs() : prev tx already used");
1042 // // Flag outpoints as used
1043 // txPrev.vout[prevout.n].posNext = posThisTx;
1045 nValueIn += txPrev.vout[prevout.n].nValue;
1047 if (GetValueOut() > nValueIn)
1057 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1059 // Disconnect in reverse order
1060 for (int i = vtx.size()-1; i >= 0; i--)
1061 if (!vtx[i].DisconnectInputs(txdb))
1064 // Update block index on disk without changing it in memory.
1065 // The memory index structure will be changed after the db commits.
1068 CDiskBlockIndex blockindexPrev(pindex->pprev);
1069 blockindexPrev.hashNext = 0;
1070 txdb.WriteBlockIndex(blockindexPrev);
1076 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1078 //// issue here: it doesn't know the version
1079 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1081 map<uint256, CTxIndex> mapUnused;
1083 foreach(CTransaction& tx, vtx)
1085 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1086 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1088 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))
1092 if (vtx[0].GetValueOut() > GetBlockValue(nFees))
1095 // Update block index on disk without changing it in memory.
1096 // The memory index structure will be changed after the db commits.
1099 CDiskBlockIndex blockindexPrev(pindex->pprev);
1100 blockindexPrev.hashNext = pindex->GetBlockHash();
1101 txdb.WriteBlockIndex(blockindexPrev);
1104 // Watch for transactions paying to me
1105 foreach(CTransaction& tx, vtx)
1106 AddToWalletIfMine(tx, this);
1113 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1115 printf("REORGANIZE\n");
1118 CBlockIndex* pfork = pindexBest;
1119 CBlockIndex* plonger = pindexNew;
1120 while (pfork != plonger)
1122 if (!(pfork = pfork->pprev))
1123 return error("Reorganize() : pfork->pprev is null");
1124 while (plonger->nHeight > pfork->nHeight)
1125 if (!(plonger = plonger->pprev))
1126 return error("Reorganize() : plonger->pprev is null");
1129 // List of what to disconnect
1130 vector<CBlockIndex*> vDisconnect;
1131 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1132 vDisconnect.push_back(pindex);
1134 // List of what to connect
1135 vector<CBlockIndex*> vConnect;
1136 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1137 vConnect.push_back(pindex);
1138 reverse(vConnect.begin(), vConnect.end());
1140 // Disconnect shorter branch
1141 vector<CTransaction> vResurrect;
1142 foreach(CBlockIndex* pindex, vDisconnect)
1145 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1146 return error("Reorganize() : ReadFromDisk for disconnect failed");
1147 if (!block.DisconnectBlock(txdb, pindex))
1148 return error("Reorganize() : DisconnectBlock failed");
1150 // Queue memory transactions to resurrect
1151 foreach(const CTransaction& tx, block.vtx)
1152 if (!tx.IsCoinBase())
1153 vResurrect.push_back(tx);
1156 // Connect longer branch
1157 vector<CTransaction> vDelete;
1158 for (int i = 0; i < vConnect.size(); i++)
1160 CBlockIndex* pindex = vConnect[i];
1162 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1163 return error("Reorganize() : ReadFromDisk for connect failed");
1164 if (!block.ConnectBlock(txdb, pindex))
1166 // Invalid block, delete the rest of this branch
1168 for (int j = i; j < vConnect.size(); j++)
1170 CBlockIndex* pindex = vConnect[j];
1171 pindex->EraseBlockFromDisk();
1172 txdb.EraseBlockIndex(pindex->GetBlockHash());
1173 mapBlockIndex.erase(pindex->GetBlockHash());
1176 return error("Reorganize() : ConnectBlock failed");
1179 // Queue memory transactions to delete
1180 foreach(const CTransaction& tx, block.vtx)
1181 vDelete.push_back(tx);
1183 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1184 return error("Reorganize() : WriteHashBestChain failed");
1186 // Commit now because resurrecting could take some time
1189 // Disconnect shorter branch
1190 foreach(CBlockIndex* pindex, vDisconnect)
1192 pindex->pprev->pnext = NULL;
1194 // Connect longer branch
1195 foreach(CBlockIndex* pindex, vConnect)
1197 pindex->pprev->pnext = pindex;
1199 // Resurrect memory transactions that were in the disconnected branch
1200 foreach(CTransaction& tx, vResurrect)
1201 tx.AcceptTransaction(txdb, false);
1203 // Delete redundant memory transactions that are in the connected branch
1204 foreach(CTransaction& tx, vDelete)
1205 tx.RemoveFromMemoryPool();
1211 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1213 // Check for duplicate
1214 uint256 hash = GetHash();
1215 if (mapBlockIndex.count(hash))
1216 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());
1218 // Construct new block index object
1219 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1221 return error("AddToBlockIndex() : new CBlockIndex failed");
1222 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1223 pindexNew->phashBlock = &((*mi).first);
1224 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1225 if (miPrev != mapBlockIndex.end())
1227 pindexNew->pprev = (*miPrev).second;
1228 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1230 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1234 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1237 if (pindexNew->bnChainWork > bnBestChainWork)
1239 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1241 pindexGenesisBlock = pindexNew;
1242 txdb.WriteHashBestChain(hash);
1244 else if (hashPrevBlock == hashBestChain)
1246 // Adding to current best branch
1247 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1250 pindexNew->EraseBlockFromDisk();
1251 mapBlockIndex.erase(pindexNew->GetBlockHash());
1253 return error("AddToBlockIndex() : ConnectBlock failed");
1256 pindexNew->pprev->pnext = pindexNew;
1258 // Delete redundant memory transactions
1259 foreach(CTransaction& tx, vtx)
1260 tx.RemoveFromMemoryPool();
1265 if (!Reorganize(txdb, pindexNew))
1268 return error("AddToBlockIndex() : Reorganize failed");
1273 hashBestChain = hash;
1274 pindexBest = pindexNew;
1275 nBestHeight = pindexBest->nHeight;
1276 bnBestChainWork = pindexNew->bnChainWork;
1277 nTimeBestReceived = GetTime();
1278 nTransactionsUpdated++;
1279 printf("AddToBlockIndex: new best=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);
1285 if (pindexNew == pindexBest)
1287 // Notify UI to display prev block's coinbase if it was ours
1288 static uint256 hashPrevBestCoinBase;
1289 CRITICAL_BLOCK(cs_mapWallet)
1290 vWalletUpdated.push_back(hashPrevBestCoinBase);
1291 hashPrevBestCoinBase = vtx[0].GetHash();
1301 bool CBlock::CheckBlock() const
1303 // These are checks that are independent of context
1304 // that can be verified before saving an orphan block.
1307 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
1308 return error("CheckBlock() : size limits failed");
1311 if (nTime > GetAdjustedTime() + 2 * 60 * 60)
1312 return error("CheckBlock() : block timestamp too far in the future");
1314 // First transaction must be coinbase, the rest must not be
1315 if (vtx.empty() || !vtx[0].IsCoinBase())
1316 return error("CheckBlock() : first tx is not coinbase");
1317 for (int i = 1; i < vtx.size(); i++)
1318 if (vtx[i].IsCoinBase())
1319 return error("CheckBlock() : more than one coinbase");
1321 // Check transactions
1322 foreach(const CTransaction& tx, vtx)
1323 if (!tx.CheckTransaction())
1324 return error("CheckBlock() : CheckTransaction failed");
1326 // Check proof of work matches claimed amount
1327 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
1328 return error("CheckBlock() : nBits below minimum work");
1329 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
1330 return error("CheckBlock() : hash doesn't match nBits");
1333 if (hashMerkleRoot != BuildMerkleTree())
1334 return error("CheckBlock() : hashMerkleRoot mismatch");
1339 bool CBlock::AcceptBlock()
1341 // Check for duplicate
1342 uint256 hash = GetHash();
1343 if (mapBlockIndex.count(hash))
1344 return error("AcceptBlock() : block already in mapBlockIndex");
1346 // Get prev block index
1347 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1348 if (mi == mapBlockIndex.end())
1349 return error("AcceptBlock() : prev block not found");
1350 CBlockIndex* pindexPrev = (*mi).second;
1352 // Check timestamp against prev
1353 if (nTime <= pindexPrev->GetMedianTimePast())
1354 return error("AcceptBlock() : block's timestamp is too early");
1356 // Check that all transactions are finalized
1357 foreach(const CTransaction& tx, vtx)
1358 if (!tx.IsFinal(nTime))
1359 return error("AcceptBlock() : contains a non-final transaction");
1361 // Check proof of work
1362 if (nBits != GetNextWorkRequired(pindexPrev))
1363 return error("AcceptBlock() : incorrect proof of work");
1365 // Check that the block chain matches the known block chain up to a checkpoint
1366 if (pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
1367 return error("AcceptBlock() : rejected by checkpoint lockin at 11111");
1368 if (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
1369 return error("AcceptBlock() : rejected by checkpoint lockin at 33333");
1370 if (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a"))
1371 return error("AcceptBlock() : rejected by checkpoint lockin at 68555");
1373 // Write block to history file
1374 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1375 return error("AcceptBlock() : out of disk space");
1377 unsigned int nBlockPos;
1378 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1379 return error("AcceptBlock() : WriteToDisk failed");
1380 if (!AddToBlockIndex(nFile, nBlockPos))
1381 return error("AcceptBlock() : AddToBlockIndex failed");
1383 // Relay inventory, but don't relay old inventory during initial block download
1384 if (hashBestChain == hash)
1385 CRITICAL_BLOCK(cs_vNodes)
1386 foreach(CNode* pnode, vNodes)
1387 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1388 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1393 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1395 // Check for duplicate
1396 uint256 hash = pblock->GetHash();
1397 if (mapBlockIndex.count(hash))
1398 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());
1399 if (mapOrphanBlocks.count(hash))
1400 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());
1402 // Preliminary checks
1403 if (!pblock->CheckBlock())
1406 return error("ProcessBlock() : CheckBlock FAILED");
1409 // If don't already have its previous block, shunt it off to holding area until we get it
1410 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1412 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());
1413 mapOrphanBlocks.insert(make_pair(hash, pblock));
1414 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1416 // Ask this guy to fill in what we're missing
1418 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1423 if (!pblock->AcceptBlock())
1426 return error("ProcessBlock() : AcceptBlock FAILED");
1430 // Recursively process any orphan blocks that depended on this one
1431 vector<uint256> vWorkQueue;
1432 vWorkQueue.push_back(hash);
1433 for (int i = 0; i < vWorkQueue.size(); i++)
1435 uint256 hashPrev = vWorkQueue[i];
1436 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1437 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1440 CBlock* pblockOrphan = (*mi).second;
1441 if (pblockOrphan->AcceptBlock())
1442 vWorkQueue.push_back(pblockOrphan->GetHash());
1443 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1444 delete pblockOrphan;
1446 mapOrphanBlocksByPrev.erase(hashPrev);
1449 printf("ProcessBlock: ACCEPTED\n");
1460 template<typename Stream>
1461 bool ScanMessageStart(Stream& s)
1463 // Scan ahead to the next pchMessageStart, which should normally be immediately
1464 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1466 short prevmask = s.exceptions(0);
1467 const char* p = BEGIN(pchMessageStart);
1477 s.exceptions(prevmask);
1481 p = BEGIN(pchMessageStart);
1484 if (++p == END(pchMessageStart))
1487 s.exceptions(prevmask);
1496 s.exceptions(prevmask);
1501 bool CheckDiskSpace(int64 nAdditionalBytes)
1503 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1505 // Check for 15MB because database could create another 10MB log file at any time
1506 if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)
1509 printf("*** %s***\n", _("Warning: Disk space is low "));
1511 ThreadSafeMessageBox(_("Warning: Disk space is low "), "Bitcoin", wxOK | wxICON_EXCLAMATION);
1513 CreateThread(Shutdown, NULL);
1519 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1523 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1526 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1528 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1537 static unsigned int nCurrentBlockFile = 1;
1539 FILE* AppendBlockFile(unsigned int& nFileRet)
1544 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1547 if (fseek(file, 0, SEEK_END) != 0)
1549 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1550 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1552 nFileRet = nCurrentBlockFile;
1556 nCurrentBlockFile++;
1560 bool LoadBlockIndex(bool fAllowNew)
1566 if (!txdb.LoadBlockIndex())
1571 // Init with genesis block
1573 if (mapBlockIndex.empty())
1580 // GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
1581 // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
1582 // txNew.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
1583 // txNew.vout[0].nValue = 5000000000
1584 // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG
1585 // block.nVersion = 1
1586 // block.nTime = 1231006505
1587 // block.nBits = 0x1d00ffff
1588 // block.nNonce = 2083236893
1589 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1590 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1591 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1592 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1593 // vMerkleTree: 4a5e1e
1596 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1598 txNew.vin.resize(1);
1599 txNew.vout.resize(1);
1600 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1601 txNew.vout[0].nValue = 50 * COIN;
1603 bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");
1604 txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;
1606 block.vtx.push_back(txNew);
1607 block.hashPrevBlock = 0;
1608 block.hashMerkleRoot = block.BuildMerkleTree();
1610 block.nTime = 1231006505;
1611 block.nBits = 0x1d00ffff;
1612 block.nNonce = 2083236893;
1615 printf("%s\n", block.GetHash().ToString().c_str());
1616 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1617 printf("%s\n", hashGenesisBlock.ToString().c_str());
1618 txNew.vout[0].scriptPubKey.print();
1620 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1622 assert(block.GetHash() == hashGenesisBlock);
1624 // Start new block file
1626 unsigned int nBlockPos;
1627 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1628 return error("LoadBlockIndex() : writing genesis block to disk failed");
1629 if (!block.AddToBlockIndex(nFile, nBlockPos))
1630 return error("LoadBlockIndex() : genesis block not accepted");
1638 void PrintBlockTree()
1640 // precompute tree structure
1641 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1642 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1644 CBlockIndex* pindex = (*mi).second;
1645 mapNext[pindex->pprev].push_back(pindex);
1647 //while (rand() % 3 == 0)
1648 // mapNext[pindex->pprev].push_back(pindex);
1651 vector<pair<int, CBlockIndex*> > vStack;
1652 vStack.push_back(make_pair(0, pindexGenesisBlock));
1655 while (!vStack.empty())
1657 int nCol = vStack.back().first;
1658 CBlockIndex* pindex = vStack.back().second;
1661 // print split or gap
1662 if (nCol > nPrevCol)
1664 for (int i = 0; i < nCol-1; i++)
1668 else if (nCol < nPrevCol)
1670 for (int i = 0; i < nCol; i++)
1677 for (int i = 0; i < nCol; i++)
1682 block.ReadFromDisk(pindex);
1683 printf("%d (%u,%u) %s %s tx %d",
1687 block.GetHash().ToString().substr(0,16).c_str(),
1688 DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),
1691 CRITICAL_BLOCK(cs_mapWallet)
1693 if (mapWallet.count(block.vtx[0].GetHash()))
1695 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1696 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1702 // put the main timechain first
1703 vector<CBlockIndex*>& vNext = mapNext[pindex];
1704 for (int i = 0; i < vNext.size(); i++)
1706 if (vNext[i]->pnext)
1708 swap(vNext[0], vNext[i]);
1714 for (int i = 0; i < vNext.size(); i++)
1715 vStack.push_back(make_pair(nCol+i, vNext[i]));
1728 //////////////////////////////////////////////////////////////////////////////
1734 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1738 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1739 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1741 // Don't know what it is, just say we already got one
1751 bool ProcessMessages(CNode* pfrom)
1753 CDataStream& vRecv = pfrom->vRecv;
1757 // printf("ProcessMessages(%d bytes)\n", vRecv.size());
1761 // (4) message start
1770 // Scan for message start
1771 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
1772 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
1773 if (vRecv.end() - pstart < nHeaderSize)
1775 if (vRecv.size() > nHeaderSize)
1777 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
1778 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
1782 if (pstart - vRecv.begin() > 0)
1783 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
1784 vRecv.erase(vRecv.begin(), pstart);
1787 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
1792 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
1795 string strCommand = hdr.GetCommand();
1798 unsigned int nMessageSize = hdr.nMessageSize;
1799 if (nMessageSize > vRecv.size())
1801 // Rewind and wait for rest of message
1802 ///// need a mechanism to give up waiting for overlong message size error
1803 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
1807 // Copy message to its own buffer
1808 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
1809 vRecv.ignore(nMessageSize);
1812 if (vRecv.GetVersion() >= 209)
1814 uint256 hash = Hash(vMsg.begin(), vMsg.end());
1815 unsigned int nChecksum = 0;
1816 memcpy(&nChecksum, &hash, sizeof(nChecksum));
1817 if (nChecksum != hdr.nChecksum)
1819 printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
1820 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
1829 CRITICAL_BLOCK(cs_main)
1830 fRet = ProcessMessage(pfrom, strCommand, vMsg);
1834 catch (std::ios_base::failure& e)
1836 if (strstr(e.what(), "CDataStream::read() : end of data"))
1838 // Allow exceptions from underlength message on vRecv
1839 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());
1841 else if (strstr(e.what(), ": size too large"))
1843 // Allow exceptions from overlong size
1844 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
1848 PrintException(&e, "ProcessMessage()");
1851 catch (std::exception& e) {
1852 PrintException(&e, "ProcessMessage()");
1854 PrintException(NULL, "ProcessMessage()");
1858 printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);
1868 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1870 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1871 RandAddSeedPerfmon();
1873 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1874 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1875 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1877 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1885 if (strCommand == "version")
1887 // Each connection can only send one version message
1888 if (pfrom->nVersion != 0)
1896 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1897 if (pfrom->nVersion == 10300)
1898 pfrom->nVersion = 300;
1899 if (pfrom->nVersion >= 106 && !vRecv.empty())
1900 vRecv >> addrFrom >> nNonce;
1901 if (pfrom->nVersion >= 106 && !vRecv.empty())
1903 if (pfrom->nVersion >= 209 && !vRecv.empty())
1904 vRecv >> pfrom->nStartingHeight;
1906 if (pfrom->nVersion == 0)
1909 // Disconnect if we connected to ourself
1910 if (nNonce == nLocalHostNonce && nNonce > 1)
1912 pfrom->fDisconnect = true;
1916 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1919 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
1920 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
1923 AddTimeData(pfrom->addr.ip, nTime);
1924 AddStartingHeight(pfrom->nStartingHeight);
1927 if (pfrom->nVersion >= 209)
1928 pfrom->PushMessage("verack");
1929 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1930 if (pfrom->nVersion < 209)
1931 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1933 // Ask the first connected node for block updates
1934 static int nAskedForBlocks;
1935 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1938 pfrom->PushGetBlocks(pindexBest, uint256(0));
1941 pfrom->fSuccessfullyConnected = true;
1943 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1947 else if (pfrom->nVersion == 0)
1949 // Must have a version message before anything else
1954 else if (strCommand == "verack")
1956 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1960 else if (strCommand == "addr")
1962 vector<CAddress> vAddr;
1964 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
1966 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
1968 if (vAddr.size() > 1000)
1969 return error("message addr size() = %d", vAddr.size());
1971 // Store the new addresses
1972 foreach(CAddress& addr, vAddr)
1976 // ignore IPv6 for now, since it isn't implemented anyway
1979 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
1980 if (pfrom->fGetAddr || vAddr.size() > 10)
1981 addr.nTime -= 5 * 24 * 60 * 60;
1983 pfrom->AddAddressKnown(addr);
1984 if (!pfrom->fGetAddr && addr.IsRoutable())
1986 // Relay to a limited number of other nodes
1987 CRITICAL_BLOCK(cs_vNodes)
1989 // Use deterministic randomness to send to
1990 // the same places for 12 hours at a time
1991 static uint256 hashSalt;
1993 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1994 uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
1995 multimap<uint256, CNode*> mapMix;
1996 foreach(CNode* pnode, vNodes)
1997 mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
1998 int nRelayNodes = 4;
1999 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2000 ((*mi).second)->PushAddress(addr);
2004 if (vAddr.size() < 1000)
2005 pfrom->fGetAddr = false;
2009 else if (strCommand == "inv")
2013 if (vInv.size() > 50000)
2014 return error("message inv size() = %d", vInv.size());
2017 foreach(const CInv& inv, vInv)
2021 pfrom->AddInventoryKnown(inv);
2023 bool fAlreadyHave = AlreadyHave(txdb, inv);
2024 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2028 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2029 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2031 // Track requests for our stuff
2032 CRITICAL_BLOCK(cs_mapRequestCount)
2034 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2035 if (mi != mapRequestCount.end())
2042 else if (strCommand == "getdata")
2046 if (vInv.size() > 50000)
2047 return error("message getdata size() = %d", vInv.size());
2049 foreach(const CInv& inv, vInv)
2053 printf("received getdata for: %s\n", inv.ToString().c_str());
2055 if (inv.type == MSG_BLOCK)
2057 // Send block from disk
2058 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2059 if (mi != mapBlockIndex.end())
2061 //// could optimize this to send header straight from blockindex for client
2063 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2064 pfrom->PushMessage("block", block);
2066 // Trigger them to send a getblocks request for the next batch of inventory
2067 if (inv.hash == pfrom->hashContinue)
2069 // Bypass PushInventory, this must send even if redundant,
2070 // and we want it right after the last block so they don't
2071 // wait for other stuff first.
2073 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2074 pfrom->PushMessage("inv", vInv);
2075 pfrom->hashContinue = 0;
2079 else if (inv.IsKnownType())
2081 // Send stream from relay memory
2082 CRITICAL_BLOCK(cs_mapRelay)
2084 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2085 if (mi != mapRelay.end())
2086 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2090 // Track requests for our stuff
2091 CRITICAL_BLOCK(cs_mapRequestCount)
2093 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2094 if (mi != mapRequestCount.end())
2101 else if (strCommand == "getblocks")
2103 CBlockLocator locator;
2105 vRecv >> locator >> hashStop;
2107 // Find the first block the caller has in the main chain
2108 CBlockIndex* pindex = locator.GetBlockIndex();
2110 // Send the rest of the chain
2112 pindex = pindex->pnext;
2113 int nLimit = 500 + locator.GetDistanceBack();
2114 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);
2115 for (; pindex; pindex = pindex->pnext)
2117 if (pindex->GetBlockHash() == hashStop)
2119 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2122 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2125 // When this block is requested, we'll send an inv that'll make them
2126 // getblocks the next batch of inventory.
2127 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2128 pfrom->hashContinue = pindex->GetBlockHash();
2135 else if (strCommand == "tx")
2137 vector<uint256> vWorkQueue;
2138 CDataStream vMsg(vRecv);
2142 CInv inv(MSG_TX, tx.GetHash());
2143 pfrom->AddInventoryKnown(inv);
2145 bool fMissingInputs = false;
2146 if (tx.AcceptTransaction(true, &fMissingInputs))
2148 AddToWalletIfMine(tx, NULL);
2149 RelayMessage(inv, vMsg);
2150 mapAlreadyAskedFor.erase(inv);
2151 vWorkQueue.push_back(inv.hash);
2153 // Recursively process any orphan transactions that depended on this one
2154 for (int i = 0; i < vWorkQueue.size(); i++)
2156 uint256 hashPrev = vWorkQueue[i];
2157 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2158 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2161 const CDataStream& vMsg = *((*mi).second);
2163 CDataStream(vMsg) >> tx;
2164 CInv inv(MSG_TX, tx.GetHash());
2166 if (tx.AcceptTransaction(true))
2168 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2169 AddToWalletIfMine(tx, NULL);
2170 RelayMessage(inv, vMsg);
2171 mapAlreadyAskedFor.erase(inv);
2172 vWorkQueue.push_back(inv.hash);
2177 foreach(uint256 hash, vWorkQueue)
2178 EraseOrphanTx(hash);
2180 else if (fMissingInputs)
2182 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2188 else if (strCommand == "block")
2190 auto_ptr<CBlock> pblock(new CBlock);
2194 printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());
2197 CInv inv(MSG_BLOCK, pblock->GetHash());
2198 pfrom->AddInventoryKnown(inv);
2200 if (ProcessBlock(pfrom, pblock.release()))
2201 mapAlreadyAskedFor.erase(inv);
2205 else if (strCommand == "getaddr")
2207 // This includes all nodes that are currently online,
2208 // since they rebroadcast an addr every 24 hours
2209 pfrom->vAddrToSend.clear();
2210 int64 nSince = GetAdjustedTime() - 24 * 60 * 60; // in the last 24 hours
2211 CRITICAL_BLOCK(cs_mapAddresses)
2213 unsigned int nSize = mapAddresses.size();
2214 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2218 const CAddress& addr = item.second;
2219 if (addr.nTime > nSince)
2220 pfrom->PushAddress(addr);
2226 else if (strCommand == "checkorder")
2230 vRecv >> hashReply >> order;
2232 /// we have a chance to check the order here
2234 // Keep giving the same key to the same ip until they use it
2235 if (!mapReuseKey.count(pfrom->addr.ip))
2236 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
2238 // Send back approval of order and pubkey to use
2239 CScript scriptPubKey;
2240 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2241 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2245 else if (strCommand == "submitorder")
2249 vRecv >> hashReply >> wtxNew;
2250 wtxNew.fFromMe = false;
2253 if (!wtxNew.AcceptWalletTransaction())
2255 pfrom->PushMessage("reply", hashReply, (int)1);
2256 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2258 wtxNew.fTimeReceivedIsTxTime = true;
2259 AddToWallet(wtxNew);
2260 wtxNew.RelayWalletTransaction();
2261 mapReuseKey.erase(pfrom->addr.ip);
2263 // Send back confirmation
2264 pfrom->PushMessage("reply", hashReply, (int)0);
2268 else if (strCommand == "reply")
2273 CRequestTracker tracker;
2274 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2276 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2277 if (mi != pfrom->mapRequests.end())
2279 tracker = (*mi).second;
2280 pfrom->mapRequests.erase(mi);
2283 if (!tracker.IsNull())
2284 tracker.fn(tracker.param1, vRecv);
2288 else if (strCommand == "ping")
2295 // Ignore unknown commands for extensibility
2299 // Update the last seen time for this node's address
2300 if (pfrom->fNetworkNode)
2301 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2302 AddressCurrentlyConnected(pfrom->addr);
2316 bool SendMessages(CNode* pto, bool fSendTrickle)
2318 CRITICAL_BLOCK(cs_main)
2320 // Don't send anything until we get their version message
2321 if (pto->nVersion == 0)
2325 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2326 pto->PushMessage("ping");
2328 // Address refresh broadcast
2329 static int64 nLastRebroadcast;
2330 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2332 nLastRebroadcast = GetTime();
2333 CRITICAL_BLOCK(cs_vNodes)
2335 foreach(CNode* pnode, vNodes)
2337 // Periodically clear setAddrKnown to allow refresh broadcasts
2338 pnode->setAddrKnown.clear();
2340 // Rebroadcast our address
2341 if (addrLocalHost.IsRoutable() && !fUseProxy)
2342 pnode->PushAddress(addrLocalHost);
2347 // Resend wallet transactions that haven't gotten in a block yet
2348 ResendWalletTransactions();
2356 vector<CAddress> vAddr;
2357 vAddr.reserve(pto->vAddrToSend.size());
2358 foreach(const CAddress& addr, pto->vAddrToSend)
2360 // returns true if wasn't already contained in the set
2361 if (pto->setAddrKnown.insert(addr).second)
2363 vAddr.push_back(addr);
2364 // receiver rejects addr messages larger than 1000
2365 if (vAddr.size() >= 1000)
2367 pto->PushMessage("addr", vAddr);
2372 pto->vAddrToSend.clear();
2374 pto->PushMessage("addr", vAddr);
2379 // Message: inventory
2382 vector<CInv> vInvWait;
2383 CRITICAL_BLOCK(pto->cs_inventory)
2385 vInv.reserve(pto->vInventoryToSend.size());
2386 vInvWait.reserve(pto->vInventoryToSend.size());
2387 foreach(const CInv& inv, pto->vInventoryToSend)
2389 if (pto->setInventoryKnown.count(inv))
2392 // trickle out tx inv to protect privacy
2393 if (inv.type == MSG_TX && !fSendTrickle)
2395 // 1/4 of tx invs blast to all immediately
2396 static uint256 hashSalt;
2398 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2399 uint256 hashRand = inv.hash ^ hashSalt;
2400 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2401 bool fTrickleWait = ((hashRand & 3) != 0);
2403 // always trickle our own transactions
2406 TRY_CRITICAL_BLOCK(cs_mapWallet)
2408 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2409 if (mi != mapWallet.end())
2411 CWalletTx& wtx = (*mi).second;
2413 fTrickleWait = true;
2420 vInvWait.push_back(inv);
2425 // returns true if wasn't already contained in the set
2426 if (pto->setInventoryKnown.insert(inv).second)
2428 vInv.push_back(inv);
2429 if (vInv.size() >= 1000)
2431 pto->PushMessage("inv", vInv);
2436 pto->vInventoryToSend = vInvWait;
2439 pto->PushMessage("inv", vInv);
2445 vector<CInv> vGetData;
2446 int64 nNow = GetTime() * 1000000;
2448 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2450 const CInv& inv = (*pto->mapAskFor.begin()).second;
2451 if (!AlreadyHave(txdb, inv))
2453 printf("sending getdata: %s\n", inv.ToString().c_str());
2454 vGetData.push_back(inv);
2455 if (vGetData.size() >= 1000)
2457 pto->PushMessage("getdata", vGetData);
2461 pto->mapAskFor.erase(pto->mapAskFor.begin());
2463 if (!vGetData.empty())
2464 pto->PushMessage("getdata", vGetData);
2483 //////////////////////////////////////////////////////////////////////////////
2488 void GenerateBitcoins(bool fGenerate)
2490 if (fGenerateBitcoins != fGenerate)
2492 fGenerateBitcoins = fGenerate;
2493 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2496 if (fGenerateBitcoins)
2498 int nProcessors = boost::thread::hardware_concurrency();
2499 printf("%d processors\n", nProcessors);
2500 if (nProcessors < 1)
2502 if (fLimitProcessors && nProcessors > nLimitProcessors)
2503 nProcessors = nLimitProcessors;
2504 int nAddThreads = nProcessors - vnThreadsRunning[3];
2505 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2506 for (int i = 0; i < nAddThreads; i++)
2508 if (!CreateThread(ThreadBitcoinMiner, NULL))
2509 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2515 void ThreadBitcoinMiner(void* parg)
2519 vnThreadsRunning[3]++;
2521 vnThreadsRunning[3]--;
2523 catch (std::exception& e) {
2524 vnThreadsRunning[3]--;
2525 PrintException(&e, "ThreadBitcoinMiner()");
2527 vnThreadsRunning[3]--;
2528 PrintException(NULL, "ThreadBitcoinMiner()");
2530 UIThreadCall(bind(CalledSetStatusBar, "", 0));
2531 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2534 int FormatHashBlocks(void* pbuffer, unsigned int len)
2536 unsigned char* pdata = (unsigned char*)pbuffer;
2537 unsigned int blocks = 1 + ((len + 8) / 64);
2538 unsigned char* pend = pdata + 64 * blocks;
2539 memset(pdata + len, 0, 64 * blocks - len);
2541 unsigned int bits = len * 8;
2542 pend[-1] = (bits >> 0) & 0xff;
2543 pend[-2] = (bits >> 8) & 0xff;
2544 pend[-3] = (bits >> 16) & 0xff;
2545 pend[-4] = (bits >> 24) & 0xff;
2549 using CryptoPP::ByteReverse;
2551 static const unsigned int pSHA256InitState[8] =
2552 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2554 static const unsigned int SHA256_K[64] = {
2555 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
2556 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
2557 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
2558 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
2559 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
2560 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
2561 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
2562 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
2563 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
2564 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
2565 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
2566 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
2567 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
2568 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
2569 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
2570 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
2573 #define blk0(i) (W[i] = dat[i])
2575 #define blk2(i) (W[i&15]+=s1(W[(i-2)&15])+W[(i-7)&15]+s0(W[(i-15)&15]))
2577 #define Ch(x,y,z) (z^(x&(y^z)))
2578 #define Maj(x,y,z) ((x&y)|(z&(x|y)))
2580 #define a(i) T[(0-i)&7]
2581 #define b(i) T[(1-i)&7]
2582 #define c(i) T[(2-i)&7]
2583 #define d(i) T[(3-i)&7]
2584 #define e(i) T[(4-i)&7]
2585 #define f(i) T[(5-i)&7]
2586 #define g(i) T[(6-i)&7]
2587 #define h(i) T[(7-i)&7]
2589 #define R(i,j) h(i)+=S1(e(i))+Ch(e(i),f(i),g(i))+SHA256_K[i+j]+(j?blk2(i):blk0(i));\
2590 d(i)+=h(i);h(i)+=S0(a(i))+Maj(a(i),b(i),c(i))
2592 #define rotrFixed(x,y) ((x>>y) | (x<<(sizeof(unsigned int)*8-y)))
2595 #define S0(x) (rotrFixed(x,2)^rotrFixed(x,13)^rotrFixed(x,22))
2596 #define S1(x) (rotrFixed(x,6)^rotrFixed(x,11)^rotrFixed(x,25))
2597 #define s0(x) (rotrFixed(x,7)^rotrFixed(x,18)^(x>>3))
2598 #define s1(x) (rotrFixed(x,17)^rotrFixed(x,19)^(x>>10))
2601 inline void SHA256Transform(void* pout, const void* pin, const void* pinit)
2603 memcpy(pout, pinit, 32);
2604 unsigned int* dat = (unsigned int*)pin;
2605 unsigned int* T = (unsigned int*)pout;
2606 unsigned int* initstate = (unsigned int*)pinit;
2609 R( 0, 0); R( 1, 0); R( 2, 0); R( 3, 0); R( 4, 0); R( 5, 0); R( 6, 0); R( 7, 0); R( 8, 0); R( 9, 0); R(10, 0); R(11, 0); R(12, 0); R(13, 0); R(14, 0); R(15, 0);
2610 R( 0, 16); R( 1, 16); R( 2, 16); R( 3, 16); R( 4, 16); R( 5, 16); R( 6, 16); R( 7, 16); R( 8, 16); R( 9, 16); R(10, 16); R(11, 16); R(12, 16); R(13, 16); R(14, 16); R(15, 16);
2611 R( 0, 32); R( 1, 32); R( 2, 32); R( 3, 32); R( 4, 32); R( 5, 32); R( 6, 32); R( 7, 32); R( 8, 32); R( 9, 32); R(10, 32); R(11, 32); R(12, 32); R(13, 32); R(14, 32); R(15, 32);
2612 R( 0, 48); R( 1, 48); R( 2, 48); R( 3, 48); R( 4, 48); R( 5, 48); R( 6, 48); R( 7, 48); R( 8, 48); R( 9, 48); R(10, 48); R(11, 48); R(12, 48); R(13, 48); R(14, 48); R(15, 48);
2614 T[0] += initstate[0];
2615 T[1] += initstate[1];
2616 T[2] += initstate[2];
2617 T[3] += initstate[3];
2618 T[4] += initstate[4];
2619 T[5] += initstate[5];
2620 T[6] += initstate[6];
2621 T[7] += initstate[7];
2624 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2626 memcpy(pstate, pinit, 32);
2627 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2637 printf("BitcoinMiner started\n");
2638 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2642 CBigNum bnExtraNonce = 0;
2643 while (fGenerateBitcoins)
2648 while (vNodes.empty())
2653 if (!fGenerateBitcoins)
2657 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2658 CBlockIndex* pindexPrev = pindexBest;
2659 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2663 // Create coinbase tx
2666 txNew.vin.resize(1);
2667 txNew.vin[0].prevout.SetNull();
2668 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
2669 txNew.vout.resize(1);
2670 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
2676 auto_ptr<CBlock> pblock(new CBlock());
2680 // Add our coinbase tx as first transaction
2681 pblock->vtx.push_back(txNew);
2683 // Collect the latest transactions into the block
2685 CRITICAL_BLOCK(cs_main)
2686 CRITICAL_BLOCK(cs_mapTransactions)
2689 map<uint256, CTxIndex> mapTestPool;
2690 vector<char> vfAlreadyAdded(mapTransactions.size());
2691 bool fFoundSomething = true;
2692 unsigned int nBlockSize = 0;
2693 while (fFoundSomething && nBlockSize < MAX_SIZE/2)
2695 fFoundSomething = false;
2697 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
2699 if (vfAlreadyAdded[n])
2701 CTransaction& tx = (*mi).second;
2702 if (tx.IsCoinBase() || !tx.IsFinal())
2704 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2705 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)
2708 // Transaction fee based on block size
2709 int64 nMinFee = tx.GetMinFee(nBlockSize);
2711 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2712 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))
2714 swap(mapTestPool, mapTestPoolTmp);
2716 pblock->vtx.push_back(tx);
2717 nBlockSize += nTxSize;
2718 vfAlreadyAdded[n] = true;
2719 fFoundSomething = true;
2723 pblock->nBits = nBits;
2724 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);
2725 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2729 // Prebuild hash buffer
2736 uint256 hashPrevBlock;
2737 uint256 hashMerkleRoot;
2740 unsigned int nNonce;
2743 unsigned char pchPadding0[64];
2745 unsigned char pchPadding1[64];
2749 tmp.block.nVersion = pblock->nVersion;
2750 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
2751 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2752 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
2753 tmp.block.nBits = pblock->nBits = nBits;
2754 tmp.block.nNonce = pblock->nNonce = 0;
2756 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2757 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2759 // Byte swap all the input buffer
2760 for (int i = 0; i < sizeof(tmp)/4; i++)
2761 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2763 // Precalc the first half of the first hash, which stays constant
2765 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
2771 int64 nStart = GetTime();
2772 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2776 SHA256Transform(&tmp.hash1, (char*)&tmp.block + 64, &midstate);
2777 SHA256Transform(&hash, &tmp.hash1, pSHA256InitState);
2779 if (((unsigned short*)&hash)[14] == 0)
2781 // Byte swap the result after preliminary check
2782 for (int i = 0; i < sizeof(hash)/4; i++)
2783 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
2785 if (hash <= hashTarget)
2787 pblock->nNonce = ByteReverse(tmp.block.nNonce);
2788 assert(hash == pblock->GetHash());
2791 printf("BitcoinMiner:\n");
2792 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2794 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2795 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2797 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2798 CRITICAL_BLOCK(cs_main)
2800 if (pindexPrev == pindexBest)
2807 // Track how many getdata requests this block gets
2808 CRITICAL_BLOCK(cs_mapRequestCount)
2809 mapRequestCount[pblock->GetHash()] = 0;
2811 // Process this block the same as if we had received it from another node
2812 if (!ProcessBlock(NULL, pblock.release()))
2813 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
2816 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2823 // Update nTime every few seconds
2824 const unsigned int nMask = 0xffff;
2825 if ((++tmp.block.nNonce & nMask) == 0)
2828 static int64 nTimerStart;
2829 static int nHashCounter;
2830 if (nTimerStart == 0)
2831 nTimerStart = GetTimeMillis();
2834 if (GetTimeMillis() - nTimerStart > 4000)
2836 static CCriticalSection cs;
2839 if (GetTimeMillis() - nTimerStart > 4000)
2841 double dHashesPerSec = 1000.0 * (nMask+1) * nHashCounter / (GetTimeMillis() - nTimerStart);
2842 nTimerStart = GetTimeMillis();
2844 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
2845 UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));
2846 static int64 nLogTime;
2847 if (GetTime() - nLogTime > 30 * 60)
2849 nLogTime = GetTime();
2850 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2851 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
2857 // Check for stop or if block needs to be rebuilt
2860 if (!fGenerateBitcoins)
2862 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
2866 if (tmp.block.nNonce == 0)
2868 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2870 if (pindexPrev != pindexBest)
2872 // Pause generating during initial download
2873 if (GetTime() - nStart < 20)
2875 CBlockIndex* pindexTmp;
2878 pindexTmp = pindexBest;
2879 for (int i = 0; i < 10; i++)
2886 while (pindexTmp != pindexBest);
2891 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2892 tmp.block.nTime = ByteReverse(pblock->nTime);
2915 //////////////////////////////////////////////////////////////////////////////
2923 int64 nStart = GetTimeMillis();
2926 CRITICAL_BLOCK(cs_mapWallet)
2928 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2930 CWalletTx* pcoin = &(*it).second;
2931 if (!pcoin->IsFinal() || pcoin->fSpent)
2933 nTotal += pcoin->GetCredit(true);
2937 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
2942 int GetRandInt(int nMax)
2944 return GetRand(nMax);
2947 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
2949 setCoinsRet.clear();
2951 // List of values less than target
2952 int64 nLowestLarger = INT64_MAX;
2953 CWalletTx* pcoinLowestLarger = NULL;
2954 vector<pair<int64, CWalletTx*> > vValue;
2955 int64 nTotalLower = 0;
2957 CRITICAL_BLOCK(cs_mapWallet)
2959 vector<CWalletTx*> vCoins;
2960 vCoins.reserve(mapWallet.size());
2961 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2962 vCoins.push_back(&(*it).second);
2963 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2965 foreach(CWalletTx* pcoin, vCoins)
2967 if (!pcoin->IsFinal() || pcoin->fSpent)
2969 int64 n = pcoin->GetCredit();
2972 if (n < nTargetValue)
2974 vValue.push_back(make_pair(n, pcoin));
2977 else if (n == nTargetValue)
2979 setCoinsRet.insert(pcoin);
2982 else if (n < nLowestLarger)
2985 pcoinLowestLarger = pcoin;
2990 if (nTotalLower < nTargetValue)
2992 if (pcoinLowestLarger == NULL)
2994 setCoinsRet.insert(pcoinLowestLarger);
2998 // Solve subset sum by stochastic approximation
2999 sort(vValue.rbegin(), vValue.rend());
3000 vector<char> vfIncluded;
3001 vector<char> vfBest(vValue.size(), true);
3002 int64 nBest = nTotalLower;
3004 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3006 vfIncluded.assign(vValue.size(), false);
3008 bool fReachedTarget = false;
3009 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3011 for (int i = 0; i < vValue.size(); i++)
3013 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3015 nTotal += vValue[i].first;
3016 vfIncluded[i] = true;
3017 if (nTotal >= nTargetValue)
3019 fReachedTarget = true;
3023 vfBest = vfIncluded;
3025 nTotal -= vValue[i].first;
3026 vfIncluded[i] = false;
3033 // If the next larger is still closer, return it
3034 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3035 setCoinsRet.insert(pcoinLowestLarger);
3038 for (int i = 0; i < vValue.size(); i++)
3040 setCoinsRet.insert(vValue[i].second);
3043 printf("SelectCoins() best subset: ");
3044 for (int i = 0; i < vValue.size(); i++)
3046 printf("%s ", FormatMoney(vValue[i].first).c_str());
3047 printf("total %s\n", FormatMoney(nBest).c_str());
3056 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
3058 nFeeRequiredRet = 0;
3059 CRITICAL_BLOCK(cs_main)
3061 // txdb must be opened before the mapWallet lock
3063 CRITICAL_BLOCK(cs_mapWallet)
3065 int64 nFee = nTransactionFee;
3069 wtxNew.vout.clear();
3070 wtxNew.fFromMe = true;
3073 int64 nValueOut = nValue;
3074 int64 nTotalValue = nValue + nFee;
3076 // Choose coins to use
3077 set<CWalletTx*> setCoins;
3078 if (!SelectCoins(nTotalValue, setCoins))
3081 foreach(CWalletTx* pcoin, setCoins)
3082 nValueIn += pcoin->GetCredit();
3084 // Fill a vout to the payee
3085 bool fChangeFirst = GetRand(2);
3087 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3089 // Fill a vout back to self with any change
3090 if (nValueIn > nTotalValue)
3092 // Note: We use a new key here to keep it from being obvious which side is the change.
3093 // The drawback is that by not reusing a previous key, the change may be lost if a
3094 // backup is restored, if the backup doesn't have the new private key for the change.
3095 // If we reused the old key, it would be possible to add code to look for and
3096 // rediscover unknown transactions that were written with keys of ours to recover
3097 // post-backup change.
3100 if (keyRet.IsNull())
3101 keyRet.MakeNewKey();
3103 // Fill a vout to ourself, using same address type as the payment
3104 CScript scriptChange;
3105 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3106 scriptChange.SetBitcoinAddress(keyRet.GetPubKey());
3108 scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;
3109 wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));
3112 // Fill a vout to the payee
3114 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3117 foreach(CWalletTx* pcoin, setCoins)
3118 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3119 if (pcoin->vout[nOut].IsMine())
3120 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3124 foreach(CWalletTx* pcoin, setCoins)
3125 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3126 if (pcoin->vout[nOut].IsMine())
3127 SignSignature(*pcoin, wtxNew, nIn++);
3129 // Check that enough fee is included
3130 if (nFee < wtxNew.GetMinFee())
3132 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3136 // Fill vtxPrev by copying from previous transactions vtxPrev
3137 wtxNew.AddSupportingTransactions(txdb);
3138 wtxNew.fTimeReceivedIsTxTime = true;
3147 // Call after CreateTransaction unless you want to abort
3148 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)
3150 CRITICAL_BLOCK(cs_main)
3152 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3153 CRITICAL_BLOCK(cs_mapWallet)
3155 // This is only to keep the database open to defeat the auto-flush for the
3156 // duration of this scope. This is the only place where this optimization
3157 // maybe makes sense; please don't do it anywhere else.
3158 CWalletDB walletdb("r");
3160 // Add the change's private key to wallet
3161 if (!key.IsNull() && !AddKey(key))
3162 throw runtime_error("CommitTransaction() : AddKey failed\n");
3164 // Add tx to wallet, because if it has change it's also ours,
3165 // otherwise just for transaction history.
3166 AddToWallet(wtxNew);
3168 // Mark old coins as spent
3169 set<CWalletTx*> setCoins;
3170 foreach(const CTxIn& txin, wtxNew.vin)
3171 setCoins.insert(&mapWallet[txin.prevout.hash]);
3172 foreach(CWalletTx* pcoin, setCoins)
3174 pcoin->fSpent = true;
3175 pcoin->WriteToDisk();
3176 vWalletUpdated.push_back(pcoin->GetHash());
3180 // Track how many getdata requests our transaction gets
3181 CRITICAL_BLOCK(cs_mapRequestCount)
3182 mapRequestCount[wtxNew.GetHash()] = 0;
3185 if (!wtxNew.AcceptTransaction())
3187 // This must not fail. The transaction has already been signed and recorded.
3188 printf("CommitTransaction() : Error: Transaction not valid");
3191 wtxNew.RelayWalletTransaction();
3200 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3202 CRITICAL_BLOCK(cs_main)
3206 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
3209 if (nValue + nFeeRequired > GetBalance())
3210 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3212 strError = _("Error: Transaction creation failed ");
3213 printf("SendMoney() : %s", strError.c_str());
3217 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3220 if (!CommitTransaction(wtxNew, key))
3221 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.");
3229 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3233 return _("Invalid amount");
3234 if (nValue + nTransactionFee > GetBalance())
3235 return _("Insufficient funds");
3237 // Parse bitcoin address
3238 CScript scriptPubKey;
3239 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3240 return _("Invalid bitcoin address");
3242 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);