1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "cryptopp/sha.h"
16 CCriticalSection cs_main;
18 map<uint256, CTransaction> mapTransactions;
19 CCriticalSection cs_mapTransactions;
20 unsigned int nTransactionsUpdated = 0;
21 map<COutPoint, CInPoint> mapNextTx;
23 map<uint256, CBlockIndex*> mapBlockIndex;
24 const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
25 CBlockIndex* pindexGenesisBlock = NULL;
27 CBigNum bnBestChainWork = 0;
28 CBigNum bnBestInvalidWork = 0;
29 uint256 hashBestChain = 0;
30 CBlockIndex* pindexBest = NULL;
31 int64 nTimeBestReceived = 0;
33 map<uint256, CBlock*> mapOrphanBlocks;
34 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
36 map<uint256, CDataStream*> mapOrphanTransactions;
37 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
39 map<uint256, CWalletTx> mapWallet;
40 vector<uint256> vWalletUpdated;
41 CCriticalSection cs_mapWallet;
43 map<vector<unsigned char>, CPrivKey> mapKeys;
44 map<uint160, vector<unsigned char> > mapPubKeys;
45 CCriticalSection cs_mapKeys;
48 map<uint256, int> mapRequestCount;
49 CCriticalSection cs_mapRequestCount;
51 map<string, string> mapAddressBook;
52 CCriticalSection cs_mapAddressBook;
54 vector<unsigned char> vchDefaultKey;
60 int fGenerateBitcoins = false;
61 int64 nTransactionFee = 0;
62 CAddress addrIncoming;
63 int fLimitProcessors = false;
64 int nLimitProcessors = 1;
65 int fMinimizeToTray = true;
66 int fMinimizeOnClose = true;
73 //////////////////////////////////////////////////////////////////////////////
78 bool AddKey(const CKey& key)
80 CRITICAL_BLOCK(cs_mapKeys)
82 mapKeys[key.GetPubKey()] = key.GetPrivKey();
83 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
85 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
88 vector<unsigned char> GenerateNewKey()
94 throw runtime_error("GenerateNewKey() : AddKey failed\n");
95 return key.GetPubKey();
101 //////////////////////////////////////////////////////////////////////////////
106 bool AddToWallet(const CWalletTx& wtxIn)
108 uint256 hash = wtxIn.GetHash();
109 CRITICAL_BLOCK(cs_mapWallet)
111 // Inserts only if not already there, returns tx inserted or tx found
112 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
113 CWalletTx& wtx = (*ret.first).second;
114 bool fInsertedNew = ret.second;
116 wtx.nTimeReceived = GetAdjustedTime();
118 bool fUpdated = false;
122 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
124 wtx.hashBlock = wtxIn.hashBlock;
127 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
129 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
130 wtx.nIndex = wtxIn.nIndex;
133 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
135 wtx.fFromMe = wtxIn.fFromMe;
138 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
140 wtx.fSpent = wtxIn.fSpent;
146 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
149 if (fInsertedNew || fUpdated)
150 if (!wtx.WriteToDisk())
153 // If default receiving address gets used, replace it with a new one
154 CScript scriptDefaultKey;
155 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
156 foreach(const CTxOut& txout, wtx.vout)
158 if (txout.scriptPubKey == scriptDefaultKey)
161 walletdb.WriteDefaultKey(GenerateNewKey());
162 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
167 vWalletUpdated.push_back(hash);
175 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
177 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
180 // Get merkle branch if transaction was found in a block
182 wtx.SetMerkleBranch(pblock);
183 return AddToWallet(wtx);
188 bool EraseFromWallet(uint256 hash)
190 CRITICAL_BLOCK(cs_mapWallet)
192 if (mapWallet.erase(hash))
193 CWalletDB().EraseTx(hash);
198 void WalletUpdateSpent(const COutPoint& prevout)
200 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
201 // Update the wallet spent flag if it doesn't know due to wallet.dat being
202 // restored from backup or the user making copies of wallet.dat.
203 CRITICAL_BLOCK(cs_mapWallet)
205 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
206 if (mi != mapWallet.end())
208 CWalletTx& wtx = (*mi).second;
209 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
211 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
214 vWalletUpdated.push_back(prevout.hash);
227 //////////////////////////////////////////////////////////////////////////////
229 // mapOrphanTransactions
232 void AddOrphanTx(const CDataStream& vMsg)
235 CDataStream(vMsg) >> tx;
236 uint256 hash = tx.GetHash();
237 if (mapOrphanTransactions.count(hash))
239 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
240 foreach(const CTxIn& txin, tx.vin)
241 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
244 void EraseOrphanTx(uint256 hash)
246 if (!mapOrphanTransactions.count(hash))
248 const CDataStream* pvMsg = mapOrphanTransactions[hash];
250 CDataStream(*pvMsg) >> tx;
251 foreach(const CTxIn& txin, tx.vin)
253 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
254 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
256 if ((*mi).second == pvMsg)
257 mapOrphanTransactionsByPrev.erase(mi++);
263 mapOrphanTransactions.erase(hash);
273 //////////////////////////////////////////////////////////////////////////////
278 bool CTxIn::IsMine() const
280 CRITICAL_BLOCK(cs_mapWallet)
282 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
283 if (mi != mapWallet.end())
285 const CWalletTx& prev = (*mi).second;
286 if (prevout.n < prev.vout.size())
287 if (prev.vout[prevout.n].IsMine())
294 int64 CTxIn::GetDebit() const
296 CRITICAL_BLOCK(cs_mapWallet)
298 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
299 if (mi != mapWallet.end())
301 const CWalletTx& prev = (*mi).second;
302 if (prevout.n < prev.vout.size())
303 if (prev.vout[prevout.n].IsMine())
304 return prev.vout[prevout.n].nValue;
310 int64 CWalletTx::GetTxTime() const
312 if (!fTimeReceivedIsTxTime && hashBlock != 0)
314 // If we did not receive the transaction directly, we rely on the block's
315 // time to figure out when it happened. We use the median over a range
316 // of blocks to try to filter out inaccurate block times.
317 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
318 if (mi != mapBlockIndex.end())
320 CBlockIndex* pindex = (*mi).second;
322 return pindex->GetMedianTime();
325 return nTimeReceived;
328 int CWalletTx::GetRequestCount() const
330 // Returns -1 if it wasn't being tracked
332 CRITICAL_BLOCK(cs_mapRequestCount)
339 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
340 if (mi != mapRequestCount.end())
341 nRequests = (*mi).second;
346 // Did anyone request this transaction?
347 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
348 if (mi != mapRequestCount.end())
350 nRequests = (*mi).second;
352 // How about the block it's in?
353 if (nRequests == 0 && hashBlock != 0)
355 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
356 if (mi != mapRequestCount.end())
357 nRequests = (*mi).second;
359 nRequests = 1; // If it's in someone else's block it must have got out
370 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
382 // Load the block this tx is in
384 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
386 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
391 // Update the tx's hashBlock
392 hashBlock = pblock->GetHash();
394 // Locate the transaction
395 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
396 if (pblock->vtx[nIndex] == *(CTransaction*)this)
398 if (nIndex == pblock->vtx.size())
400 vMerkleBranch.clear();
402 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
406 // Fill in merkle branch
407 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
410 // Is the tx in a block that's in the main chain
411 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
412 if (mi == mapBlockIndex.end())
414 CBlockIndex* pindex = (*mi).second;
415 if (!pindex || !pindex->IsInMainChain())
418 return pindexBest->nHeight - pindex->nHeight + 1;
423 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
427 const int COPY_DEPTH = 3;
428 if (SetMerkleBranch() < COPY_DEPTH)
430 vector<uint256> vWorkQueue;
431 foreach(const CTxIn& txin, vin)
432 vWorkQueue.push_back(txin.prevout.hash);
434 // This critsect is OK because txdb is already open
435 CRITICAL_BLOCK(cs_mapWallet)
437 map<uint256, const CMerkleTx*> mapWalletPrev;
438 set<uint256> setAlreadyDone;
439 for (int i = 0; i < vWorkQueue.size(); i++)
441 uint256 hash = vWorkQueue[i];
442 if (setAlreadyDone.count(hash))
444 setAlreadyDone.insert(hash);
447 if (mapWallet.count(hash))
449 tx = mapWallet[hash];
450 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
451 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
453 else if (mapWalletPrev.count(hash))
455 tx = *mapWalletPrev[hash];
457 else if (!fClient && txdb.ReadDiskTx(hash, tx))
463 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
467 int nDepth = tx.SetMerkleBranch();
468 vtxPrev.push_back(tx);
470 if (nDepth < COPY_DEPTH)
471 foreach(const CTxIn& txin, tx.vin)
472 vWorkQueue.push_back(txin.prevout.hash);
477 reverse(vtxPrev.begin(), vtxPrev.end());
490 bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
493 *pfMissingInputs = false;
495 // Coinbase is only valid in a block, not as a loose transaction
497 return error("AcceptTransaction() : coinbase as individual tx");
499 if (!CheckTransaction())
500 return error("AcceptTransaction() : CheckTransaction failed");
502 // To help v0.1.5 clients who would see it as a negative number
503 if (nLockTime > INT_MAX)
504 return error("AcceptTransaction() : not accepting nLockTime beyond 2038");
506 // Do we already have it?
507 uint256 hash = GetHash();
508 CRITICAL_BLOCK(cs_mapTransactions)
509 if (mapTransactions.count(hash))
512 if (txdb.ContainsTx(hash))
515 // Check for conflicts with in-memory transactions
516 CTransaction* ptxOld = NULL;
517 for (int i = 0; i < vin.size(); i++)
519 COutPoint outpoint = vin[i].prevout;
520 if (mapNextTx.count(outpoint))
522 // Allow replacing with a newer version of the same transaction
525 ptxOld = mapNextTx[outpoint].ptx;
526 if (!IsNewerThan(*ptxOld))
528 for (int i = 0; i < vin.size(); i++)
530 COutPoint outpoint = vin[i].prevout;
531 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
538 // Check against previous transactions
539 map<uint256, CTxIndex> mapUnused;
541 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
544 *pfMissingInputs = true;
545 return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());
548 // Store transaction in memory
549 CRITICAL_BLOCK(cs_mapTransactions)
553 printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());
554 mapTransactions.erase(ptxOld->GetHash());
559 ///// are we sure this is ok when loading transactions or restoring block txes
560 // If updated, erase old tx from wallet
562 EraseFromWallet(ptxOld->GetHash());
564 printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());
569 bool CTransaction::AddToMemoryPool()
571 // Add to memory pool without checking anything. Don't call this directly,
572 // call AcceptTransaction to properly check the transaction first.
573 CRITICAL_BLOCK(cs_mapTransactions)
575 uint256 hash = GetHash();
576 mapTransactions[hash] = *this;
577 for (int i = 0; i < vin.size(); i++)
578 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
579 nTransactionsUpdated++;
585 bool CTransaction::RemoveFromMemoryPool()
587 // Remove transaction from memory pool
588 CRITICAL_BLOCK(cs_mapTransactions)
590 foreach(const CTxIn& txin, vin)
591 mapNextTx.erase(txin.prevout);
592 mapTransactions.erase(GetHash());
593 nTransactionsUpdated++;
603 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
605 if (hashBlock == 0 || nIndex == -1)
608 // Find the block it claims to be in
609 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
610 if (mi == mapBlockIndex.end())
612 CBlockIndex* pindex = (*mi).second;
613 if (!pindex || !pindex->IsInMainChain())
616 // Make sure the merkle branch connects to this block
617 if (!fMerkleVerified)
619 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
621 fMerkleVerified = true;
624 nHeightRet = pindex->nHeight;
625 return pindexBest->nHeight - pindex->nHeight + 1;
629 int CMerkleTx::GetBlocksToMaturity() const
633 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
637 bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
641 if (!IsInMainChain() && !ClientConnectInputs())
643 return CTransaction::AcceptTransaction(txdb, false);
647 return CTransaction::AcceptTransaction(txdb, fCheckInputs);
653 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
655 CRITICAL_BLOCK(cs_mapTransactions)
657 foreach(CMerkleTx& tx, vtxPrev)
659 if (!tx.IsCoinBase())
661 uint256 hash = tx.GetHash();
662 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
663 tx.AcceptTransaction(txdb, fCheckInputs);
667 return AcceptTransaction(txdb, fCheckInputs);
672 void ReacceptWalletTransactions()
675 CRITICAL_BLOCK(cs_mapWallet)
677 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
679 CWalletTx& wtx = item.second;
680 if (wtx.fSpent && wtx.IsCoinBase())
684 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
686 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
689 if (txindex.vSpent.size() != wtx.vout.size())
691 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
694 for (int i = 0; i < txindex.vSpent.size(); i++)
696 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
698 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
708 // Reaccept any txes of ours that aren't already in a block
709 if (!wtx.IsCoinBase())
710 wtx.AcceptWalletTransaction(txdb, false);
717 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
719 foreach(const CMerkleTx& tx, vtxPrev)
721 if (!tx.IsCoinBase())
723 uint256 hash = tx.GetHash();
724 if (!txdb.ContainsTx(hash))
725 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
730 uint256 hash = GetHash();
731 if (!txdb.ContainsTx(hash))
733 printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());
734 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
739 void ResendWalletTransactions()
741 // Do this infrequently and randomly to avoid giving away
742 // that these are our transactions.
743 static int64 nNextTime;
744 if (GetTime() < nNextTime)
746 bool fFirst = (nNextTime == 0);
747 nNextTime = GetTime() + GetRand(30 * 60);
751 // Rebroadcast any of our txes that aren't in a block yet
752 printf("ResendWalletTransactions()\n");
754 CRITICAL_BLOCK(cs_mapWallet)
756 // Sort them in chronological order
757 multimap<unsigned int, CWalletTx*> mapSorted;
758 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
760 CWalletTx& wtx = item.second;
761 // Don't rebroadcast until it's had plenty of time that
762 // it should have gotten in already by now.
763 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
764 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
766 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
768 CWalletTx& wtx = *item.second;
769 wtx.RelayWalletTransaction(txdb);
783 //////////////////////////////////////////////////////////////////////////////
785 // CBlock and CBlockIndex
788 bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)
790 return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);
793 uint256 GetOrphanRoot(const CBlock* pblock)
795 // Work back to the first block in the orphan chain
796 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
797 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
798 return pblock->GetHash();
801 int64 CBlock::GetBlockValue(int nHeight, int64 nFees) const
803 int64 nSubsidy = 50 * COIN;
805 // Subsidy is cut in half every 4 years
806 nSubsidy >>= (nHeight / 210000);
808 return nSubsidy + nFees;
811 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
813 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
814 const int64 nTargetSpacing = 10 * 60;
815 const int64 nInterval = nTargetTimespan / nTargetSpacing;
818 if (pindexLast == NULL)
819 return bnProofOfWorkLimit.GetCompact();
821 // Only change once per interval
822 if ((pindexLast->nHeight+1) % nInterval != 0)
823 return pindexLast->nBits;
825 // Go back by what we want to be 14 days worth of blocks
826 const CBlockIndex* pindexFirst = pindexLast;
827 for (int i = 0; pindexFirst && i < nInterval-1; i++)
828 pindexFirst = pindexFirst->pprev;
831 // Limit adjustment step
832 int64 nActualTimespan = (int64)pindexLast->nTime - (int64)pindexFirst->nTime;
833 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
834 if (nActualTimespan < nTargetTimespan/4)
835 nActualTimespan = nTargetTimespan/4;
836 if (nActualTimespan > nTargetTimespan*4)
837 nActualTimespan = nTargetTimespan*4;
841 bnNew.SetCompact(pindexLast->nBits);
842 bnNew *= nActualTimespan;
843 bnNew /= nTargetTimespan;
845 if (bnNew > bnProofOfWorkLimit)
846 bnNew = bnProofOfWorkLimit;
849 printf("GetNextWorkRequired RETARGET\n");
850 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
851 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
852 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
854 return bnNew.GetCompact();
857 bool IsInitialBlockDownload()
859 if (pindexBest == NULL)
861 static int64 nLastUpdate;
862 static CBlockIndex* pindexLastBest;
863 if (pindexBest != pindexLastBest)
865 pindexLastBest = pindexBest;
866 nLastUpdate = GetTime();
868 return (GetTime() - nLastUpdate < 10 &&
869 pindexBest->nTime < GetTime() - 24 * 60 * 60);
876 return (bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6);
879 void Lockdown(CBlockIndex* pindexNew)
881 if (pindexNew->bnChainWork > bnBestInvalidWork)
883 bnBestInvalidWork = pindexNew->bnChainWork;
884 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
887 printf("Lockdown: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,22).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
888 printf("Lockdown: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
889 printf("Lockdown: IsLockdown()=%d\n", (IsLockdown() ? 1 : 0));
891 printf("Lockdown: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
901 bool CTransaction::DisconnectInputs(CTxDB& txdb)
903 // Relinquish previous transactions' spent pointers
906 foreach(const CTxIn& txin, vin)
908 COutPoint prevout = txin.prevout;
910 // Get prev txindex from disk
912 if (!txdb.ReadTxIndex(prevout.hash, txindex))
913 return error("DisconnectInputs() : ReadTxIndex failed");
915 if (prevout.n >= txindex.vSpent.size())
916 return error("DisconnectInputs() : prevout.n out of range");
918 // Mark outpoint as not spent
919 txindex.vSpent[prevout.n].SetNull();
922 txdb.UpdateTxIndex(prevout.hash, txindex);
926 // Remove transaction from index
927 if (!txdb.EraseTxIndex(*this))
928 return error("DisconnectInputs() : EraseTxPos failed");
934 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
935 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
937 // Take over previous transactions' spent pointers
941 for (int i = 0; i < vin.size(); i++)
943 COutPoint prevout = vin[i].prevout;
948 if (fMiner && mapTestPool.count(prevout.hash))
950 // Get txindex from current proposed changes
951 txindex = mapTestPool[prevout.hash];
955 // Read txindex from txdb
956 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
958 if (!fFound && (fBlock || fMiner))
959 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());
963 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
965 // Get prev tx from single transactions in memory
966 CRITICAL_BLOCK(cs_mapTransactions)
968 if (!mapTransactions.count(prevout.hash))
969 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
970 txPrev = mapTransactions[prevout.hash];
973 txindex.vSpent.resize(txPrev.vout.size());
977 // Get prev tx from disk
978 if (!txPrev.ReadFromDisk(txindex.pos))
979 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
982 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
983 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());
985 // If prev is coinbase, check that it's matured
986 if (txPrev.IsCoinBase())
987 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
988 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
989 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
992 if (!VerifySignature(txPrev, *this, i))
993 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
995 // Check for conflicts
996 if (!txindex.vSpent[prevout.n].IsNull())
997 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());
999 // Mark outpoints as spent
1000 txindex.vSpent[prevout.n] = posThisTx;
1004 txdb.UpdateTxIndex(prevout.hash, txindex);
1006 mapTestPool[prevout.hash] = txindex;
1008 nValueIn += txPrev.vout[prevout.n].nValue;
1010 // Check for negative or overflow input values
1011 if (txPrev.vout[prevout.n].nValue < 0)
1012 return error("ConnectInputs() : txin.nValue negative");
1013 if (txPrev.vout[prevout.n].nValue > MAX_MONEY)
1014 return error("ConnectInputs() : txin.nValue too high");
1015 if (nValueIn > MAX_MONEY)
1016 return error("ConnectInputs() : txin total too high");
1019 // Tally transaction fees
1020 int64 nTxFee = nValueIn - GetValueOut();
1022 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
1023 if (nTxFee < nMinFee)
1030 // Add transaction to disk index
1031 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1032 return error("ConnectInputs() : AddTxPos failed");
1036 // Add transaction to test pool
1037 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1044 bool CTransaction::ClientConnectInputs()
1049 // Take over previous transactions' spent pointers
1050 CRITICAL_BLOCK(cs_mapTransactions)
1053 for (int i = 0; i < vin.size(); i++)
1055 // Get prev tx from single transactions in memory
1056 COutPoint prevout = vin[i].prevout;
1057 if (!mapTransactions.count(prevout.hash))
1059 CTransaction& txPrev = mapTransactions[prevout.hash];
1061 if (prevout.n >= txPrev.vout.size())
1065 if (!VerifySignature(txPrev, *this, i))
1066 return error("ConnectInputs() : VerifySignature failed");
1068 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1069 ///// this has to go away now that posNext is gone
1070 // // Check for conflicts
1071 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1072 // return error("ConnectInputs() : prev tx already used");
1074 // // Flag outpoints as used
1075 // txPrev.vout[prevout.n].posNext = posThisTx;
1077 nValueIn += txPrev.vout[prevout.n].nValue;
1079 if (GetValueOut() > nValueIn)
1089 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1091 // Disconnect in reverse order
1092 for (int i = vtx.size()-1; i >= 0; i--)
1093 if (!vtx[i].DisconnectInputs(txdb))
1096 // Update block index on disk without changing it in memory.
1097 // The memory index structure will be changed after the db commits.
1100 CDiskBlockIndex blockindexPrev(pindex->pprev);
1101 blockindexPrev.hashNext = 0;
1102 txdb.WriteBlockIndex(blockindexPrev);
1108 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1110 // Check it again in case a previous version let a bad block in
1114 //// issue here: it doesn't know the version
1115 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1117 map<uint256, CTxIndex> mapUnused;
1119 foreach(CTransaction& tx, vtx)
1121 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1122 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1124 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1128 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1131 // Update block index on disk without changing it in memory.
1132 // The memory index structure will be changed after the db commits.
1135 CDiskBlockIndex blockindexPrev(pindex->pprev);
1136 blockindexPrev.hashNext = pindex->GetBlockHash();
1137 txdb.WriteBlockIndex(blockindexPrev);
1140 // Watch for transactions paying to me
1141 foreach(CTransaction& tx, vtx)
1142 AddToWalletIfMine(tx, this);
1149 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1151 printf("REORGANIZE\n");
1154 CBlockIndex* pfork = pindexBest;
1155 CBlockIndex* plonger = pindexNew;
1156 while (pfork != plonger)
1158 while (plonger->nHeight > pfork->nHeight)
1159 if (!(plonger = plonger->pprev))
1160 return error("Reorganize() : plonger->pprev is null");
1161 if (pfork == plonger)
1163 if (!(pfork = pfork->pprev))
1164 return error("Reorganize() : pfork->pprev is null");
1167 // List of what to disconnect
1168 vector<CBlockIndex*> vDisconnect;
1169 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1170 vDisconnect.push_back(pindex);
1172 // List of what to connect
1173 vector<CBlockIndex*> vConnect;
1174 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1175 vConnect.push_back(pindex);
1176 reverse(vConnect.begin(), vConnect.end());
1178 // Disconnect shorter branch
1179 vector<CTransaction> vResurrect;
1180 foreach(CBlockIndex* pindex, vDisconnect)
1183 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1184 return error("Reorganize() : ReadFromDisk for disconnect failed");
1185 if (!block.DisconnectBlock(txdb, pindex))
1186 return error("Reorganize() : DisconnectBlock failed");
1188 // Queue memory transactions to resurrect
1189 foreach(const CTransaction& tx, block.vtx)
1190 if (!tx.IsCoinBase())
1191 vResurrect.push_back(tx);
1194 // Connect longer branch
1195 vector<CTransaction> vDelete;
1196 for (int i = 0; i < vConnect.size(); i++)
1198 CBlockIndex* pindex = vConnect[i];
1200 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1201 return error("Reorganize() : ReadFromDisk for connect failed");
1202 if (!block.ConnectBlock(txdb, pindex))
1206 return error("Reorganize() : ConnectBlock failed");
1209 // Queue memory transactions to delete
1210 foreach(const CTransaction& tx, block.vtx)
1211 vDelete.push_back(tx);
1213 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1214 return error("Reorganize() : WriteHashBestChain failed");
1216 // Commit now because resurrecting could take some time
1219 // Disconnect shorter branch
1220 foreach(CBlockIndex* pindex, vDisconnect)
1222 pindex->pprev->pnext = NULL;
1224 // Connect longer branch
1225 foreach(CBlockIndex* pindex, vConnect)
1227 pindex->pprev->pnext = pindex;
1229 // Resurrect memory transactions that were in the disconnected branch
1230 foreach(CTransaction& tx, vResurrect)
1231 tx.AcceptTransaction(txdb, false);
1233 // Delete redundant memory transactions that are in the connected branch
1234 foreach(CTransaction& tx, vDelete)
1235 tx.RemoveFromMemoryPool();
1241 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1243 uint256 hash = GetHash();
1246 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1248 pindexGenesisBlock = pindexNew;
1249 txdb.WriteHashBestChain(hash);
1251 else if (hashPrevBlock == hashBestChain)
1253 // Adding to current best branch
1254 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1257 Lockdown(pindexNew);
1258 return error("SetBestChain() : ConnectBlock failed");
1261 pindexNew->pprev->pnext = pindexNew;
1263 // Delete redundant memory transactions
1264 foreach(CTransaction& tx, vtx)
1265 tx.RemoveFromMemoryPool();
1270 if (!Reorganize(txdb, pindexNew))
1273 Lockdown(pindexNew);
1274 return error("SetBestChain() : Reorganize failed");
1280 hashBestChain = hash;
1281 pindexBest = pindexNew;
1282 nBestHeight = pindexBest->nHeight;
1283 bnBestChainWork = pindexNew->bnChainWork;
1284 nTimeBestReceived = GetTime();
1285 nTransactionsUpdated++;
1286 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1292 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1294 // Check for duplicate
1295 uint256 hash = GetHash();
1296 if (mapBlockIndex.count(hash))
1297 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());
1299 // Construct new block index object
1300 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1302 return error("AddToBlockIndex() : new CBlockIndex failed");
1303 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1304 pindexNew->phashBlock = &((*mi).first);
1305 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1306 if (miPrev != mapBlockIndex.end())
1308 pindexNew->pprev = (*miPrev).second;
1309 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1311 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1314 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1317 if (pindexNew->bnChainWork > bnBestChainWork)
1318 if (!SetBestChain(txdb, pindexNew))
1323 if (pindexNew == pindexBest)
1325 // Notify UI to display prev block's coinbase if it was ours
1326 static uint256 hashPrevBestCoinBase;
1327 CRITICAL_BLOCK(cs_mapWallet)
1328 vWalletUpdated.push_back(hashPrevBestCoinBase);
1329 hashPrevBestCoinBase = vtx[0].GetHash();
1339 bool CBlock::CheckBlock() const
1341 // These are checks that are independent of context
1342 // that can be verified before saving an orphan block.
1345 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
1346 return error("CheckBlock() : size limits failed");
1349 if (nTime > GetAdjustedTime() + 2 * 60 * 60)
1350 return error("CheckBlock() : block timestamp too far in the future");
1352 // First transaction must be coinbase, the rest must not be
1353 if (vtx.empty() || !vtx[0].IsCoinBase())
1354 return error("CheckBlock() : first tx is not coinbase");
1355 for (int i = 1; i < vtx.size(); i++)
1356 if (vtx[i].IsCoinBase())
1357 return error("CheckBlock() : more than one coinbase");
1359 // Check transactions
1360 foreach(const CTransaction& tx, vtx)
1361 if (!tx.CheckTransaction())
1362 return error("CheckBlock() : CheckTransaction failed");
1364 // Check proof of work matches claimed amount
1365 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
1366 return error("CheckBlock() : nBits below minimum work");
1367 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
1368 return error("CheckBlock() : hash doesn't match nBits");
1371 if (hashMerkleRoot != BuildMerkleTree())
1372 return error("CheckBlock() : hashMerkleRoot mismatch");
1377 bool CBlock::AcceptBlock()
1379 // Check for duplicate
1380 uint256 hash = GetHash();
1381 if (mapBlockIndex.count(hash))
1382 return error("AcceptBlock() : block already in mapBlockIndex");
1384 // Get prev block index
1385 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1386 if (mi == mapBlockIndex.end())
1387 return error("AcceptBlock() : prev block not found");
1388 CBlockIndex* pindexPrev = (*mi).second;
1390 // Check timestamp against prev
1391 if (nTime <= pindexPrev->GetMedianTimePast())
1392 return error("AcceptBlock() : block's timestamp is too early");
1394 // Check that all transactions are finalized
1395 foreach(const CTransaction& tx, vtx)
1396 if (!tx.IsFinal(pindexPrev->nHeight+1, nTime))
1397 return error("AcceptBlock() : contains a non-final transaction");
1399 // Check proof of work
1400 if (nBits != GetNextWorkRequired(pindexPrev))
1401 return error("AcceptBlock() : incorrect proof of work");
1403 // Check that the block chain matches the known block chain up to a checkpoint
1404 if ((pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1405 (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1406 (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1407 (pindexPrev->nHeight+1 == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1408 (pindexPrev->nHeight+1 == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1409 return error("AcceptBlock() : rejected by checkpoint lockin at %d", pindexPrev->nHeight+1);
1411 // Scanback checkpoint lockin
1412 for (CBlockIndex* pindex = pindexPrev; pindex->nHeight >= 74000; pindex = pindex->pprev)
1414 if (pindex->nHeight == 74000 && pindex->GetBlockHash() != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
1415 return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);
1416 if (pindex->nHeight == 74638 && pindex->GetBlockHash() == uint256("0x0000000000790ab3f22ec756ad43b6ab569abf0bddeb97c67a6f7b1470a7ec1c"))
1417 return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);
1420 // Write block to history file
1421 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1422 return error("AcceptBlock() : out of disk space");
1424 unsigned int nBlockPos;
1425 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1426 return error("AcceptBlock() : WriteToDisk failed");
1427 if (!AddToBlockIndex(nFile, nBlockPos))
1428 return error("AcceptBlock() : AddToBlockIndex failed");
1430 // Relay inventory, but don't relay old inventory during initial block download
1431 if (hashBestChain == hash)
1432 CRITICAL_BLOCK(cs_vNodes)
1433 foreach(CNode* pnode, vNodes)
1434 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1435 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1440 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1442 // Check for duplicate
1443 uint256 hash = pblock->GetHash();
1444 if (mapBlockIndex.count(hash))
1445 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());
1446 if (mapOrphanBlocks.count(hash))
1447 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());
1449 // Preliminary checks
1450 if (!pblock->CheckBlock())
1453 return error("ProcessBlock() : CheckBlock FAILED");
1456 // If don't already have its previous block, shunt it off to holding area until we get it
1457 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1459 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());
1460 mapOrphanBlocks.insert(make_pair(hash, pblock));
1461 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1463 // Ask this guy to fill in what we're missing
1465 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1470 if (!pblock->AcceptBlock())
1473 return error("ProcessBlock() : AcceptBlock FAILED");
1477 // Recursively process any orphan blocks that depended on this one
1478 vector<uint256> vWorkQueue;
1479 vWorkQueue.push_back(hash);
1480 for (int i = 0; i < vWorkQueue.size(); i++)
1482 uint256 hashPrev = vWorkQueue[i];
1483 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1484 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1487 CBlock* pblockOrphan = (*mi).second;
1488 if (pblockOrphan->AcceptBlock())
1489 vWorkQueue.push_back(pblockOrphan->GetHash());
1490 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1491 delete pblockOrphan;
1493 mapOrphanBlocksByPrev.erase(hashPrev);
1496 printf("ProcessBlock: ACCEPTED\n");
1507 template<typename Stream>
1508 bool ScanMessageStart(Stream& s)
1510 // Scan ahead to the next pchMessageStart, which should normally be immediately
1511 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1513 short prevmask = s.exceptions(0);
1514 const char* p = BEGIN(pchMessageStart);
1524 s.exceptions(prevmask);
1528 p = BEGIN(pchMessageStart);
1531 if (++p == END(pchMessageStart))
1534 s.exceptions(prevmask);
1543 s.exceptions(prevmask);
1548 bool CheckDiskSpace(int64 nAdditionalBytes)
1550 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1552 // Check for 15MB because database could create another 10MB log file at any time
1553 if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)
1556 printf("*** %s***\n", _("Warning: Disk space is low "));
1558 ThreadSafeMessageBox(_("Warning: Disk space is low "), "Bitcoin", wxOK | wxICON_EXCLAMATION);
1560 CreateThread(Shutdown, NULL);
1566 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1570 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1573 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1575 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1584 static unsigned int nCurrentBlockFile = 1;
1586 FILE* AppendBlockFile(unsigned int& nFileRet)
1591 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1594 if (fseek(file, 0, SEEK_END) != 0)
1596 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1597 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1599 nFileRet = nCurrentBlockFile;
1603 nCurrentBlockFile++;
1607 bool LoadBlockIndex(bool fAllowNew)
1613 if (!txdb.LoadBlockIndex())
1618 // Init with genesis block
1620 if (mapBlockIndex.empty())
1627 // GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
1628 // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
1629 // txNew.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
1630 // txNew.vout[0].nValue = 5000000000
1631 // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG
1632 // block.nVersion = 1
1633 // block.nTime = 1231006505
1634 // block.nBits = 0x1d00ffff
1635 // block.nNonce = 2083236893
1636 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1637 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1638 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1639 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1640 // vMerkleTree: 4a5e1e
1643 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1645 txNew.vin.resize(1);
1646 txNew.vout.resize(1);
1647 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1648 txNew.vout[0].nValue = 50 * COIN;
1650 bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");
1651 txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;
1653 block.vtx.push_back(txNew);
1654 block.hashPrevBlock = 0;
1655 block.hashMerkleRoot = block.BuildMerkleTree();
1657 block.nTime = 1231006505;
1658 block.nBits = 0x1d00ffff;
1659 block.nNonce = 2083236893;
1662 printf("%s\n", block.GetHash().ToString().c_str());
1663 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1664 printf("%s\n", hashGenesisBlock.ToString().c_str());
1665 txNew.vout[0].scriptPubKey.print();
1667 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1669 assert(block.GetHash() == hashGenesisBlock);
1671 // Start new block file
1673 unsigned int nBlockPos;
1674 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1675 return error("LoadBlockIndex() : writing genesis block to disk failed");
1676 if (!block.AddToBlockIndex(nFile, nBlockPos))
1677 return error("LoadBlockIndex() : genesis block not accepted");
1685 void PrintBlockTree()
1687 // precompute tree structure
1688 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1689 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1691 CBlockIndex* pindex = (*mi).second;
1692 mapNext[pindex->pprev].push_back(pindex);
1694 //while (rand() % 3 == 0)
1695 // mapNext[pindex->pprev].push_back(pindex);
1698 vector<pair<int, CBlockIndex*> > vStack;
1699 vStack.push_back(make_pair(0, pindexGenesisBlock));
1702 while (!vStack.empty())
1704 int nCol = vStack.back().first;
1705 CBlockIndex* pindex = vStack.back().second;
1708 // print split or gap
1709 if (nCol > nPrevCol)
1711 for (int i = 0; i < nCol-1; i++)
1715 else if (nCol < nPrevCol)
1717 for (int i = 0; i < nCol; i++)
1724 for (int i = 0; i < nCol; i++)
1729 block.ReadFromDisk(pindex);
1730 printf("%d (%u,%u) %s %s tx %d",
1734 block.GetHash().ToString().substr(0,16).c_str(),
1735 DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),
1738 CRITICAL_BLOCK(cs_mapWallet)
1740 if (mapWallet.count(block.vtx[0].GetHash()))
1742 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1743 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1749 // put the main timechain first
1750 vector<CBlockIndex*>& vNext = mapNext[pindex];
1751 for (int i = 0; i < vNext.size(); i++)
1753 if (vNext[i]->pnext)
1755 swap(vNext[0], vNext[i]);
1761 for (int i = 0; i < vNext.size(); i++)
1762 vStack.push_back(make_pair(nCol+i, vNext[i]));
1775 //////////////////////////////////////////////////////////////////////////////
1781 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1785 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1786 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1788 // Don't know what it is, just say we already got one
1798 bool ProcessMessages(CNode* pfrom)
1800 CDataStream& vRecv = pfrom->vRecv;
1804 // printf("ProcessMessages(%d bytes)\n", vRecv.size());
1808 // (4) message start
1817 // Scan for message start
1818 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
1819 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
1820 if (vRecv.end() - pstart < nHeaderSize)
1822 if (vRecv.size() > nHeaderSize)
1824 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
1825 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
1829 if (pstart - vRecv.begin() > 0)
1830 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
1831 vRecv.erase(vRecv.begin(), pstart);
1834 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
1839 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
1842 string strCommand = hdr.GetCommand();
1845 unsigned int nMessageSize = hdr.nMessageSize;
1846 if (nMessageSize > vRecv.size())
1848 // Rewind and wait for rest of message
1849 ///// need a mechanism to give up waiting for overlong message size error
1850 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
1854 // Copy message to its own buffer
1855 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
1856 vRecv.ignore(nMessageSize);
1859 if (vRecv.GetVersion() >= 209)
1861 uint256 hash = Hash(vMsg.begin(), vMsg.end());
1862 unsigned int nChecksum = 0;
1863 memcpy(&nChecksum, &hash, sizeof(nChecksum));
1864 if (nChecksum != hdr.nChecksum)
1866 printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
1867 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
1876 CRITICAL_BLOCK(cs_main)
1877 fRet = ProcessMessage(pfrom, strCommand, vMsg);
1881 catch (std::ios_base::failure& e)
1883 if (strstr(e.what(), "CDataStream::read() : end of data"))
1885 // Allow exceptions from underlength message on vRecv
1886 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());
1888 else if (strstr(e.what(), ": size too large"))
1890 // Allow exceptions from overlong size
1891 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
1895 PrintException(&e, "ProcessMessage()");
1898 catch (std::exception& e) {
1899 PrintException(&e, "ProcessMessage()");
1901 PrintException(NULL, "ProcessMessage()");
1905 printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);
1915 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1917 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1918 RandAddSeedPerfmon();
1920 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1921 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1922 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1924 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1932 if (strCommand == "version")
1934 // Each connection can only send one version message
1935 if (pfrom->nVersion != 0)
1943 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1944 if (pfrom->nVersion == 10300)
1945 pfrom->nVersion = 300;
1946 if (pfrom->nVersion >= 106 && !vRecv.empty())
1947 vRecv >> addrFrom >> nNonce;
1948 if (pfrom->nVersion >= 106 && !vRecv.empty())
1950 if (pfrom->nVersion >= 209 && !vRecv.empty())
1951 vRecv >> pfrom->nStartingHeight;
1953 if (pfrom->nVersion == 0)
1956 // Disconnect if we connected to ourself
1957 if (nNonce == nLocalHostNonce && nNonce > 1)
1959 pfrom->fDisconnect = true;
1963 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1966 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
1967 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
1970 AddTimeData(pfrom->addr.ip, nTime);
1973 if (pfrom->nVersion >= 209)
1974 pfrom->PushMessage("verack");
1975 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1976 if (pfrom->nVersion < 209)
1977 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1979 // Ask the first connected node for block updates
1980 static int nAskedForBlocks;
1981 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1984 pfrom->PushGetBlocks(pindexBest, uint256(0));
1987 pfrom->fSuccessfullyConnected = true;
1989 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1993 else if (pfrom->nVersion == 0)
1995 // Must have a version message before anything else
2000 else if (strCommand == "verack")
2002 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2006 else if (strCommand == "addr")
2008 vector<CAddress> vAddr;
2010 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
2012 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
2014 if (vAddr.size() > 1000)
2015 return error("message addr size() = %d", vAddr.size());
2017 // Store the new addresses
2018 foreach(CAddress& addr, vAddr)
2022 // ignore IPv6 for now, since it isn't implemented anyway
2025 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
2026 if (pfrom->fGetAddr || vAddr.size() > 10)
2027 addr.nTime -= 5 * 24 * 60 * 60;
2029 pfrom->AddAddressKnown(addr);
2030 if (!pfrom->fGetAddr && addr.IsRoutable())
2032 // Relay to a limited number of other nodes
2033 CRITICAL_BLOCK(cs_vNodes)
2035 // Use deterministic randomness to send to
2036 // the same places for 12 hours at a time
2037 static uint256 hashSalt;
2039 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2040 uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
2041 multimap<uint256, CNode*> mapMix;
2042 foreach(CNode* pnode, vNodes)
2043 mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
2044 int nRelayNodes = 4;
2045 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2046 ((*mi).second)->PushAddress(addr);
2050 if (vAddr.size() < 1000)
2051 pfrom->fGetAddr = false;
2055 else if (strCommand == "inv")
2059 if (vInv.size() > 50000)
2060 return error("message inv size() = %d", vInv.size());
2063 foreach(const CInv& inv, vInv)
2067 pfrom->AddInventoryKnown(inv);
2069 bool fAlreadyHave = AlreadyHave(txdb, inv);
2070 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2074 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2075 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2077 // Track requests for our stuff
2078 CRITICAL_BLOCK(cs_mapRequestCount)
2080 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2081 if (mi != mapRequestCount.end())
2088 else if (strCommand == "getdata")
2092 if (vInv.size() > 50000)
2093 return error("message getdata size() = %d", vInv.size());
2095 foreach(const CInv& inv, vInv)
2099 printf("received getdata for: %s\n", inv.ToString().c_str());
2101 if (inv.type == MSG_BLOCK)
2103 // Send block from disk
2104 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2105 if (mi != mapBlockIndex.end())
2107 //// could optimize this to send header straight from blockindex for client
2109 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2110 pfrom->PushMessage("block", block);
2112 // Trigger them to send a getblocks request for the next batch of inventory
2113 if (inv.hash == pfrom->hashContinue)
2115 // Bypass PushInventory, this must send even if redundant,
2116 // and we want it right after the last block so they don't
2117 // wait for other stuff first.
2119 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2120 pfrom->PushMessage("inv", vInv);
2121 pfrom->hashContinue = 0;
2125 else if (inv.IsKnownType())
2127 // Send stream from relay memory
2128 CRITICAL_BLOCK(cs_mapRelay)
2130 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2131 if (mi != mapRelay.end())
2132 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2136 // Track requests for our stuff
2137 CRITICAL_BLOCK(cs_mapRequestCount)
2139 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2140 if (mi != mapRequestCount.end())
2147 else if (strCommand == "getblocks")
2149 CBlockLocator locator;
2151 vRecv >> locator >> hashStop;
2153 // Find the first block the caller has in the main chain
2154 CBlockIndex* pindex = locator.GetBlockIndex();
2156 // Send the rest of the chain
2158 pindex = pindex->pnext;
2159 int nLimit = 500 + locator.GetDistanceBack();
2160 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);
2161 for (; pindex; pindex = pindex->pnext)
2163 if (pindex->GetBlockHash() == hashStop)
2165 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2168 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2171 // When this block is requested, we'll send an inv that'll make them
2172 // getblocks the next batch of inventory.
2173 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2174 pfrom->hashContinue = pindex->GetBlockHash();
2181 else if (strCommand == "tx")
2183 vector<uint256> vWorkQueue;
2184 CDataStream vMsg(vRecv);
2188 CInv inv(MSG_TX, tx.GetHash());
2189 pfrom->AddInventoryKnown(inv);
2191 bool fMissingInputs = false;
2192 if (tx.AcceptTransaction(true, &fMissingInputs))
2194 AddToWalletIfMine(tx, NULL);
2195 RelayMessage(inv, vMsg);
2196 mapAlreadyAskedFor.erase(inv);
2197 vWorkQueue.push_back(inv.hash);
2199 // Recursively process any orphan transactions that depended on this one
2200 for (int i = 0; i < vWorkQueue.size(); i++)
2202 uint256 hashPrev = vWorkQueue[i];
2203 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2204 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2207 const CDataStream& vMsg = *((*mi).second);
2209 CDataStream(vMsg) >> tx;
2210 CInv inv(MSG_TX, tx.GetHash());
2212 if (tx.AcceptTransaction(true))
2214 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2215 AddToWalletIfMine(tx, NULL);
2216 RelayMessage(inv, vMsg);
2217 mapAlreadyAskedFor.erase(inv);
2218 vWorkQueue.push_back(inv.hash);
2223 foreach(uint256 hash, vWorkQueue)
2224 EraseOrphanTx(hash);
2226 else if (fMissingInputs)
2228 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2234 else if (strCommand == "block")
2236 auto_ptr<CBlock> pblock(new CBlock);
2240 printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());
2243 CInv inv(MSG_BLOCK, pblock->GetHash());
2244 pfrom->AddInventoryKnown(inv);
2246 if (ProcessBlock(pfrom, pblock.release()))
2247 mapAlreadyAskedFor.erase(inv);
2251 else if (strCommand == "getaddr")
2253 // This includes all nodes that are currently online,
2254 // since they rebroadcast an addr every 24 hours
2255 pfrom->vAddrToSend.clear();
2256 int64 nSince = GetAdjustedTime() - 12 * 60 * 60; // in the last 12 hours
2257 CRITICAL_BLOCK(cs_mapAddresses)
2259 unsigned int nSize = mapAddresses.size();
2260 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2264 const CAddress& addr = item.second;
2265 if (addr.nTime > nSince)
2266 pfrom->PushAddress(addr);
2272 else if (strCommand == "checkorder")
2276 vRecv >> hashReply >> order;
2278 /// we have a chance to check the order here
2280 // Keep giving the same key to the same ip until they use it
2281 if (!mapReuseKey.count(pfrom->addr.ip))
2282 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
2284 // Send back approval of order and pubkey to use
2285 CScript scriptPubKey;
2286 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2287 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2291 else if (strCommand == "submitorder")
2295 vRecv >> hashReply >> wtxNew;
2296 wtxNew.fFromMe = false;
2299 if (!wtxNew.AcceptWalletTransaction())
2301 pfrom->PushMessage("reply", hashReply, (int)1);
2302 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2304 wtxNew.fTimeReceivedIsTxTime = true;
2305 AddToWallet(wtxNew);
2306 wtxNew.RelayWalletTransaction();
2307 mapReuseKey.erase(pfrom->addr.ip);
2309 // Send back confirmation
2310 pfrom->PushMessage("reply", hashReply, (int)0);
2314 else if (strCommand == "reply")
2319 CRequestTracker tracker;
2320 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2322 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2323 if (mi != pfrom->mapRequests.end())
2325 tracker = (*mi).second;
2326 pfrom->mapRequests.erase(mi);
2329 if (!tracker.IsNull())
2330 tracker.fn(tracker.param1, vRecv);
2334 else if (strCommand == "ping")
2341 // Ignore unknown commands for extensibility
2345 // Update the last seen time for this node's address
2346 if (pfrom->fNetworkNode)
2347 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2348 AddressCurrentlyConnected(pfrom->addr);
2362 bool SendMessages(CNode* pto, bool fSendTrickle)
2364 CRITICAL_BLOCK(cs_main)
2366 // Don't send anything until we get their version message
2367 if (pto->nVersion == 0)
2371 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2372 pto->PushMessage("ping");
2374 // Address refresh broadcast
2375 static int64 nLastRebroadcast;
2376 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2378 nLastRebroadcast = GetTime();
2379 CRITICAL_BLOCK(cs_vNodes)
2381 foreach(CNode* pnode, vNodes)
2383 // Periodically clear setAddrKnown to allow refresh broadcasts
2384 pnode->setAddrKnown.clear();
2386 // Rebroadcast our address
2387 if (addrLocalHost.IsRoutable() && !fUseProxy)
2388 pnode->PushAddress(addrLocalHost);
2393 // Resend wallet transactions that haven't gotten in a block yet
2394 ResendWalletTransactions();
2402 vector<CAddress> vAddr;
2403 vAddr.reserve(pto->vAddrToSend.size());
2404 foreach(const CAddress& addr, pto->vAddrToSend)
2406 // returns true if wasn't already contained in the set
2407 if (pto->setAddrKnown.insert(addr).second)
2409 vAddr.push_back(addr);
2410 // receiver rejects addr messages larger than 1000
2411 if (vAddr.size() >= 1000)
2413 pto->PushMessage("addr", vAddr);
2418 pto->vAddrToSend.clear();
2420 pto->PushMessage("addr", vAddr);
2425 // Message: inventory
2428 vector<CInv> vInvWait;
2429 CRITICAL_BLOCK(pto->cs_inventory)
2431 vInv.reserve(pto->vInventoryToSend.size());
2432 vInvWait.reserve(pto->vInventoryToSend.size());
2433 foreach(const CInv& inv, pto->vInventoryToSend)
2435 if (pto->setInventoryKnown.count(inv))
2438 // trickle out tx inv to protect privacy
2439 if (inv.type == MSG_TX && !fSendTrickle)
2441 // 1/4 of tx invs blast to all immediately
2442 static uint256 hashSalt;
2444 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2445 uint256 hashRand = inv.hash ^ hashSalt;
2446 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2447 bool fTrickleWait = ((hashRand & 3) != 0);
2449 // always trickle our own transactions
2452 TRY_CRITICAL_BLOCK(cs_mapWallet)
2454 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2455 if (mi != mapWallet.end())
2457 CWalletTx& wtx = (*mi).second;
2459 fTrickleWait = true;
2466 vInvWait.push_back(inv);
2471 // returns true if wasn't already contained in the set
2472 if (pto->setInventoryKnown.insert(inv).second)
2474 vInv.push_back(inv);
2475 if (vInv.size() >= 1000)
2477 pto->PushMessage("inv", vInv);
2482 pto->vInventoryToSend = vInvWait;
2485 pto->PushMessage("inv", vInv);
2491 vector<CInv> vGetData;
2492 int64 nNow = GetTime() * 1000000;
2494 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2496 const CInv& inv = (*pto->mapAskFor.begin()).second;
2497 if (!AlreadyHave(txdb, inv))
2499 printf("sending getdata: %s\n", inv.ToString().c_str());
2500 vGetData.push_back(inv);
2501 if (vGetData.size() >= 1000)
2503 pto->PushMessage("getdata", vGetData);
2507 pto->mapAskFor.erase(pto->mapAskFor.begin());
2509 if (!vGetData.empty())
2510 pto->PushMessage("getdata", vGetData);
2529 //////////////////////////////////////////////////////////////////////////////
2534 void GenerateBitcoins(bool fGenerate)
2536 if (fGenerateBitcoins != fGenerate)
2538 fGenerateBitcoins = fGenerate;
2539 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2542 if (fGenerateBitcoins)
2544 int nProcessors = boost::thread::hardware_concurrency();
2545 printf("%d processors\n", nProcessors);
2546 if (nProcessors < 1)
2548 if (fLimitProcessors && nProcessors > nLimitProcessors)
2549 nProcessors = nLimitProcessors;
2550 int nAddThreads = nProcessors - vnThreadsRunning[3];
2551 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2552 for (int i = 0; i < nAddThreads; i++)
2554 if (!CreateThread(ThreadBitcoinMiner, NULL))
2555 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2561 void ThreadBitcoinMiner(void* parg)
2565 vnThreadsRunning[3]++;
2567 vnThreadsRunning[3]--;
2569 catch (std::exception& e) {
2570 vnThreadsRunning[3]--;
2571 PrintException(&e, "ThreadBitcoinMiner()");
2573 vnThreadsRunning[3]--;
2574 PrintException(NULL, "ThreadBitcoinMiner()");
2576 UIThreadCall(bind(CalledSetStatusBar, "", 0));
2578 if (vnThreadsRunning[3] == 0)
2580 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2583 int FormatHashBlocks(void* pbuffer, unsigned int len)
2585 unsigned char* pdata = (unsigned char*)pbuffer;
2586 unsigned int blocks = 1 + ((len + 8) / 64);
2587 unsigned char* pend = pdata + 64 * blocks;
2588 memset(pdata + len, 0, 64 * blocks - len);
2590 unsigned int bits = len * 8;
2591 pend[-1] = (bits >> 0) & 0xff;
2592 pend[-2] = (bits >> 8) & 0xff;
2593 pend[-3] = (bits >> 16) & 0xff;
2594 pend[-4] = (bits >> 24) & 0xff;
2598 using CryptoPP::ByteReverse;
2600 static const unsigned int pSHA256InitState[8] =
2601 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2603 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2605 memcpy(pstate, pinit, 32);
2606 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2609 static const int NPAR = 32;
2610 extern void Double_BlockSHA256(const void* pin, void* pout, const void* pinit, unsigned int hash[8][NPAR], const void* init2);
2617 printf("BitcoinMiner started\n");
2618 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2622 CBigNum bnExtraNonce = 0;
2623 while (fGenerateBitcoins)
2628 while (vNodes.empty() || IsInitialBlockDownload())
2633 if (!fGenerateBitcoins)
2637 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2638 CBlockIndex* pindexPrev = pindexBest;
2639 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2643 // Create coinbase tx
2646 txNew.vin.resize(1);
2647 txNew.vin[0].prevout.SetNull();
2648 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
2649 txNew.vout.resize(1);
2650 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
2656 auto_ptr<CBlock> pblock(new CBlock());
2660 // Add our coinbase tx as first transaction
2661 pblock->vtx.push_back(txNew);
2663 // Collect the latest transactions into the block
2665 CRITICAL_BLOCK(cs_main)
2666 CRITICAL_BLOCK(cs_mapTransactions)
2669 map<uint256, CTxIndex> mapTestPool;
2670 vector<char> vfAlreadyAdded(mapTransactions.size());
2671 bool fFoundSomething = true;
2672 unsigned int nBlockSize = 0;
2673 while (fFoundSomething && nBlockSize < MAX_SIZE/2)
2675 fFoundSomething = false;
2677 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
2679 if (vfAlreadyAdded[n])
2681 CTransaction& tx = (*mi).second;
2682 if (tx.IsCoinBase() || !tx.IsFinal())
2684 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2685 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)
2688 // Transaction fee based on block size
2689 int64 nMinFee = tx.GetMinFee(nBlockSize);
2691 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2692 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2694 swap(mapTestPool, mapTestPoolTmp);
2696 pblock->vtx.push_back(tx);
2697 nBlockSize += nTxSize;
2698 vfAlreadyAdded[n] = true;
2699 fFoundSomething = true;
2703 pblock->nBits = nBits;
2704 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(pindexPrev->nHeight+1, nFees);
2705 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2709 // Prebuild hash buffer
2716 uint256 hashPrevBlock;
2717 uint256 hashMerkleRoot;
2720 unsigned int nNonce;
2723 unsigned char pchPadding0[64];
2725 unsigned char pchPadding1[64];
2727 char tmpbuf[sizeof(tmpworkspace)+16];
2728 tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
2730 tmp.block.nVersion = pblock->nVersion;
2731 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
2732 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2733 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
2734 tmp.block.nBits = pblock->nBits = nBits;
2735 tmp.block.nNonce = pblock->nNonce = 0;
2737 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2738 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2740 // Byte swap all the input buffer
2741 for (int i = 0; i < sizeof(tmp)/4; i++)
2742 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2744 // Precalc the first half of the first hash, which stays constant
2745 uint256 midstatebuf[2];
2746 uint256& midstate = *alignup<16>(midstatebuf);
2747 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
2753 bool f4WaySSE2 = mapArgs.count("-4way");
2754 int64 nStart = GetTime();
2755 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2757 uint256& hash = *alignup<16>(hashbuf);
2763 // tcatm's 4-way SSE2 SHA-256
2764 tmp.block.nNonce += NPAR;
2765 unsigned int thashbuf[9][NPAR];
2766 unsigned int (&thash)[9][NPAR] = *alignup<16>(&thashbuf);
2767 Double_BlockSHA256((char*)&tmp.block + 64, &tmp.hash1, &midstate, thash, pSHA256InitState);
2768 ((unsigned short*)&hash)[14] = 0xffff;
2769 for (int j = 0; j < NPAR; j++)
2771 if (thash[7][j] == 0)
2773 for (int i = 0; i < sizeof(hash)/4; i++)
2774 ((unsigned int*)&hash)[i] = thash[i][j];
2775 pblock->nNonce = ByteReverse(tmp.block.nNonce + j);
2784 SHA256Transform(&tmp.hash1, (char*)&tmp.block + 64, &midstate);
2785 SHA256Transform(&hash, &tmp.hash1, pSHA256InitState);
2788 if (((unsigned short*)&hash)[14] == 0)
2790 // Byte swap the result after preliminary check
2791 for (int i = 0; i < sizeof(hash)/4; i++)
2792 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
2794 if (hash <= hashTarget)
2799 pblock->nNonce = ByteReverse(tmp.block.nNonce);
2800 assert(hash == pblock->GetHash());
2803 printf("BitcoinMiner:\n");
2804 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2806 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2807 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2809 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2810 CRITICAL_BLOCK(cs_main)
2812 if (pindexPrev == pindexBest)
2819 // Track how many getdata requests this block gets
2820 CRITICAL_BLOCK(cs_mapRequestCount)
2821 mapRequestCount[pblock->GetHash()] = 0;
2823 // Process this block the same as if we had received it from another node
2824 if (!ProcessBlock(NULL, pblock.release()))
2825 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
2828 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2835 // Update nTime every few seconds
2836 const unsigned int nMask = 0xffff;
2837 const int nHashesPerCycle = (nMask+1);
2838 if ((tmp.block.nNonce & nMask) == 0)
2841 static int nCycleCounter;
2842 if (nHPSTimerStart == 0)
2844 nHPSTimerStart = GetTimeMillis();
2849 if (GetTimeMillis() - nHPSTimerStart > 4000)
2851 static CCriticalSection cs;
2854 if (GetTimeMillis() - nHPSTimerStart > 4000)
2856 dHashesPerSec = 1000.0 * nHashesPerCycle * nCycleCounter / (GetTimeMillis() - nHPSTimerStart);
2857 nHPSTimerStart = GetTimeMillis();
2859 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
2860 UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));
2861 static int64 nLogTime;
2862 if (GetTime() - nLogTime > 30 * 60)
2864 nLogTime = GetTime();
2865 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2866 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
2872 // Check for stop or if block needs to be rebuilt
2875 if (!fGenerateBitcoins)
2877 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
2881 if (tmp.block.nNonce == 0)
2883 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2885 if (pindexPrev != pindexBest)
2888 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2889 tmp.block.nTime = ByteReverse(pblock->nTime);
2912 //////////////////////////////////////////////////////////////////////////////
2920 int64 nStart = GetTimeMillis();
2923 CRITICAL_BLOCK(cs_mapWallet)
2925 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2927 CWalletTx* pcoin = &(*it).second;
2928 if (!pcoin->IsFinal() || pcoin->fSpent)
2930 nTotal += pcoin->GetCredit(true);
2934 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
2939 int GetRandInt(int nMax)
2941 return GetRand(nMax);
2944 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
2946 setCoinsRet.clear();
2948 // List of values less than target
2949 int64 nLowestLarger = INT64_MAX;
2950 CWalletTx* pcoinLowestLarger = NULL;
2951 vector<pair<int64, CWalletTx*> > vValue;
2952 int64 nTotalLower = 0;
2954 CRITICAL_BLOCK(cs_mapWallet)
2956 vector<CWalletTx*> vCoins;
2957 vCoins.reserve(mapWallet.size());
2958 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2959 vCoins.push_back(&(*it).second);
2960 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2962 foreach(CWalletTx* pcoin, vCoins)
2964 if (!pcoin->IsFinal() || pcoin->fSpent)
2966 int64 n = pcoin->GetCredit();
2969 if (n < nTargetValue)
2971 vValue.push_back(make_pair(n, pcoin));
2974 else if (n == nTargetValue)
2976 setCoinsRet.insert(pcoin);
2979 else if (n < nLowestLarger)
2982 pcoinLowestLarger = pcoin;
2987 if (nTotalLower < nTargetValue)
2989 if (pcoinLowestLarger == NULL)
2991 setCoinsRet.insert(pcoinLowestLarger);
2995 // Solve subset sum by stochastic approximation
2996 sort(vValue.rbegin(), vValue.rend());
2997 vector<char> vfIncluded;
2998 vector<char> vfBest(vValue.size(), true);
2999 int64 nBest = nTotalLower;
3001 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3003 vfIncluded.assign(vValue.size(), false);
3005 bool fReachedTarget = false;
3006 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3008 for (int i = 0; i < vValue.size(); i++)
3010 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3012 nTotal += vValue[i].first;
3013 vfIncluded[i] = true;
3014 if (nTotal >= nTargetValue)
3016 fReachedTarget = true;
3020 vfBest = vfIncluded;
3022 nTotal -= vValue[i].first;
3023 vfIncluded[i] = false;
3030 // If the next larger is still closer, return it
3031 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3032 setCoinsRet.insert(pcoinLowestLarger);
3035 for (int i = 0; i < vValue.size(); i++)
3037 setCoinsRet.insert(vValue[i].second);
3040 printf("SelectCoins() best subset: ");
3041 for (int i = 0; i < vValue.size(); i++)
3043 printf("%s ", FormatMoney(vValue[i].first).c_str());
3044 printf("total %s\n", FormatMoney(nBest).c_str());
3053 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
3055 nFeeRequiredRet = 0;
3056 CRITICAL_BLOCK(cs_main)
3058 // txdb must be opened before the mapWallet lock
3060 CRITICAL_BLOCK(cs_mapWallet)
3062 int64 nFee = nTransactionFee;
3066 wtxNew.vout.clear();
3067 wtxNew.fFromMe = true;
3070 int64 nValueOut = nValue;
3071 int64 nTotalValue = nValue + nFee;
3073 // Choose coins to use
3074 set<CWalletTx*> setCoins;
3075 if (!SelectCoins(nTotalValue, setCoins))
3078 foreach(CWalletTx* pcoin, setCoins)
3079 nValueIn += pcoin->GetCredit();
3081 // Fill a vout to the payee
3082 bool fChangeFirst = GetRand(2);
3084 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3086 // Fill a vout back to self with any change
3087 if (nValueIn > nTotalValue)
3089 // Note: We use a new key here to keep it from being obvious which side is the change.
3090 // The drawback is that by not reusing a previous key, the change may be lost if a
3091 // backup is restored, if the backup doesn't have the new private key for the change.
3092 // If we reused the old key, it would be possible to add code to look for and
3093 // rediscover unknown transactions that were written with keys of ours to recover
3094 // post-backup change.
3097 if (keyRet.IsNull())
3098 keyRet.MakeNewKey();
3100 // Fill a vout to ourself, using same address type as the payment
3101 CScript scriptChange;
3102 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3103 scriptChange.SetBitcoinAddress(keyRet.GetPubKey());
3105 scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;
3106 wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));
3109 // Fill a vout to the payee
3111 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3114 foreach(CWalletTx* pcoin, setCoins)
3115 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3116 if (pcoin->vout[nOut].IsMine())
3117 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3121 foreach(CWalletTx* pcoin, setCoins)
3122 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3123 if (pcoin->vout[nOut].IsMine())
3124 if (!SignSignature(*pcoin, wtxNew, nIn++))
3127 // Check that enough fee is included
3128 if (nFee < wtxNew.GetMinFee())
3130 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3134 // Fill vtxPrev by copying from previous transactions vtxPrev
3135 wtxNew.AddSupportingTransactions(txdb);
3136 wtxNew.fTimeReceivedIsTxTime = true;
3145 // Call after CreateTransaction unless you want to abort
3146 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)
3148 CRITICAL_BLOCK(cs_main)
3150 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3151 CRITICAL_BLOCK(cs_mapWallet)
3153 // This is only to keep the database open to defeat the auto-flush for the
3154 // duration of this scope. This is the only place where this optimization
3155 // maybe makes sense; please don't do it anywhere else.
3156 CWalletDB walletdb("r");
3158 // Add the change's private key to wallet
3159 if (!key.IsNull() && !AddKey(key))
3160 throw runtime_error("CommitTransaction() : AddKey failed\n");
3162 // Add tx to wallet, because if it has change it's also ours,
3163 // otherwise just for transaction history.
3164 AddToWallet(wtxNew);
3166 // Mark old coins as spent
3167 set<CWalletTx*> setCoins;
3168 foreach(const CTxIn& txin, wtxNew.vin)
3169 setCoins.insert(&mapWallet[txin.prevout.hash]);
3170 foreach(CWalletTx* pcoin, setCoins)
3172 pcoin->fSpent = true;
3173 pcoin->WriteToDisk();
3174 vWalletUpdated.push_back(pcoin->GetHash());
3178 // Track how many getdata requests our transaction gets
3179 CRITICAL_BLOCK(cs_mapRequestCount)
3180 mapRequestCount[wtxNew.GetHash()] = 0;
3183 if (!wtxNew.AcceptTransaction())
3185 // This must not fail. The transaction has already been signed and recorded.
3186 printf("CommitTransaction() : Error: Transaction not valid");
3189 wtxNew.RelayWalletTransaction();
3198 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3200 CRITICAL_BLOCK(cs_main)
3204 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
3207 if (nValue + nFeeRequired > GetBalance())
3208 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3210 strError = _("Error: Transaction creation failed ");
3211 printf("SendMoney() : %s", strError.c_str());
3215 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3218 if (!CommitTransaction(wtxNew, key))
3219 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.");
3227 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3231 return _("Invalid amount");
3232 if (nValue + nTransactionFee > GetBalance())
3233 return _("Insufficient funds");
3235 // Parse bitcoin address
3236 CScript scriptPubKey;
3237 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3238 return _("Invalid bitcoin address");
3240 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);