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 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 int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
810 const int64 nTargetSpacing = 10 * 60;
811 const int64 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 int64 nActualTimespan = (int64)pindexLast->nTime - (int64)pindexFirst->nTime;
829 printf(" nActualTimespan = %"PRI64d" 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 = %"PRI64d" nActualTimespan = %"PRI64d"\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 bool IsInitialBlockDownload()
855 if (pindexBest == NULL)
857 static int64 nLastUpdate;
858 static CBlockIndex* pindexLastBest;
859 if (pindexBest != pindexLastBest)
861 pindexLastBest = pindexBest;
862 nLastUpdate = GetTime();
864 return (GetTime() - nLastUpdate < 10 &&
865 pindexBest->nTime < GetTime() - 24 * 60 * 60);
875 bool CTransaction::DisconnectInputs(CTxDB& txdb)
877 // Relinquish previous transactions' spent pointers
880 foreach(const CTxIn& txin, vin)
882 COutPoint prevout = txin.prevout;
884 // Get prev txindex from disk
886 if (!txdb.ReadTxIndex(prevout.hash, txindex))
887 return error("DisconnectInputs() : ReadTxIndex failed");
889 if (prevout.n >= txindex.vSpent.size())
890 return error("DisconnectInputs() : prevout.n out of range");
892 // Mark outpoint as not spent
893 txindex.vSpent[prevout.n].SetNull();
896 txdb.UpdateTxIndex(prevout.hash, txindex);
900 // Remove transaction from index
901 if (!txdb.EraseTxIndex(*this))
902 return error("DisconnectInputs() : EraseTxPos failed");
908 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
910 // Take over previous transactions' spent pointers
914 for (int i = 0; i < vin.size(); i++)
916 COutPoint prevout = vin[i].prevout;
921 if (fMiner && mapTestPool.count(prevout.hash))
923 // Get txindex from current proposed changes
924 txindex = mapTestPool[prevout.hash];
928 // Read txindex from txdb
929 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
931 if (!fFound && (fBlock || fMiner))
932 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());
936 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
938 // Get prev tx from single transactions in memory
939 CRITICAL_BLOCK(cs_mapTransactions)
941 if (!mapTransactions.count(prevout.hash))
942 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
943 txPrev = mapTransactions[prevout.hash];
946 txindex.vSpent.resize(txPrev.vout.size());
950 // Get prev tx from disk
951 if (!txPrev.ReadFromDisk(txindex.pos))
952 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
955 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
956 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());
958 // If prev is coinbase, check that it's matured
959 if (txPrev.IsCoinBase())
960 for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)
961 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
962 return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);
965 if (!VerifySignature(txPrev, *this, i))
966 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
968 // Check for conflicts
969 if (!txindex.vSpent[prevout.n].IsNull())
970 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());
972 // Mark outpoints as spent
973 txindex.vSpent[prevout.n] = posThisTx;
977 txdb.UpdateTxIndex(prevout.hash, txindex);
979 mapTestPool[prevout.hash] = txindex;
981 nValueIn += txPrev.vout[prevout.n].nValue;
984 // Tally transaction fees
985 int64 nTxFee = nValueIn - GetValueOut();
987 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
988 if (nTxFee < nMinFee)
995 // Add transaction to disk index
996 if (!txdb.AddTxIndex(*this, posThisTx, nHeight))
997 return error("ConnectInputs() : AddTxPos failed");
1001 // Add transaction to test pool
1002 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1009 bool CTransaction::ClientConnectInputs()
1014 // Take over previous transactions' spent pointers
1015 CRITICAL_BLOCK(cs_mapTransactions)
1018 for (int i = 0; i < vin.size(); i++)
1020 // Get prev tx from single transactions in memory
1021 COutPoint prevout = vin[i].prevout;
1022 if (!mapTransactions.count(prevout.hash))
1024 CTransaction& txPrev = mapTransactions[prevout.hash];
1026 if (prevout.n >= txPrev.vout.size())
1030 if (!VerifySignature(txPrev, *this, i))
1031 return error("ConnectInputs() : VerifySignature failed");
1033 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1034 ///// this has to go away now that posNext is gone
1035 // // Check for conflicts
1036 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1037 // return error("ConnectInputs() : prev tx already used");
1039 // // Flag outpoints as used
1040 // txPrev.vout[prevout.n].posNext = posThisTx;
1042 nValueIn += txPrev.vout[prevout.n].nValue;
1044 if (GetValueOut() > nValueIn)
1054 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1056 // Disconnect in reverse order
1057 for (int i = vtx.size()-1; i >= 0; i--)
1058 if (!vtx[i].DisconnectInputs(txdb))
1061 // Update block index on disk without changing it in memory.
1062 // The memory index structure will be changed after the db commits.
1065 CDiskBlockIndex blockindexPrev(pindex->pprev);
1066 blockindexPrev.hashNext = 0;
1067 txdb.WriteBlockIndex(blockindexPrev);
1073 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1075 //// issue here: it doesn't know the version
1076 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1078 map<uint256, CTxIndex> mapUnused;
1080 foreach(CTransaction& tx, vtx)
1082 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1083 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1085 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))
1089 if (vtx[0].GetValueOut() > GetBlockValue(nFees))
1092 // Update block index on disk without changing it in memory.
1093 // The memory index structure will be changed after the db commits.
1096 CDiskBlockIndex blockindexPrev(pindex->pprev);
1097 blockindexPrev.hashNext = pindex->GetBlockHash();
1098 txdb.WriteBlockIndex(blockindexPrev);
1101 // Watch for transactions paying to me
1102 foreach(CTransaction& tx, vtx)
1103 AddToWalletIfMine(tx, this);
1110 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1112 printf("REORGANIZE\n");
1115 CBlockIndex* pfork = pindexBest;
1116 CBlockIndex* plonger = pindexNew;
1117 while (pfork != plonger)
1119 if (!(pfork = pfork->pprev))
1120 return error("Reorganize() : pfork->pprev is null");
1121 while (plonger->nHeight > pfork->nHeight)
1122 if (!(plonger = plonger->pprev))
1123 return error("Reorganize() : plonger->pprev is null");
1126 // List of what to disconnect
1127 vector<CBlockIndex*> vDisconnect;
1128 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1129 vDisconnect.push_back(pindex);
1131 // List of what to connect
1132 vector<CBlockIndex*> vConnect;
1133 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1134 vConnect.push_back(pindex);
1135 reverse(vConnect.begin(), vConnect.end());
1137 // Disconnect shorter branch
1138 vector<CTransaction> vResurrect;
1139 foreach(CBlockIndex* pindex, vDisconnect)
1142 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1143 return error("Reorganize() : ReadFromDisk for disconnect failed");
1144 if (!block.DisconnectBlock(txdb, pindex))
1145 return error("Reorganize() : DisconnectBlock failed");
1147 // Queue memory transactions to resurrect
1148 foreach(const CTransaction& tx, block.vtx)
1149 if (!tx.IsCoinBase())
1150 vResurrect.push_back(tx);
1153 // Connect longer branch
1154 vector<CTransaction> vDelete;
1155 for (int i = 0; i < vConnect.size(); i++)
1157 CBlockIndex* pindex = vConnect[i];
1159 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1160 return error("Reorganize() : ReadFromDisk for connect failed");
1161 if (!block.ConnectBlock(txdb, pindex))
1163 // Invalid block, delete the rest of this branch
1165 for (int j = i; j < vConnect.size(); j++)
1167 CBlockIndex* pindex = vConnect[j];
1168 pindex->EraseBlockFromDisk();
1169 txdb.EraseBlockIndex(pindex->GetBlockHash());
1170 mapBlockIndex.erase(pindex->GetBlockHash());
1173 return error("Reorganize() : ConnectBlock failed");
1176 // Queue memory transactions to delete
1177 foreach(const CTransaction& tx, block.vtx)
1178 vDelete.push_back(tx);
1180 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1181 return error("Reorganize() : WriteHashBestChain failed");
1183 // Commit now because resurrecting could take some time
1186 // Disconnect shorter branch
1187 foreach(CBlockIndex* pindex, vDisconnect)
1189 pindex->pprev->pnext = NULL;
1191 // Connect longer branch
1192 foreach(CBlockIndex* pindex, vConnect)
1194 pindex->pprev->pnext = pindex;
1196 // Resurrect memory transactions that were in the disconnected branch
1197 foreach(CTransaction& tx, vResurrect)
1198 tx.AcceptTransaction(txdb, false);
1200 // Delete redundant memory transactions that are in the connected branch
1201 foreach(CTransaction& tx, vDelete)
1202 tx.RemoveFromMemoryPool();
1208 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1210 // Check for duplicate
1211 uint256 hash = GetHash();
1212 if (mapBlockIndex.count(hash))
1213 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());
1215 // Construct new block index object
1216 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1218 return error("AddToBlockIndex() : new CBlockIndex failed");
1219 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1220 pindexNew->phashBlock = &((*mi).first);
1221 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1222 if (miPrev != mapBlockIndex.end())
1224 pindexNew->pprev = (*miPrev).second;
1225 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1227 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1231 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1234 if (pindexNew->bnChainWork > bnBestChainWork)
1236 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1238 pindexGenesisBlock = pindexNew;
1239 txdb.WriteHashBestChain(hash);
1241 else if (hashPrevBlock == hashBestChain)
1243 // Adding to current best branch
1244 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1247 pindexNew->EraseBlockFromDisk();
1248 mapBlockIndex.erase(pindexNew->GetBlockHash());
1250 return error("AddToBlockIndex() : ConnectBlock failed");
1253 pindexNew->pprev->pnext = pindexNew;
1255 // Delete redundant memory transactions
1256 foreach(CTransaction& tx, vtx)
1257 tx.RemoveFromMemoryPool();
1262 if (!Reorganize(txdb, pindexNew))
1265 return error("AddToBlockIndex() : Reorganize failed");
1270 hashBestChain = hash;
1271 pindexBest = pindexNew;
1272 nBestHeight = pindexBest->nHeight;
1273 bnBestChainWork = pindexNew->bnChainWork;
1274 nTimeBestReceived = GetTime();
1275 nTransactionsUpdated++;
1276 printf("AddToBlockIndex: new best=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);
1282 if (pindexNew == pindexBest)
1284 // Notify UI to display prev block's coinbase if it was ours
1285 static uint256 hashPrevBestCoinBase;
1286 CRITICAL_BLOCK(cs_mapWallet)
1287 vWalletUpdated.push_back(hashPrevBestCoinBase);
1288 hashPrevBestCoinBase = vtx[0].GetHash();
1298 bool CBlock::CheckBlock() const
1300 // These are checks that are independent of context
1301 // that can be verified before saving an orphan block.
1304 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
1305 return error("CheckBlock() : size limits failed");
1308 if (nTime > GetAdjustedTime() + 2 * 60 * 60)
1309 return error("CheckBlock() : block timestamp too far in the future");
1311 // First transaction must be coinbase, the rest must not be
1312 if (vtx.empty() || !vtx[0].IsCoinBase())
1313 return error("CheckBlock() : first tx is not coinbase");
1314 for (int i = 1; i < vtx.size(); i++)
1315 if (vtx[i].IsCoinBase())
1316 return error("CheckBlock() : more than one coinbase");
1318 // Check transactions
1319 foreach(const CTransaction& tx, vtx)
1320 if (!tx.CheckTransaction())
1321 return error("CheckBlock() : CheckTransaction failed");
1323 // Check proof of work matches claimed amount
1324 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
1325 return error("CheckBlock() : nBits below minimum work");
1326 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
1327 return error("CheckBlock() : hash doesn't match nBits");
1330 if (hashMerkleRoot != BuildMerkleTree())
1331 return error("CheckBlock() : hashMerkleRoot mismatch");
1336 bool CBlock::AcceptBlock()
1338 // Check for duplicate
1339 uint256 hash = GetHash();
1340 if (mapBlockIndex.count(hash))
1341 return error("AcceptBlock() : block already in mapBlockIndex");
1343 // Get prev block index
1344 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1345 if (mi == mapBlockIndex.end())
1346 return error("AcceptBlock() : prev block not found");
1347 CBlockIndex* pindexPrev = (*mi).second;
1349 // Check timestamp against prev
1350 if (nTime <= pindexPrev->GetMedianTimePast())
1351 return error("AcceptBlock() : block's timestamp is too early");
1353 // Check that all transactions are finalized
1354 foreach(const CTransaction& tx, vtx)
1355 if (!tx.IsFinal(nTime))
1356 return error("AcceptBlock() : contains a non-final transaction");
1358 // Check proof of work
1359 if (nBits != GetNextWorkRequired(pindexPrev))
1360 return error("AcceptBlock() : incorrect proof of work");
1362 // Check that the block chain matches the known block chain up to a checkpoint
1363 if (pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
1364 return error("AcceptBlock() : rejected by checkpoint lockin at 11111");
1365 if (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
1366 return error("AcceptBlock() : rejected by checkpoint lockin at 33333");
1367 if (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a"))
1368 return error("AcceptBlock() : rejected by checkpoint lockin at 68555");
1369 if (pindexPrev->nHeight+1 == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a"))
1370 return error("AcceptBlock() : rejected by checkpoint lockin at 70567");
1372 // Write block to history file
1373 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1374 return error("AcceptBlock() : out of disk space");
1376 unsigned int nBlockPos;
1377 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1378 return error("AcceptBlock() : WriteToDisk failed");
1379 if (!AddToBlockIndex(nFile, nBlockPos))
1380 return error("AcceptBlock() : AddToBlockIndex failed");
1382 // Relay inventory, but don't relay old inventory during initial block download
1383 if (hashBestChain == hash)
1384 CRITICAL_BLOCK(cs_vNodes)
1385 foreach(CNode* pnode, vNodes)
1386 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1387 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1392 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1394 // Check for duplicate
1395 uint256 hash = pblock->GetHash();
1396 if (mapBlockIndex.count(hash))
1397 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());
1398 if (mapOrphanBlocks.count(hash))
1399 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());
1401 // Preliminary checks
1402 if (!pblock->CheckBlock())
1405 return error("ProcessBlock() : CheckBlock FAILED");
1408 // If don't already have its previous block, shunt it off to holding area until we get it
1409 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1411 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());
1412 mapOrphanBlocks.insert(make_pair(hash, pblock));
1413 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1415 // Ask this guy to fill in what we're missing
1417 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1422 if (!pblock->AcceptBlock())
1425 return error("ProcessBlock() : AcceptBlock FAILED");
1429 // Recursively process any orphan blocks that depended on this one
1430 vector<uint256> vWorkQueue;
1431 vWorkQueue.push_back(hash);
1432 for (int i = 0; i < vWorkQueue.size(); i++)
1434 uint256 hashPrev = vWorkQueue[i];
1435 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1436 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1439 CBlock* pblockOrphan = (*mi).second;
1440 if (pblockOrphan->AcceptBlock())
1441 vWorkQueue.push_back(pblockOrphan->GetHash());
1442 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1443 delete pblockOrphan;
1445 mapOrphanBlocksByPrev.erase(hashPrev);
1448 printf("ProcessBlock: ACCEPTED\n");
1459 template<typename Stream>
1460 bool ScanMessageStart(Stream& s)
1462 // Scan ahead to the next pchMessageStart, which should normally be immediately
1463 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1465 short prevmask = s.exceptions(0);
1466 const char* p = BEGIN(pchMessageStart);
1476 s.exceptions(prevmask);
1480 p = BEGIN(pchMessageStart);
1483 if (++p == END(pchMessageStart))
1486 s.exceptions(prevmask);
1495 s.exceptions(prevmask);
1500 bool CheckDiskSpace(int64 nAdditionalBytes)
1502 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1504 // Check for 15MB because database could create another 10MB log file at any time
1505 if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)
1508 printf("*** %s***\n", _("Warning: Disk space is low "));
1510 ThreadSafeMessageBox(_("Warning: Disk space is low "), "Bitcoin", wxOK | wxICON_EXCLAMATION);
1512 CreateThread(Shutdown, NULL);
1518 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1522 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1525 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1527 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1536 static unsigned int nCurrentBlockFile = 1;
1538 FILE* AppendBlockFile(unsigned int& nFileRet)
1543 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1546 if (fseek(file, 0, SEEK_END) != 0)
1548 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1549 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1551 nFileRet = nCurrentBlockFile;
1555 nCurrentBlockFile++;
1559 bool LoadBlockIndex(bool fAllowNew)
1565 if (!txdb.LoadBlockIndex())
1570 // Init with genesis block
1572 if (mapBlockIndex.empty())
1579 // GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
1580 // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
1581 // txNew.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
1582 // txNew.vout[0].nValue = 5000000000
1583 // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG
1584 // block.nVersion = 1
1585 // block.nTime = 1231006505
1586 // block.nBits = 0x1d00ffff
1587 // block.nNonce = 2083236893
1588 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1589 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1590 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1591 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1592 // vMerkleTree: 4a5e1e
1595 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1597 txNew.vin.resize(1);
1598 txNew.vout.resize(1);
1599 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1600 txNew.vout[0].nValue = 50 * COIN;
1602 bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");
1603 txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;
1605 block.vtx.push_back(txNew);
1606 block.hashPrevBlock = 0;
1607 block.hashMerkleRoot = block.BuildMerkleTree();
1609 block.nTime = 1231006505;
1610 block.nBits = 0x1d00ffff;
1611 block.nNonce = 2083236893;
1614 printf("%s\n", block.GetHash().ToString().c_str());
1615 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1616 printf("%s\n", hashGenesisBlock.ToString().c_str());
1617 txNew.vout[0].scriptPubKey.print();
1619 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1621 assert(block.GetHash() == hashGenesisBlock);
1623 // Start new block file
1625 unsigned int nBlockPos;
1626 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1627 return error("LoadBlockIndex() : writing genesis block to disk failed");
1628 if (!block.AddToBlockIndex(nFile, nBlockPos))
1629 return error("LoadBlockIndex() : genesis block not accepted");
1637 void PrintBlockTree()
1639 // precompute tree structure
1640 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1641 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1643 CBlockIndex* pindex = (*mi).second;
1644 mapNext[pindex->pprev].push_back(pindex);
1646 //while (rand() % 3 == 0)
1647 // mapNext[pindex->pprev].push_back(pindex);
1650 vector<pair<int, CBlockIndex*> > vStack;
1651 vStack.push_back(make_pair(0, pindexGenesisBlock));
1654 while (!vStack.empty())
1656 int nCol = vStack.back().first;
1657 CBlockIndex* pindex = vStack.back().second;
1660 // print split or gap
1661 if (nCol > nPrevCol)
1663 for (int i = 0; i < nCol-1; i++)
1667 else if (nCol < nPrevCol)
1669 for (int i = 0; i < nCol; i++)
1676 for (int i = 0; i < nCol; i++)
1681 block.ReadFromDisk(pindex);
1682 printf("%d (%u,%u) %s %s tx %d",
1686 block.GetHash().ToString().substr(0,16).c_str(),
1687 DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),
1690 CRITICAL_BLOCK(cs_mapWallet)
1692 if (mapWallet.count(block.vtx[0].GetHash()))
1694 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1695 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1701 // put the main timechain first
1702 vector<CBlockIndex*>& vNext = mapNext[pindex];
1703 for (int i = 0; i < vNext.size(); i++)
1705 if (vNext[i]->pnext)
1707 swap(vNext[0], vNext[i]);
1713 for (int i = 0; i < vNext.size(); i++)
1714 vStack.push_back(make_pair(nCol+i, vNext[i]));
1727 //////////////////////////////////////////////////////////////////////////////
1733 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1737 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1738 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1740 // Don't know what it is, just say we already got one
1750 bool ProcessMessages(CNode* pfrom)
1752 CDataStream& vRecv = pfrom->vRecv;
1756 // printf("ProcessMessages(%d bytes)\n", vRecv.size());
1760 // (4) message start
1769 // Scan for message start
1770 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
1771 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
1772 if (vRecv.end() - pstart < nHeaderSize)
1774 if (vRecv.size() > nHeaderSize)
1776 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
1777 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
1781 if (pstart - vRecv.begin() > 0)
1782 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
1783 vRecv.erase(vRecv.begin(), pstart);
1786 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
1791 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
1794 string strCommand = hdr.GetCommand();
1797 unsigned int nMessageSize = hdr.nMessageSize;
1798 if (nMessageSize > vRecv.size())
1800 // Rewind and wait for rest of message
1801 ///// need a mechanism to give up waiting for overlong message size error
1802 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
1806 // Copy message to its own buffer
1807 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
1808 vRecv.ignore(nMessageSize);
1811 if (vRecv.GetVersion() >= 209)
1813 uint256 hash = Hash(vMsg.begin(), vMsg.end());
1814 unsigned int nChecksum = 0;
1815 memcpy(&nChecksum, &hash, sizeof(nChecksum));
1816 if (nChecksum != hdr.nChecksum)
1818 printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
1819 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
1828 CRITICAL_BLOCK(cs_main)
1829 fRet = ProcessMessage(pfrom, strCommand, vMsg);
1833 catch (std::ios_base::failure& e)
1835 if (strstr(e.what(), "CDataStream::read() : end of data"))
1837 // Allow exceptions from underlength message on vRecv
1838 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());
1840 else if (strstr(e.what(), ": size too large"))
1842 // Allow exceptions from overlong size
1843 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
1847 PrintException(&e, "ProcessMessage()");
1850 catch (std::exception& e) {
1851 PrintException(&e, "ProcessMessage()");
1853 PrintException(NULL, "ProcessMessage()");
1857 printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);
1867 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1869 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1870 RandAddSeedPerfmon();
1872 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1873 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1874 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1876 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1884 if (strCommand == "version")
1886 // Each connection can only send one version message
1887 if (pfrom->nVersion != 0)
1895 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1896 if (pfrom->nVersion == 10300)
1897 pfrom->nVersion = 300;
1898 if (pfrom->nVersion >= 106 && !vRecv.empty())
1899 vRecv >> addrFrom >> nNonce;
1900 if (pfrom->nVersion >= 106 && !vRecv.empty())
1902 if (pfrom->nVersion >= 209 && !vRecv.empty())
1903 vRecv >> pfrom->nStartingHeight;
1905 if (pfrom->nVersion == 0)
1908 // Disconnect if we connected to ourself
1909 if (nNonce == nLocalHostNonce && nNonce > 1)
1911 pfrom->fDisconnect = true;
1915 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1918 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
1919 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
1922 AddTimeData(pfrom->addr.ip, nTime);
1925 if (pfrom->nVersion >= 209)
1926 pfrom->PushMessage("verack");
1927 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1928 if (pfrom->nVersion < 209)
1929 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1931 // Ask the first connected node for block updates
1932 static int nAskedForBlocks;
1933 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1936 pfrom->PushGetBlocks(pindexBest, uint256(0));
1939 pfrom->fSuccessfullyConnected = true;
1941 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1945 else if (pfrom->nVersion == 0)
1947 // Must have a version message before anything else
1952 else if (strCommand == "verack")
1954 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1958 else if (strCommand == "addr")
1960 vector<CAddress> vAddr;
1962 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
1964 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
1966 if (vAddr.size() > 1000)
1967 return error("message addr size() = %d", vAddr.size());
1969 // Store the new addresses
1970 foreach(CAddress& addr, vAddr)
1974 // ignore IPv6 for now, since it isn't implemented anyway
1977 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
1978 if (pfrom->fGetAddr || vAddr.size() > 10)
1979 addr.nTime -= 5 * 24 * 60 * 60;
1981 pfrom->AddAddressKnown(addr);
1982 if (!pfrom->fGetAddr && addr.IsRoutable())
1984 // Relay to a limited number of other nodes
1985 CRITICAL_BLOCK(cs_vNodes)
1987 // Use deterministic randomness to send to
1988 // the same places for 12 hours at a time
1989 static uint256 hashSalt;
1991 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1992 uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
1993 multimap<uint256, CNode*> mapMix;
1994 foreach(CNode* pnode, vNodes)
1995 mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
1996 int nRelayNodes = 4;
1997 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1998 ((*mi).second)->PushAddress(addr);
2002 if (vAddr.size() < 1000)
2003 pfrom->fGetAddr = false;
2007 else if (strCommand == "inv")
2011 if (vInv.size() > 50000)
2012 return error("message inv size() = %d", vInv.size());
2015 foreach(const CInv& inv, vInv)
2019 pfrom->AddInventoryKnown(inv);
2021 bool fAlreadyHave = AlreadyHave(txdb, inv);
2022 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2026 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2027 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2029 // Track requests for our stuff
2030 CRITICAL_BLOCK(cs_mapRequestCount)
2032 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2033 if (mi != mapRequestCount.end())
2040 else if (strCommand == "getdata")
2044 if (vInv.size() > 50000)
2045 return error("message getdata size() = %d", vInv.size());
2047 foreach(const CInv& inv, vInv)
2051 printf("received getdata for: %s\n", inv.ToString().c_str());
2053 if (inv.type == MSG_BLOCK)
2055 // Send block from disk
2056 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2057 if (mi != mapBlockIndex.end())
2059 //// could optimize this to send header straight from blockindex for client
2061 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2062 pfrom->PushMessage("block", block);
2064 // Trigger them to send a getblocks request for the next batch of inventory
2065 if (inv.hash == pfrom->hashContinue)
2067 // Bypass PushInventory, this must send even if redundant,
2068 // and we want it right after the last block so they don't
2069 // wait for other stuff first.
2071 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2072 pfrom->PushMessage("inv", vInv);
2073 pfrom->hashContinue = 0;
2077 else if (inv.IsKnownType())
2079 // Send stream from relay memory
2080 CRITICAL_BLOCK(cs_mapRelay)
2082 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2083 if (mi != mapRelay.end())
2084 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2088 // Track requests for our stuff
2089 CRITICAL_BLOCK(cs_mapRequestCount)
2091 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2092 if (mi != mapRequestCount.end())
2099 else if (strCommand == "getblocks")
2101 CBlockLocator locator;
2103 vRecv >> locator >> hashStop;
2105 // Find the first block the caller has in the main chain
2106 CBlockIndex* pindex = locator.GetBlockIndex();
2108 // Send the rest of the chain
2110 pindex = pindex->pnext;
2111 int nLimit = 500 + locator.GetDistanceBack();
2112 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);
2113 for (; pindex; pindex = pindex->pnext)
2115 if (pindex->GetBlockHash() == hashStop)
2117 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2120 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2123 // When this block is requested, we'll send an inv that'll make them
2124 // getblocks the next batch of inventory.
2125 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2126 pfrom->hashContinue = pindex->GetBlockHash();
2133 else if (strCommand == "tx")
2135 vector<uint256> vWorkQueue;
2136 CDataStream vMsg(vRecv);
2140 CInv inv(MSG_TX, tx.GetHash());
2141 pfrom->AddInventoryKnown(inv);
2143 bool fMissingInputs = false;
2144 if (tx.AcceptTransaction(true, &fMissingInputs))
2146 AddToWalletIfMine(tx, NULL);
2147 RelayMessage(inv, vMsg);
2148 mapAlreadyAskedFor.erase(inv);
2149 vWorkQueue.push_back(inv.hash);
2151 // Recursively process any orphan transactions that depended on this one
2152 for (int i = 0; i < vWorkQueue.size(); i++)
2154 uint256 hashPrev = vWorkQueue[i];
2155 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2156 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2159 const CDataStream& vMsg = *((*mi).second);
2161 CDataStream(vMsg) >> tx;
2162 CInv inv(MSG_TX, tx.GetHash());
2164 if (tx.AcceptTransaction(true))
2166 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2167 AddToWalletIfMine(tx, NULL);
2168 RelayMessage(inv, vMsg);
2169 mapAlreadyAskedFor.erase(inv);
2170 vWorkQueue.push_back(inv.hash);
2175 foreach(uint256 hash, vWorkQueue)
2176 EraseOrphanTx(hash);
2178 else if (fMissingInputs)
2180 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2186 else if (strCommand == "block")
2188 auto_ptr<CBlock> pblock(new CBlock);
2192 printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());
2195 CInv inv(MSG_BLOCK, pblock->GetHash());
2196 pfrom->AddInventoryKnown(inv);
2198 if (ProcessBlock(pfrom, pblock.release()))
2199 mapAlreadyAskedFor.erase(inv);
2203 else if (strCommand == "getaddr")
2205 // This includes all nodes that are currently online,
2206 // since they rebroadcast an addr every 24 hours
2207 pfrom->vAddrToSend.clear();
2208 int64 nSince = GetAdjustedTime() - 24 * 60 * 60; // in the last 24 hours
2209 CRITICAL_BLOCK(cs_mapAddresses)
2211 unsigned int nSize = mapAddresses.size();
2212 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2216 const CAddress& addr = item.second;
2217 if (addr.nTime > nSince)
2218 pfrom->PushAddress(addr);
2224 else if (strCommand == "checkorder")
2228 vRecv >> hashReply >> order;
2230 /// we have a chance to check the order here
2232 // Keep giving the same key to the same ip until they use it
2233 if (!mapReuseKey.count(pfrom->addr.ip))
2234 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
2236 // Send back approval of order and pubkey to use
2237 CScript scriptPubKey;
2238 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2239 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2243 else if (strCommand == "submitorder")
2247 vRecv >> hashReply >> wtxNew;
2248 wtxNew.fFromMe = false;
2251 if (!wtxNew.AcceptWalletTransaction())
2253 pfrom->PushMessage("reply", hashReply, (int)1);
2254 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2256 wtxNew.fTimeReceivedIsTxTime = true;
2257 AddToWallet(wtxNew);
2258 wtxNew.RelayWalletTransaction();
2259 mapReuseKey.erase(pfrom->addr.ip);
2261 // Send back confirmation
2262 pfrom->PushMessage("reply", hashReply, (int)0);
2266 else if (strCommand == "reply")
2271 CRequestTracker tracker;
2272 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2274 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2275 if (mi != pfrom->mapRequests.end())
2277 tracker = (*mi).second;
2278 pfrom->mapRequests.erase(mi);
2281 if (!tracker.IsNull())
2282 tracker.fn(tracker.param1, vRecv);
2286 else if (strCommand == "ping")
2293 // Ignore unknown commands for extensibility
2297 // Update the last seen time for this node's address
2298 if (pfrom->fNetworkNode)
2299 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2300 AddressCurrentlyConnected(pfrom->addr);
2314 bool SendMessages(CNode* pto, bool fSendTrickle)
2316 CRITICAL_BLOCK(cs_main)
2318 // Don't send anything until we get their version message
2319 if (pto->nVersion == 0)
2323 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2324 pto->PushMessage("ping");
2326 // Address refresh broadcast
2327 static int64 nLastRebroadcast;
2328 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2330 nLastRebroadcast = GetTime();
2331 CRITICAL_BLOCK(cs_vNodes)
2333 foreach(CNode* pnode, vNodes)
2335 // Periodically clear setAddrKnown to allow refresh broadcasts
2336 pnode->setAddrKnown.clear();
2338 // Rebroadcast our address
2339 if (addrLocalHost.IsRoutable() && !fUseProxy)
2340 pnode->PushAddress(addrLocalHost);
2345 // Resend wallet transactions that haven't gotten in a block yet
2346 ResendWalletTransactions();
2354 vector<CAddress> vAddr;
2355 vAddr.reserve(pto->vAddrToSend.size());
2356 foreach(const CAddress& addr, pto->vAddrToSend)
2358 // returns true if wasn't already contained in the set
2359 if (pto->setAddrKnown.insert(addr).second)
2361 vAddr.push_back(addr);
2362 // receiver rejects addr messages larger than 1000
2363 if (vAddr.size() >= 1000)
2365 pto->PushMessage("addr", vAddr);
2370 pto->vAddrToSend.clear();
2372 pto->PushMessage("addr", vAddr);
2377 // Message: inventory
2380 vector<CInv> vInvWait;
2381 CRITICAL_BLOCK(pto->cs_inventory)
2383 vInv.reserve(pto->vInventoryToSend.size());
2384 vInvWait.reserve(pto->vInventoryToSend.size());
2385 foreach(const CInv& inv, pto->vInventoryToSend)
2387 if (pto->setInventoryKnown.count(inv))
2390 // trickle out tx inv to protect privacy
2391 if (inv.type == MSG_TX && !fSendTrickle)
2393 // 1/4 of tx invs blast to all immediately
2394 static uint256 hashSalt;
2396 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2397 uint256 hashRand = inv.hash ^ hashSalt;
2398 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2399 bool fTrickleWait = ((hashRand & 3) != 0);
2401 // always trickle our own transactions
2404 TRY_CRITICAL_BLOCK(cs_mapWallet)
2406 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2407 if (mi != mapWallet.end())
2409 CWalletTx& wtx = (*mi).second;
2411 fTrickleWait = true;
2418 vInvWait.push_back(inv);
2423 // returns true if wasn't already contained in the set
2424 if (pto->setInventoryKnown.insert(inv).second)
2426 vInv.push_back(inv);
2427 if (vInv.size() >= 1000)
2429 pto->PushMessage("inv", vInv);
2434 pto->vInventoryToSend = vInvWait;
2437 pto->PushMessage("inv", vInv);
2443 vector<CInv> vGetData;
2444 int64 nNow = GetTime() * 1000000;
2446 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2448 const CInv& inv = (*pto->mapAskFor.begin()).second;
2449 if (!AlreadyHave(txdb, inv))
2451 printf("sending getdata: %s\n", inv.ToString().c_str());
2452 vGetData.push_back(inv);
2453 if (vGetData.size() >= 1000)
2455 pto->PushMessage("getdata", vGetData);
2459 pto->mapAskFor.erase(pto->mapAskFor.begin());
2461 if (!vGetData.empty())
2462 pto->PushMessage("getdata", vGetData);
2481 //////////////////////////////////////////////////////////////////////////////
2486 void GenerateBitcoins(bool fGenerate)
2488 if (fGenerateBitcoins != fGenerate)
2490 fGenerateBitcoins = fGenerate;
2491 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2494 if (fGenerateBitcoins)
2496 int nProcessors = boost::thread::hardware_concurrency();
2497 printf("%d processors\n", nProcessors);
2498 if (nProcessors < 1)
2500 if (fLimitProcessors && nProcessors > nLimitProcessors)
2501 nProcessors = nLimitProcessors;
2502 int nAddThreads = nProcessors - vnThreadsRunning[3];
2503 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2504 for (int i = 0; i < nAddThreads; i++)
2506 if (!CreateThread(ThreadBitcoinMiner, NULL))
2507 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2513 void ThreadBitcoinMiner(void* parg)
2517 vnThreadsRunning[3]++;
2519 vnThreadsRunning[3]--;
2521 catch (std::exception& e) {
2522 vnThreadsRunning[3]--;
2523 PrintException(&e, "ThreadBitcoinMiner()");
2525 vnThreadsRunning[3]--;
2526 PrintException(NULL, "ThreadBitcoinMiner()");
2528 UIThreadCall(bind(CalledSetStatusBar, "", 0));
2529 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2532 int FormatHashBlocks(void* pbuffer, unsigned int len)
2534 unsigned char* pdata = (unsigned char*)pbuffer;
2535 unsigned int blocks = 1 + ((len + 8) / 64);
2536 unsigned char* pend = pdata + 64 * blocks;
2537 memset(pdata + len, 0, 64 * blocks - len);
2539 unsigned int bits = len * 8;
2540 pend[-1] = (bits >> 0) & 0xff;
2541 pend[-2] = (bits >> 8) & 0xff;
2542 pend[-3] = (bits >> 16) & 0xff;
2543 pend[-4] = (bits >> 24) & 0xff;
2547 using CryptoPP::ByteReverse;
2549 static const unsigned int pSHA256InitState[8] =
2550 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2552 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2554 memcpy(pstate, pinit, 32);
2555 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2564 printf("BitcoinMiner started\n");
2565 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2569 CBigNum bnExtraNonce = 0;
2570 while (fGenerateBitcoins)
2575 while (vNodes.empty() || IsInitialBlockDownload())
2580 if (!fGenerateBitcoins)
2584 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2585 CBlockIndex* pindexPrev = pindexBest;
2586 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2590 // Create coinbase tx
2593 txNew.vin.resize(1);
2594 txNew.vin[0].prevout.SetNull();
2595 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
2596 txNew.vout.resize(1);
2597 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
2603 auto_ptr<CBlock> pblock(new CBlock());
2607 // Add our coinbase tx as first transaction
2608 pblock->vtx.push_back(txNew);
2610 // Collect the latest transactions into the block
2612 CRITICAL_BLOCK(cs_main)
2613 CRITICAL_BLOCK(cs_mapTransactions)
2616 map<uint256, CTxIndex> mapTestPool;
2617 vector<char> vfAlreadyAdded(mapTransactions.size());
2618 bool fFoundSomething = true;
2619 unsigned int nBlockSize = 0;
2620 while (fFoundSomething && nBlockSize < MAX_SIZE/2)
2622 fFoundSomething = false;
2624 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
2626 if (vfAlreadyAdded[n])
2628 CTransaction& tx = (*mi).second;
2629 if (tx.IsCoinBase() || !tx.IsFinal())
2631 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2632 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)
2635 // Transaction fee based on block size
2636 int64 nMinFee = tx.GetMinFee(nBlockSize);
2638 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2639 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))
2641 swap(mapTestPool, mapTestPoolTmp);
2643 pblock->vtx.push_back(tx);
2644 nBlockSize += nTxSize;
2645 vfAlreadyAdded[n] = true;
2646 fFoundSomething = true;
2650 pblock->nBits = nBits;
2651 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);
2652 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2656 // Prebuild hash buffer
2663 uint256 hashPrevBlock;
2664 uint256 hashMerkleRoot;
2667 unsigned int nNonce;
2670 unsigned char pchPadding0[64];
2672 unsigned char pchPadding1[64];
2674 char tmpbuf[sizeof(tmpworkspace)+16];
2675 tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
2677 tmp.block.nVersion = pblock->nVersion;
2678 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
2679 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2680 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
2681 tmp.block.nBits = pblock->nBits = nBits;
2682 tmp.block.nNonce = pblock->nNonce = 0;
2684 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2685 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2687 // Byte swap all the input buffer
2688 for (int i = 0; i < sizeof(tmp)/4; i++)
2689 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2691 // Precalc the first half of the first hash, which stays constant
2692 uint256 midstatebuf[2];
2693 uint256& midstate = *alignup<16>(midstatebuf);
2694 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
2700 int64 nStart = GetTime();
2701 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2703 uint256& hash = *alignup<16>(hashbuf);
2706 SHA256Transform(&tmp.hash1, (char*)&tmp.block + 64, &midstate);
2707 SHA256Transform(&hash, &tmp.hash1, pSHA256InitState);
2709 if (((unsigned short*)&hash)[14] == 0)
2711 // Byte swap the result after preliminary check
2712 for (int i = 0; i < sizeof(hash)/4; i++)
2713 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
2715 if (hash <= hashTarget)
2717 pblock->nNonce = ByteReverse(tmp.block.nNonce);
2718 assert(hash == pblock->GetHash());
2721 printf("BitcoinMiner:\n");
2722 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2724 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2725 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2727 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2728 CRITICAL_BLOCK(cs_main)
2730 if (pindexPrev == pindexBest)
2737 // Track how many getdata requests this block gets
2738 CRITICAL_BLOCK(cs_mapRequestCount)
2739 mapRequestCount[pblock->GetHash()] = 0;
2741 // Process this block the same as if we had received it from another node
2742 if (!ProcessBlock(NULL, pblock.release()))
2743 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
2746 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2753 // Update nTime every few seconds
2754 const unsigned int nMask = 0xffff;
2755 if ((++tmp.block.nNonce & nMask) == 0)
2758 static int64 nTimerStart;
2759 static int nHashCounter;
2760 if (nTimerStart == 0)
2761 nTimerStart = GetTimeMillis();
2764 if (GetTimeMillis() - nTimerStart > 4000)
2766 static CCriticalSection cs;
2769 if (GetTimeMillis() - nTimerStart > 4000)
2771 double dHashesPerSec = 1000.0 * (nMask+1) * nHashCounter / (GetTimeMillis() - nTimerStart);
2772 nTimerStart = GetTimeMillis();
2774 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
2775 UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));
2776 static int64 nLogTime;
2777 if (GetTime() - nLogTime > 30 * 60)
2779 nLogTime = GetTime();
2780 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2781 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
2787 // Check for stop or if block needs to be rebuilt
2790 if (!fGenerateBitcoins)
2792 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
2796 if (tmp.block.nNonce == 0)
2798 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2800 if (pindexPrev != pindexBest)
2803 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2804 tmp.block.nTime = ByteReverse(pblock->nTime);
2827 //////////////////////////////////////////////////////////////////////////////
2835 int64 nStart = GetTimeMillis();
2838 CRITICAL_BLOCK(cs_mapWallet)
2840 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2842 CWalletTx* pcoin = &(*it).second;
2843 if (!pcoin->IsFinal() || pcoin->fSpent)
2845 nTotal += pcoin->GetCredit(true);
2849 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
2854 int GetRandInt(int nMax)
2856 return GetRand(nMax);
2859 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
2861 setCoinsRet.clear();
2863 // List of values less than target
2864 int64 nLowestLarger = INT64_MAX;
2865 CWalletTx* pcoinLowestLarger = NULL;
2866 vector<pair<int64, CWalletTx*> > vValue;
2867 int64 nTotalLower = 0;
2869 CRITICAL_BLOCK(cs_mapWallet)
2871 vector<CWalletTx*> vCoins;
2872 vCoins.reserve(mapWallet.size());
2873 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2874 vCoins.push_back(&(*it).second);
2875 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2877 foreach(CWalletTx* pcoin, vCoins)
2879 if (!pcoin->IsFinal() || pcoin->fSpent)
2881 int64 n = pcoin->GetCredit();
2884 if (n < nTargetValue)
2886 vValue.push_back(make_pair(n, pcoin));
2889 else if (n == nTargetValue)
2891 setCoinsRet.insert(pcoin);
2894 else if (n < nLowestLarger)
2897 pcoinLowestLarger = pcoin;
2902 if (nTotalLower < nTargetValue)
2904 if (pcoinLowestLarger == NULL)
2906 setCoinsRet.insert(pcoinLowestLarger);
2910 // Solve subset sum by stochastic approximation
2911 sort(vValue.rbegin(), vValue.rend());
2912 vector<char> vfIncluded;
2913 vector<char> vfBest(vValue.size(), true);
2914 int64 nBest = nTotalLower;
2916 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
2918 vfIncluded.assign(vValue.size(), false);
2920 bool fReachedTarget = false;
2921 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2923 for (int i = 0; i < vValue.size(); i++)
2925 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
2927 nTotal += vValue[i].first;
2928 vfIncluded[i] = true;
2929 if (nTotal >= nTargetValue)
2931 fReachedTarget = true;
2935 vfBest = vfIncluded;
2937 nTotal -= vValue[i].first;
2938 vfIncluded[i] = false;
2945 // If the next larger is still closer, return it
2946 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
2947 setCoinsRet.insert(pcoinLowestLarger);
2950 for (int i = 0; i < vValue.size(); i++)
2952 setCoinsRet.insert(vValue[i].second);
2955 printf("SelectCoins() best subset: ");
2956 for (int i = 0; i < vValue.size(); i++)
2958 printf("%s ", FormatMoney(vValue[i].first).c_str());
2959 printf("total %s\n", FormatMoney(nBest).c_str());
2968 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
2970 nFeeRequiredRet = 0;
2971 CRITICAL_BLOCK(cs_main)
2973 // txdb must be opened before the mapWallet lock
2975 CRITICAL_BLOCK(cs_mapWallet)
2977 int64 nFee = nTransactionFee;
2981 wtxNew.vout.clear();
2982 wtxNew.fFromMe = true;
2985 int64 nValueOut = nValue;
2986 int64 nTotalValue = nValue + nFee;
2988 // Choose coins to use
2989 set<CWalletTx*> setCoins;
2990 if (!SelectCoins(nTotalValue, setCoins))
2993 foreach(CWalletTx* pcoin, setCoins)
2994 nValueIn += pcoin->GetCredit();
2996 // Fill a vout to the payee
2997 bool fChangeFirst = GetRand(2);
2999 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3001 // Fill a vout back to self with any change
3002 if (nValueIn > nTotalValue)
3004 // Note: We use a new key here to keep it from being obvious which side is the change.
3005 // The drawback is that by not reusing a previous key, the change may be lost if a
3006 // backup is restored, if the backup doesn't have the new private key for the change.
3007 // If we reused the old key, it would be possible to add code to look for and
3008 // rediscover unknown transactions that were written with keys of ours to recover
3009 // post-backup change.
3012 if (keyRet.IsNull())
3013 keyRet.MakeNewKey();
3015 // Fill a vout to ourself, using same address type as the payment
3016 CScript scriptChange;
3017 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3018 scriptChange.SetBitcoinAddress(keyRet.GetPubKey());
3020 scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;
3021 wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));
3024 // Fill a vout to the payee
3026 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3029 foreach(CWalletTx* pcoin, setCoins)
3030 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3031 if (pcoin->vout[nOut].IsMine())
3032 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3036 foreach(CWalletTx* pcoin, setCoins)
3037 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3038 if (pcoin->vout[nOut].IsMine())
3039 SignSignature(*pcoin, wtxNew, nIn++);
3041 // Check that enough fee is included
3042 if (nFee < wtxNew.GetMinFee())
3044 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3048 // Fill vtxPrev by copying from previous transactions vtxPrev
3049 wtxNew.AddSupportingTransactions(txdb);
3050 wtxNew.fTimeReceivedIsTxTime = true;
3059 // Call after CreateTransaction unless you want to abort
3060 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)
3062 CRITICAL_BLOCK(cs_main)
3064 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3065 CRITICAL_BLOCK(cs_mapWallet)
3067 // This is only to keep the database open to defeat the auto-flush for the
3068 // duration of this scope. This is the only place where this optimization
3069 // maybe makes sense; please don't do it anywhere else.
3070 CWalletDB walletdb("r");
3072 // Add the change's private key to wallet
3073 if (!key.IsNull() && !AddKey(key))
3074 throw runtime_error("CommitTransaction() : AddKey failed\n");
3076 // Add tx to wallet, because if it has change it's also ours,
3077 // otherwise just for transaction history.
3078 AddToWallet(wtxNew);
3080 // Mark old coins as spent
3081 set<CWalletTx*> setCoins;
3082 foreach(const CTxIn& txin, wtxNew.vin)
3083 setCoins.insert(&mapWallet[txin.prevout.hash]);
3084 foreach(CWalletTx* pcoin, setCoins)
3086 pcoin->fSpent = true;
3087 pcoin->WriteToDisk();
3088 vWalletUpdated.push_back(pcoin->GetHash());
3092 // Track how many getdata requests our transaction gets
3093 CRITICAL_BLOCK(cs_mapRequestCount)
3094 mapRequestCount[wtxNew.GetHash()] = 0;
3097 if (!wtxNew.AcceptTransaction())
3099 // This must not fail. The transaction has already been signed and recorded.
3100 printf("CommitTransaction() : Error: Transaction not valid");
3103 wtxNew.RelayWalletTransaction();
3112 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3114 CRITICAL_BLOCK(cs_main)
3118 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
3121 if (nValue + nFeeRequired > GetBalance())
3122 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3124 strError = _("Error: Transaction creation failed ");
3125 printf("SendMoney() : %s", strError.c_str());
3129 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3132 if (!CommitTransaction(wtxNew, key))
3133 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.");
3141 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3145 return _("Invalid amount");
3146 if (nValue + nTransactionFee > GetBalance())
3147 return _("Insufficient funds");
3149 // Parse bitcoin address
3150 CScript scriptPubKey;
3151 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3152 return _("Invalid bitcoin address");
3154 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);