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");
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::AcceptToMemoryPool(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("AcceptToMemoryPool() : coinbase as individual tx");
499 if (!CheckTransaction())
500 return error("AcceptToMemoryPool() : CheckTransaction failed");
502 // To help v0.1.5 clients who would see it as a negative number
503 if ((int64)nLockTime > INT_MAX)
504 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
506 // Rather not work on nonstandard transactions
507 if (GetSigOpCount() > 2 || ::GetSerializeSize(*this, SER_NETWORK) < 100)
508 return error("AcceptToMemoryPool() : nonstandard transaction");
510 // Do we already have it?
511 uint256 hash = GetHash();
512 CRITICAL_BLOCK(cs_mapTransactions)
513 if (mapTransactions.count(hash))
516 if (txdb.ContainsTx(hash))
519 // Check for conflicts with in-memory transactions
520 CTransaction* ptxOld = NULL;
521 for (int i = 0; i < vin.size(); i++)
523 COutPoint outpoint = vin[i].prevout;
524 if (mapNextTx.count(outpoint))
526 // Disable replacement feature for now
529 // Allow replacing with a newer version of the same transaction
532 ptxOld = mapNextTx[outpoint].ptx;
533 if (!IsNewerThan(*ptxOld))
535 for (int i = 0; i < vin.size(); i++)
537 COutPoint outpoint = vin[i].prevout;
538 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
545 // Check against previous transactions
546 map<uint256, CTxIndex> mapUnused;
548 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
551 *pfMissingInputs = true;
552 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());
555 // Store transaction in memory
556 CRITICAL_BLOCK(cs_mapTransactions)
560 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
561 ptxOld->RemoveFromMemoryPool();
563 AddToMemoryPoolUnchecked();
566 ///// are we sure this is ok when loading transactions or restoring block txes
567 // If updated, erase old tx from wallet
569 EraseFromWallet(ptxOld->GetHash());
571 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,6).c_str());
576 bool CTransaction::AddToMemoryPoolUnchecked()
578 // Add to memory pool without checking anything. Don't call this directly,
579 // call AcceptToMemoryPool to properly check the transaction first.
580 CRITICAL_BLOCK(cs_mapTransactions)
582 uint256 hash = GetHash();
583 mapTransactions[hash] = *this;
584 for (int i = 0; i < vin.size(); i++)
585 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
586 nTransactionsUpdated++;
592 bool CTransaction::RemoveFromMemoryPool()
594 // Remove transaction from memory pool
595 CRITICAL_BLOCK(cs_mapTransactions)
597 foreach(const CTxIn& txin, vin)
598 mapNextTx.erase(txin.prevout);
599 mapTransactions.erase(GetHash());
600 nTransactionsUpdated++;
610 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
612 if (hashBlock == 0 || nIndex == -1)
615 // Find the block it claims to be in
616 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
617 if (mi == mapBlockIndex.end())
619 CBlockIndex* pindex = (*mi).second;
620 if (!pindex || !pindex->IsInMainChain())
623 // Make sure the merkle branch connects to this block
624 if (!fMerkleVerified)
626 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
628 fMerkleVerified = true;
631 nHeightRet = pindex->nHeight;
632 return pindexBest->nHeight - pindex->nHeight + 1;
636 int CMerkleTx::GetBlocksToMaturity() const
640 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
644 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
648 if (!IsInMainChain() && !ClientConnectInputs())
650 return CTransaction::AcceptToMemoryPool(txdb, false);
654 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
660 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
662 CRITICAL_BLOCK(cs_mapTransactions)
664 // Add previous supporting transactions first
665 foreach(CMerkleTx& tx, vtxPrev)
667 if (!tx.IsCoinBase())
669 uint256 hash = tx.GetHash();
670 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
671 tx.AcceptToMemoryPool(txdb, fCheckInputs);
674 return AcceptToMemoryPool(txdb, fCheckInputs);
679 void ReacceptWalletTransactions()
682 CRITICAL_BLOCK(cs_mapWallet)
684 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
686 CWalletTx& wtx = item.second;
687 if (wtx.fSpent && wtx.IsCoinBase())
691 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
693 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
696 if (txindex.vSpent.size() != wtx.vout.size())
698 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
701 for (int i = 0; i < txindex.vSpent.size(); i++)
703 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
705 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
715 // Reaccept any txes of ours that aren't already in a block
716 if (!wtx.IsCoinBase())
717 wtx.AcceptWalletTransaction(txdb, false);
724 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
726 foreach(const CMerkleTx& tx, vtxPrev)
728 if (!tx.IsCoinBase())
730 uint256 hash = tx.GetHash();
731 if (!txdb.ContainsTx(hash))
732 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
737 uint256 hash = GetHash();
738 if (!txdb.ContainsTx(hash))
740 printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());
741 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
746 void ResendWalletTransactions()
748 // Do this infrequently and randomly to avoid giving away
749 // that these are our transactions.
750 static int64 nNextTime;
751 if (GetTime() < nNextTime)
753 bool fFirst = (nNextTime == 0);
754 nNextTime = GetTime() + GetRand(30 * 60);
758 // Only do it if there's been a new block since last time
759 static int64 nLastTime;
760 if (nTimeBestReceived < nLastTime)
762 nLastTime = GetTime();
764 // Rebroadcast any of our txes that aren't in a block yet
765 printf("ResendWalletTransactions()\n");
767 CRITICAL_BLOCK(cs_mapWallet)
769 // Sort them in chronological order
770 multimap<unsigned int, CWalletTx*> mapSorted;
771 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
773 CWalletTx& wtx = item.second;
774 // Don't rebroadcast until it's had plenty of time that
775 // it should have gotten in already by now.
776 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
777 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
779 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
781 CWalletTx& wtx = *item.second;
782 wtx.RelayWalletTransaction(txdb);
796 //////////////////////////////////////////////////////////////////////////////
798 // CBlock and CBlockIndex
801 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
803 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
805 if (GetHash() != pindex->GetBlockHash())
806 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
810 uint256 GetOrphanRoot(const CBlock* pblock)
812 // Work back to the first block in the orphan chain
813 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
814 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
815 return pblock->GetHash();
818 int64 CBlock::GetBlockValue(int nHeight, int64 nFees) const
820 int64 nSubsidy = 50 * COIN;
822 // Subsidy is cut in half every 4 years
823 nSubsidy >>= (nHeight / 210000);
825 return nSubsidy + nFees;
828 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
830 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
831 const int64 nTargetSpacing = 10 * 60;
832 const int64 nInterval = nTargetTimespan / nTargetSpacing;
835 if (pindexLast == NULL)
836 return bnProofOfWorkLimit.GetCompact();
838 // Only change once per interval
839 if ((pindexLast->nHeight+1) % nInterval != 0)
840 return pindexLast->nBits;
842 // Go back by what we want to be 14 days worth of blocks
843 const CBlockIndex* pindexFirst = pindexLast;
844 for (int i = 0; pindexFirst && i < nInterval-1; i++)
845 pindexFirst = pindexFirst->pprev;
848 // Limit adjustment step
849 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
850 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
851 if (nActualTimespan < nTargetTimespan/4)
852 nActualTimespan = nTargetTimespan/4;
853 if (nActualTimespan > nTargetTimespan*4)
854 nActualTimespan = nTargetTimespan*4;
858 bnNew.SetCompact(pindexLast->nBits);
859 bnNew *= nActualTimespan;
860 bnNew /= nTargetTimespan;
862 if (bnNew > bnProofOfWorkLimit)
863 bnNew = bnProofOfWorkLimit;
866 printf("GetNextWorkRequired RETARGET\n");
867 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
868 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
869 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
871 return bnNew.GetCompact();
874 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
877 bnTarget.SetCompact(nBits);
880 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
881 return error("CheckProofOfWork() : nBits below minimum work");
883 // Check proof of work matches claimed amount
884 if (hash > bnTarget.getuint256())
885 return error("CheckProofOfWork() : hash doesn't match nBits");
890 bool IsInitialBlockDownload()
892 if (pindexBest == NULL)
894 static int64 nLastUpdate;
895 static CBlockIndex* pindexLastBest;
896 if (pindexBest != pindexLastBest)
898 pindexLastBest = pindexBest;
899 nLastUpdate = GetTime();
901 return (GetTime() - nLastUpdate < 10 &&
902 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
905 void InvalidChainFound(CBlockIndex* pindexNew)
907 if (pindexNew->bnChainWork > bnBestInvalidWork)
909 bnBestInvalidWork = pindexNew->bnChainWork;
910 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
913 printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
914 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
915 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
916 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
929 bool CTransaction::DisconnectInputs(CTxDB& txdb)
931 // Relinquish previous transactions' spent pointers
934 foreach(const CTxIn& txin, vin)
936 COutPoint prevout = txin.prevout;
938 // Get prev txindex from disk
940 if (!txdb.ReadTxIndex(prevout.hash, txindex))
941 return error("DisconnectInputs() : ReadTxIndex failed");
943 if (prevout.n >= txindex.vSpent.size())
944 return error("DisconnectInputs() : prevout.n out of range");
946 // Mark outpoint as not spent
947 txindex.vSpent[prevout.n].SetNull();
950 txdb.UpdateTxIndex(prevout.hash, txindex);
954 // Remove transaction from index
955 if (!txdb.EraseTxIndex(*this))
956 return error("DisconnectInputs() : EraseTxPos failed");
962 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
963 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
965 // Take over previous transactions' spent pointers
969 for (int i = 0; i < vin.size(); i++)
971 COutPoint prevout = vin[i].prevout;
976 if (fMiner && mapTestPool.count(prevout.hash))
978 // Get txindex from current proposed changes
979 txindex = mapTestPool[prevout.hash];
983 // Read txindex from txdb
984 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
986 if (!fFound && (fBlock || fMiner))
987 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());
991 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
993 // Get prev tx from single transactions in memory
994 CRITICAL_BLOCK(cs_mapTransactions)
996 if (!mapTransactions.count(prevout.hash))
997 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
998 txPrev = mapTransactions[prevout.hash];
1001 txindex.vSpent.resize(txPrev.vout.size());
1005 // Get prev tx from disk
1006 if (!txPrev.ReadFromDisk(txindex.pos))
1007 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
1010 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1011 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());
1013 // If prev is coinbase, check that it's matured
1014 if (txPrev.IsCoinBase())
1015 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1016 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1017 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1020 if (!VerifySignature(txPrev, *this, i))
1021 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
1023 // Check for conflicts
1024 if (!txindex.vSpent[prevout.n].IsNull())
1025 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());
1027 // Mark outpoints as spent
1028 txindex.vSpent[prevout.n] = posThisTx;
1032 txdb.UpdateTxIndex(prevout.hash, txindex);
1034 mapTestPool[prevout.hash] = txindex;
1036 nValueIn += txPrev.vout[prevout.n].nValue;
1038 // Check for negative or overflow input values
1039 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1040 return error("ConnectInputs() : txin values out of range");
1043 if (nValueIn < GetValueOut())
1044 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,6).c_str());
1046 // Tally transaction fees
1047 int64 nTxFee = nValueIn - GetValueOut();
1049 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
1050 if (nTxFee < nMinFee)
1053 if (!MoneyRange(nFees))
1054 return error("ConnectInputs() : nFees out of range");
1059 // Add transaction to disk index
1060 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1061 return error("ConnectInputs() : AddTxPos failed");
1065 // Add transaction to test pool
1066 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1073 bool CTransaction::ClientConnectInputs()
1078 // Take over previous transactions' spent pointers
1079 CRITICAL_BLOCK(cs_mapTransactions)
1082 for (int i = 0; i < vin.size(); i++)
1084 // Get prev tx from single transactions in memory
1085 COutPoint prevout = vin[i].prevout;
1086 if (!mapTransactions.count(prevout.hash))
1088 CTransaction& txPrev = mapTransactions[prevout.hash];
1090 if (prevout.n >= txPrev.vout.size())
1094 if (!VerifySignature(txPrev, *this, i))
1095 return error("ConnectInputs() : VerifySignature failed");
1097 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1098 ///// this has to go away now that posNext is gone
1099 // // Check for conflicts
1100 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1101 // return error("ConnectInputs() : prev tx already used");
1103 // // Flag outpoints as used
1104 // txPrev.vout[prevout.n].posNext = posThisTx;
1106 nValueIn += txPrev.vout[prevout.n].nValue;
1108 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1109 return error("ClientConnectInputs() : txin values out of range");
1111 if (GetValueOut() > nValueIn)
1121 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1123 // Disconnect in reverse order
1124 for (int i = vtx.size()-1; i >= 0; i--)
1125 if (!vtx[i].DisconnectInputs(txdb))
1128 // Update block index on disk without changing it in memory.
1129 // The memory index structure will be changed after the db commits.
1132 CDiskBlockIndex blockindexPrev(pindex->pprev);
1133 blockindexPrev.hashNext = 0;
1134 txdb.WriteBlockIndex(blockindexPrev);
1140 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1142 // Check it again in case a previous version let a bad block in
1146 //// issue here: it doesn't know the version
1147 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1149 map<uint256, CTxIndex> mapUnused;
1151 foreach(CTransaction& tx, vtx)
1153 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1154 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1156 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1160 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1163 // Update block index on disk without changing it in memory.
1164 // The memory index structure will be changed after the db commits.
1167 CDiskBlockIndex blockindexPrev(pindex->pprev);
1168 blockindexPrev.hashNext = pindex->GetBlockHash();
1169 txdb.WriteBlockIndex(blockindexPrev);
1172 // Watch for transactions paying to me
1173 foreach(CTransaction& tx, vtx)
1174 AddToWalletIfMine(tx, this);
1181 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1183 printf("REORGANIZE\n");
1186 CBlockIndex* pfork = pindexBest;
1187 CBlockIndex* plonger = pindexNew;
1188 while (pfork != plonger)
1190 while (plonger->nHeight > pfork->nHeight)
1191 if (!(plonger = plonger->pprev))
1192 return error("Reorganize() : plonger->pprev is null");
1193 if (pfork == plonger)
1195 if (!(pfork = pfork->pprev))
1196 return error("Reorganize() : pfork->pprev is null");
1199 // List of what to disconnect
1200 vector<CBlockIndex*> vDisconnect;
1201 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1202 vDisconnect.push_back(pindex);
1204 // List of what to connect
1205 vector<CBlockIndex*> vConnect;
1206 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1207 vConnect.push_back(pindex);
1208 reverse(vConnect.begin(), vConnect.end());
1210 // Disconnect shorter branch
1211 vector<CTransaction> vResurrect;
1212 foreach(CBlockIndex* pindex, vDisconnect)
1215 if (!block.ReadFromDisk(pindex))
1216 return error("Reorganize() : ReadFromDisk for disconnect failed");
1217 if (!block.DisconnectBlock(txdb, pindex))
1218 return error("Reorganize() : DisconnectBlock failed");
1220 // Queue memory transactions to resurrect
1221 foreach(const CTransaction& tx, block.vtx)
1222 if (!tx.IsCoinBase())
1223 vResurrect.push_back(tx);
1226 // Connect longer branch
1227 vector<CTransaction> vDelete;
1228 for (int i = 0; i < vConnect.size(); i++)
1230 CBlockIndex* pindex = vConnect[i];
1232 if (!block.ReadFromDisk(pindex))
1233 return error("Reorganize() : ReadFromDisk for connect failed");
1234 if (!block.ConnectBlock(txdb, pindex))
1238 return error("Reorganize() : ConnectBlock failed");
1241 // Queue memory transactions to delete
1242 foreach(const CTransaction& tx, block.vtx)
1243 vDelete.push_back(tx);
1245 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1246 return error("Reorganize() : WriteHashBestChain failed");
1248 // Commit now because resurrecting could take some time
1251 // Disconnect shorter branch
1252 foreach(CBlockIndex* pindex, vDisconnect)
1254 pindex->pprev->pnext = NULL;
1256 // Connect longer branch
1257 foreach(CBlockIndex* pindex, vConnect)
1259 pindex->pprev->pnext = pindex;
1261 // Resurrect memory transactions that were in the disconnected branch
1262 foreach(CTransaction& tx, vResurrect)
1263 tx.AcceptToMemoryPool(txdb, false);
1265 // Delete redundant memory transactions that are in the connected branch
1266 foreach(CTransaction& tx, vDelete)
1267 tx.RemoveFromMemoryPool();
1273 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1275 uint256 hash = GetHash();
1278 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1280 pindexGenesisBlock = pindexNew;
1281 txdb.WriteHashBestChain(hash);
1283 else if (hashPrevBlock == hashBestChain)
1285 // Adding to current best branch
1286 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1289 InvalidChainFound(pindexNew);
1290 return error("SetBestChain() : ConnectBlock failed");
1293 pindexNew->pprev->pnext = pindexNew;
1295 // Delete redundant memory transactions
1296 foreach(CTransaction& tx, vtx)
1297 tx.RemoveFromMemoryPool();
1302 if (!Reorganize(txdb, pindexNew))
1305 InvalidChainFound(pindexNew);
1306 return error("SetBestChain() : Reorganize failed");
1312 hashBestChain = hash;
1313 pindexBest = pindexNew;
1314 nBestHeight = pindexBest->nHeight;
1315 bnBestChainWork = pindexNew->bnChainWork;
1316 nTimeBestReceived = GetTime();
1317 nTransactionsUpdated++;
1318 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1324 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1326 // Check for duplicate
1327 uint256 hash = GetHash();
1328 if (mapBlockIndex.count(hash))
1329 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1331 // Construct new block index object
1332 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1334 return error("AddToBlockIndex() : new CBlockIndex failed");
1335 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1336 pindexNew->phashBlock = &((*mi).first);
1337 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1338 if (miPrev != mapBlockIndex.end())
1340 pindexNew->pprev = (*miPrev).second;
1341 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1343 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1346 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1349 if (pindexNew->bnChainWork > bnBestChainWork)
1350 if (!SetBestChain(txdb, pindexNew))
1355 if (pindexNew == pindexBest)
1357 // Notify UI to display prev block's coinbase if it was ours
1358 static uint256 hashPrevBestCoinBase;
1359 CRITICAL_BLOCK(cs_mapWallet)
1360 vWalletUpdated.push_back(hashPrevBestCoinBase);
1361 hashPrevBestCoinBase = vtx[0].GetHash();
1371 bool CBlock::CheckBlock() const
1373 // These are checks that are independent of context
1374 // that can be verified before saving an orphan block.
1377 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_SIZE)
1378 return error("CheckBlock() : size limits failed");
1381 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1382 return error("CheckBlock() : block timestamp too far in the future");
1384 // First transaction must be coinbase, the rest must not be
1385 if (vtx.empty() || !vtx[0].IsCoinBase())
1386 return error("CheckBlock() : first tx is not coinbase");
1387 for (int i = 1; i < vtx.size(); i++)
1388 if (vtx[i].IsCoinBase())
1389 return error("CheckBlock() : more than one coinbase");
1391 // Check transactions
1392 foreach(const CTransaction& tx, vtx)
1393 if (!tx.CheckTransaction())
1394 return error("CheckBlock() : CheckTransaction failed");
1396 // Check proof of work matches claimed amount
1397 if (!CheckProofOfWork(GetHash(), nBits))
1398 return error("CheckBlock() : proof of work failed");
1401 if (hashMerkleRoot != BuildMerkleTree())
1402 return error("CheckBlock() : hashMerkleRoot mismatch");
1407 bool CBlock::AcceptBlock()
1409 // Check for duplicate
1410 uint256 hash = GetHash();
1411 if (mapBlockIndex.count(hash))
1412 return error("AcceptBlock() : block already in mapBlockIndex");
1414 // Get prev block index
1415 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1416 if (mi == mapBlockIndex.end())
1417 return error("AcceptBlock() : prev block not found");
1418 CBlockIndex* pindexPrev = (*mi).second;
1419 int nHeight = pindexPrev->nHeight+1;
1422 if (nHeight > 79400 && ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1423 return error("AcceptBlock() : over size limit");
1425 // Check that it's not full of nonstandard transactions
1426 if (nHeight > 79400 && GetSigOpCount() > MAX_BLOCK_SIGOPS)
1427 return error("AcceptBlock() : too many nonstandard transactions");
1429 // Check timestamp against prev
1430 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1431 return error("AcceptBlock() : block's timestamp is too early");
1433 // Check that all transactions are finalized
1434 foreach(const CTransaction& tx, vtx)
1435 if (!tx.IsFinal(nHeight, GetBlockTime()))
1436 return error("AcceptBlock() : contains a non-final transaction");
1438 // Check proof of work
1439 if (nBits != GetNextWorkRequired(pindexPrev))
1440 return error("AcceptBlock() : incorrect proof of work");
1442 // Check that the block chain matches the known block chain up to a checkpoint
1443 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1444 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1445 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1446 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1447 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1448 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1450 // Scanback checkpoint lockin
1451 for (CBlockIndex* pindex = pindexPrev; pindex->nHeight >= 74000; pindex = pindex->pprev)
1453 if (pindex->nHeight == 74000 && pindex->GetBlockHash() != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
1454 return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);
1455 if (pindex->nHeight == 74638 && pindex->GetBlockHash() == uint256("0x0000000000790ab3f22ec756ad43b6ab569abf0bddeb97c67a6f7b1470a7ec1c"))
1456 return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);
1459 // Write block to history file
1460 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1461 return error("AcceptBlock() : out of disk space");
1463 unsigned int nBlockPos;
1464 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1465 return error("AcceptBlock() : WriteToDisk failed");
1466 if (!AddToBlockIndex(nFile, nBlockPos))
1467 return error("AcceptBlock() : AddToBlockIndex failed");
1469 // Relay inventory, but don't relay old inventory during initial block download
1470 if (hashBestChain == hash)
1471 CRITICAL_BLOCK(cs_vNodes)
1472 foreach(CNode* pnode, vNodes)
1473 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1474 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1479 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1481 // Check for duplicate
1482 uint256 hash = pblock->GetHash();
1483 if (mapBlockIndex.count(hash))
1484 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1485 if (mapOrphanBlocks.count(hash))
1486 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1488 // Preliminary checks
1489 if (!pblock->CheckBlock())
1492 return error("ProcessBlock() : CheckBlock FAILED");
1495 // If don't already have its previous block, shunt it off to holding area until we get it
1496 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1498 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1499 mapOrphanBlocks.insert(make_pair(hash, pblock));
1500 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1502 // Ask this guy to fill in what we're missing
1504 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1509 if (!pblock->AcceptBlock())
1512 return error("ProcessBlock() : AcceptBlock FAILED");
1516 // Recursively process any orphan blocks that depended on this one
1517 vector<uint256> vWorkQueue;
1518 vWorkQueue.push_back(hash);
1519 for (int i = 0; i < vWorkQueue.size(); i++)
1521 uint256 hashPrev = vWorkQueue[i];
1522 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1523 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1526 CBlock* pblockOrphan = (*mi).second;
1527 if (pblockOrphan->AcceptBlock())
1528 vWorkQueue.push_back(pblockOrphan->GetHash());
1529 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1530 delete pblockOrphan;
1532 mapOrphanBlocksByPrev.erase(hashPrev);
1535 printf("ProcessBlock: ACCEPTED\n");
1546 template<typename Stream>
1547 bool ScanMessageStart(Stream& s)
1549 // Scan ahead to the next pchMessageStart, which should normally be immediately
1550 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1552 short prevmask = s.exceptions(0);
1553 const char* p = BEGIN(pchMessageStart);
1563 s.exceptions(prevmask);
1567 p = BEGIN(pchMessageStart);
1570 if (++p == END(pchMessageStart))
1573 s.exceptions(prevmask);
1582 s.exceptions(prevmask);
1587 bool CheckDiskSpace(uint64 nAdditionalBytes)
1589 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1591 // Check for 15MB because database could create another 10MB log file at any time
1592 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1595 string strMessage = _("Warning: Disk space is low ");
1596 strMiscWarning = strMessage;
1597 printf("*** %s\n", strMessage.c_str());
1598 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1599 CreateThread(Shutdown, NULL);
1605 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1609 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1612 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1614 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1623 static unsigned int nCurrentBlockFile = 1;
1625 FILE* AppendBlockFile(unsigned int& nFileRet)
1630 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1633 if (fseek(file, 0, SEEK_END) != 0)
1635 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1636 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1638 nFileRet = nCurrentBlockFile;
1642 nCurrentBlockFile++;
1646 bool LoadBlockIndex(bool fAllowNew)
1652 if (!txdb.LoadBlockIndex())
1657 // Init with genesis block
1659 if (mapBlockIndex.empty())
1665 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1666 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1667 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1668 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1669 // vMerkleTree: 4a5e1e
1672 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1674 txNew.vin.resize(1);
1675 txNew.vout.resize(1);
1676 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1677 txNew.vout[0].nValue = 50 * COIN;
1678 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1680 block.vtx.push_back(txNew);
1681 block.hashPrevBlock = 0;
1682 block.hashMerkleRoot = block.BuildMerkleTree();
1684 block.nTime = 1231006505;
1685 block.nBits = 0x1d00ffff;
1686 block.nNonce = 2083236893;
1689 printf("%s\n", block.GetHash().ToString().c_str());
1690 printf("%s\n", hashGenesisBlock.ToString().c_str());
1691 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1692 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1695 assert(block.GetHash() == hashGenesisBlock);
1697 // Start new block file
1699 unsigned int nBlockPos;
1700 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1701 return error("LoadBlockIndex() : writing genesis block to disk failed");
1702 if (!block.AddToBlockIndex(nFile, nBlockPos))
1703 return error("LoadBlockIndex() : genesis block not accepted");
1711 void PrintBlockTree()
1713 // precompute tree structure
1714 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1715 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1717 CBlockIndex* pindex = (*mi).second;
1718 mapNext[pindex->pprev].push_back(pindex);
1720 //while (rand() % 3 == 0)
1721 // mapNext[pindex->pprev].push_back(pindex);
1724 vector<pair<int, CBlockIndex*> > vStack;
1725 vStack.push_back(make_pair(0, pindexGenesisBlock));
1728 while (!vStack.empty())
1730 int nCol = vStack.back().first;
1731 CBlockIndex* pindex = vStack.back().second;
1734 // print split or gap
1735 if (nCol > nPrevCol)
1737 for (int i = 0; i < nCol-1; i++)
1741 else if (nCol < nPrevCol)
1743 for (int i = 0; i < nCol; i++)
1750 for (int i = 0; i < nCol; i++)
1755 block.ReadFromDisk(pindex);
1756 printf("%d (%u,%u) %s %s tx %d",
1760 block.GetHash().ToString().substr(0,20).c_str(),
1761 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1764 CRITICAL_BLOCK(cs_mapWallet)
1766 if (mapWallet.count(block.vtx[0].GetHash()))
1768 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1769 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1775 // put the main timechain first
1776 vector<CBlockIndex*>& vNext = mapNext[pindex];
1777 for (int i = 0; i < vNext.size(); i++)
1779 if (vNext[i]->pnext)
1781 swap(vNext[0], vNext[i]);
1787 for (int i = 0; i < vNext.size(); i++)
1788 vStack.push_back(make_pair(nCol+i, vNext[i]));
1801 //////////////////////////////////////////////////////////////////////////////
1806 map<uint256, CAlert> mapAlerts;
1807 CCriticalSection cs_mapAlerts;
1809 string GetWarnings(string strFor)
1812 string strStatusBar;
1814 if (mapArgs.count("-testsafemode"))
1817 // Misc warnings like out of disk space and clock is wrong
1818 if (strMiscWarning != "")
1821 strStatusBar = strMiscWarning;
1824 // Longer invalid proof-of-work chain
1825 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1828 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1832 CRITICAL_BLOCK(cs_mapAlerts)
1834 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1836 const CAlert& alert = item.second;
1837 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1839 nPriority = alert.nPriority;
1840 strStatusBar = alert.strStatusBar;
1841 strRPC = alert.strRPCError;
1846 if (strFor == "statusbar")
1847 return strStatusBar;
1848 else if (strFor == "rpc")
1850 assert(("GetWarnings() : invalid parameter", false));
1854 bool CAlert::ProcessAlert()
1856 if (!CheckSignature())
1861 CRITICAL_BLOCK(cs_mapAlerts)
1863 // Cancel previous alerts
1864 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1866 const CAlert& alert = (*mi).second;
1869 printf("cancelling alert %d\n", alert.nID);
1870 mapAlerts.erase(mi++);
1872 else if (!alert.IsInEffect())
1874 printf("expiring alert %d\n", alert.nID);
1875 mapAlerts.erase(mi++);
1881 // Check if this alert has been cancelled
1882 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1884 const CAlert& alert = item.second;
1885 if (alert.Cancels(*this))
1887 printf("alert already cancelled by %d\n", alert.nID);
1893 mapAlerts.insert(make_pair(GetHash(), *this));
1896 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1908 //////////////////////////////////////////////////////////////////////////////
1914 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1918 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1919 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1921 // Don't know what it is, just say we already got one
1931 bool ProcessMessages(CNode* pfrom)
1933 CDataStream& vRecv = pfrom->vRecv;
1937 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
1941 // (4) message start
1950 // Scan for message start
1951 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
1952 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
1953 if (vRecv.end() - pstart < nHeaderSize)
1955 if (vRecv.size() > nHeaderSize)
1957 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
1958 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
1962 if (pstart - vRecv.begin() > 0)
1963 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
1964 vRecv.erase(vRecv.begin(), pstart);
1967 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
1972 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
1975 string strCommand = hdr.GetCommand();
1978 unsigned int nMessageSize = hdr.nMessageSize;
1979 if (nMessageSize > MAX_SIZE)
1981 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
1984 if (nMessageSize > vRecv.size())
1986 // Rewind and wait for rest of message
1987 ///// need a mechanism to give up waiting for overlong message size error
1988 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
1992 // Copy message to its own buffer
1993 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
1994 vRecv.ignore(nMessageSize);
1997 if (vRecv.GetVersion() >= 209)
1999 uint256 hash = Hash(vMsg.begin(), vMsg.end());
2000 unsigned int nChecksum = 0;
2001 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2002 if (nChecksum != hdr.nChecksum)
2004 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2005 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2014 CRITICAL_BLOCK(cs_main)
2015 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2019 catch (std::ios_base::failure& e)
2021 if (strstr(e.what(), "end of data"))
2023 // Allow exceptions from underlength message on vRecv
2024 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2026 else if (strstr(e.what(), "size too large"))
2028 // Allow exceptions from overlong size
2029 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2033 PrintExceptionContinue(&e, "ProcessMessage()");
2036 catch (std::exception& e) {
2037 PrintExceptionContinue(&e, "ProcessMessage()");
2039 PrintExceptionContinue(NULL, "ProcessMessage()");
2043 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2053 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2055 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2056 RandAddSeedPerfmon();
2058 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2059 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2060 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2062 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2070 if (strCommand == "version")
2072 // Each connection can only send one version message
2073 if (pfrom->nVersion != 0)
2080 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2081 if (pfrom->nVersion == 10300)
2082 pfrom->nVersion = 300;
2083 if (pfrom->nVersion >= 106 && !vRecv.empty())
2084 vRecv >> addrFrom >> nNonce;
2085 if (pfrom->nVersion >= 106 && !vRecv.empty())
2086 vRecv >> pfrom->strSubVer;
2087 if (pfrom->nVersion >= 209 && !vRecv.empty())
2088 vRecv >> pfrom->nStartingHeight;
2090 if (pfrom->nVersion == 0)
2093 // Disconnect if we connected to ourself
2094 if (nNonce == nLocalHostNonce && nNonce > 1)
2096 pfrom->fDisconnect = true;
2100 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2103 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
2104 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
2107 AddTimeData(pfrom->addr.ip, nTime);
2110 if (pfrom->nVersion >= 209)
2111 pfrom->PushMessage("verack");
2112 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2113 if (pfrom->nVersion < 209)
2114 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2116 // Ask the first connected node for block updates
2117 static int nAskedForBlocks;
2118 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2121 pfrom->PushGetBlocks(pindexBest, uint256(0));
2125 CRITICAL_BLOCK(cs_mapAlerts)
2126 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2127 item.second.RelayTo(pfrom);
2129 pfrom->fSuccessfullyConnected = true;
2131 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2135 else if (pfrom->nVersion == 0)
2137 // Must have a version message before anything else
2142 else if (strCommand == "verack")
2144 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2148 else if (strCommand == "addr")
2150 vector<CAddress> vAddr;
2152 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
2154 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
2156 if (vAddr.size() > 1000)
2157 return error("message addr size() = %d", vAddr.size());
2159 // Store the new addresses
2160 foreach(CAddress& addr, vAddr)
2164 // ignore IPv6 for now, since it isn't implemented anyway
2167 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
2168 if (pfrom->fGetAddr || vAddr.size() > 10)
2169 addr.nTime -= 5 * 24 * 60 * 60;
2171 pfrom->AddAddressKnown(addr);
2172 if (!pfrom->fGetAddr && addr.IsRoutable())
2174 // Relay to a limited number of other nodes
2175 CRITICAL_BLOCK(cs_vNodes)
2177 // Use deterministic randomness to send to
2178 // the same places for 12 hours at a time
2179 static uint256 hashSalt;
2181 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2182 uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
2183 multimap<uint256, CNode*> mapMix;
2184 foreach(CNode* pnode, vNodes)
2185 mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
2186 int nRelayNodes = 2;
2187 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2188 ((*mi).second)->PushAddress(addr);
2192 if (vAddr.size() < 1000)
2193 pfrom->fGetAddr = false;
2197 else if (strCommand == "inv")
2201 if (vInv.size() > 50000)
2202 return error("message inv size() = %d", vInv.size());
2205 foreach(const CInv& inv, vInv)
2209 pfrom->AddInventoryKnown(inv);
2211 bool fAlreadyHave = AlreadyHave(txdb, inv);
2212 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2216 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2217 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2219 // Track requests for our stuff
2220 CRITICAL_BLOCK(cs_mapRequestCount)
2222 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2223 if (mi != mapRequestCount.end())
2230 else if (strCommand == "getdata")
2234 if (vInv.size() > 50000)
2235 return error("message getdata size() = %d", vInv.size());
2237 foreach(const CInv& inv, vInv)
2241 printf("received getdata for: %s\n", inv.ToString().c_str());
2243 if (inv.type == MSG_BLOCK)
2245 // Send block from disk
2246 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2247 if (mi != mapBlockIndex.end())
2249 //// could optimize this to send header straight from blockindex for client
2251 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2252 pfrom->PushMessage("block", block);
2254 // Trigger them to send a getblocks request for the next batch of inventory
2255 if (inv.hash == pfrom->hashContinue)
2257 // Bypass PushInventory, this must send even if redundant,
2258 // and we want it right after the last block so they don't
2259 // wait for other stuff first.
2261 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2262 pfrom->PushMessage("inv", vInv);
2263 pfrom->hashContinue = 0;
2267 else if (inv.IsKnownType())
2269 // Send stream from relay memory
2270 CRITICAL_BLOCK(cs_mapRelay)
2272 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2273 if (mi != mapRelay.end())
2274 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2278 // Track requests for our stuff
2279 CRITICAL_BLOCK(cs_mapRequestCount)
2281 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2282 if (mi != mapRequestCount.end())
2289 else if (strCommand == "getblocks")
2291 CBlockLocator locator;
2293 vRecv >> locator >> hashStop;
2295 // Find the first block the caller has in the main chain
2296 CBlockIndex* pindex = locator.GetBlockIndex();
2298 // Send the rest of the chain
2300 pindex = pindex->pnext;
2301 int nLimit = 500 + locator.GetDistanceBack();
2302 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2303 for (; pindex; pindex = pindex->pnext)
2305 if (pindex->GetBlockHash() == hashStop)
2307 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2310 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2313 // When this block is requested, we'll send an inv that'll make them
2314 // getblocks the next batch of inventory.
2315 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2316 pfrom->hashContinue = pindex->GetBlockHash();
2323 else if (strCommand == "tx")
2325 vector<uint256> vWorkQueue;
2326 CDataStream vMsg(vRecv);
2330 CInv inv(MSG_TX, tx.GetHash());
2331 pfrom->AddInventoryKnown(inv);
2333 bool fMissingInputs = false;
2334 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2336 AddToWalletIfMine(tx, NULL);
2337 RelayMessage(inv, vMsg);
2338 mapAlreadyAskedFor.erase(inv);
2339 vWorkQueue.push_back(inv.hash);
2341 // Recursively process any orphan transactions that depended on this one
2342 for (int i = 0; i < vWorkQueue.size(); i++)
2344 uint256 hashPrev = vWorkQueue[i];
2345 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2346 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2349 const CDataStream& vMsg = *((*mi).second);
2351 CDataStream(vMsg) >> tx;
2352 CInv inv(MSG_TX, tx.GetHash());
2354 if (tx.AcceptToMemoryPool(true))
2356 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2357 AddToWalletIfMine(tx, NULL);
2358 RelayMessage(inv, vMsg);
2359 mapAlreadyAskedFor.erase(inv);
2360 vWorkQueue.push_back(inv.hash);
2365 foreach(uint256 hash, vWorkQueue)
2366 EraseOrphanTx(hash);
2368 else if (fMissingInputs)
2370 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2376 else if (strCommand == "block")
2378 auto_ptr<CBlock> pblock(new CBlock);
2382 printf("received block %s\n", pblock->GetHash().ToString().substr(0,20).c_str());
2385 CInv inv(MSG_BLOCK, pblock->GetHash());
2386 pfrom->AddInventoryKnown(inv);
2388 if (ProcessBlock(pfrom, pblock.release()))
2389 mapAlreadyAskedFor.erase(inv);
2393 else if (strCommand == "getaddr")
2395 // This includes all nodes that are currently online,
2396 // since they rebroadcast an addr every 24 hours
2397 pfrom->vAddrToSend.clear();
2398 int64 nSince = GetAdjustedTime() - 12 * 60 * 60; // in the last 12 hours
2399 CRITICAL_BLOCK(cs_mapAddresses)
2401 unsigned int nSize = mapAddresses.size();
2402 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2406 const CAddress& addr = item.second;
2407 if (addr.nTime > nSince)
2408 pfrom->PushAddress(addr);
2414 else if (strCommand == "checkorder")
2418 vRecv >> hashReply >> order;
2420 /// we have a chance to check the order here
2422 // Keep giving the same key to the same ip until they use it
2423 if (!mapReuseKey.count(pfrom->addr.ip))
2424 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
2426 // Send back approval of order and pubkey to use
2427 CScript scriptPubKey;
2428 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2429 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2433 else if (strCommand == "submitorder")
2437 vRecv >> hashReply >> wtxNew;
2438 wtxNew.fFromMe = false;
2441 if (!wtxNew.AcceptWalletTransaction())
2443 pfrom->PushMessage("reply", hashReply, (int)1);
2444 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2446 wtxNew.fTimeReceivedIsTxTime = true;
2447 AddToWallet(wtxNew);
2448 wtxNew.RelayWalletTransaction();
2449 mapReuseKey.erase(pfrom->addr.ip);
2451 // Send back confirmation
2452 pfrom->PushMessage("reply", hashReply, (int)0);
2456 else if (strCommand == "reply")
2461 CRequestTracker tracker;
2462 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2464 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2465 if (mi != pfrom->mapRequests.end())
2467 tracker = (*mi).second;
2468 pfrom->mapRequests.erase(mi);
2471 if (!tracker.IsNull())
2472 tracker.fn(tracker.param1, vRecv);
2476 else if (strCommand == "ping")
2481 else if (strCommand == "alert")
2486 if (alert.ProcessAlert())
2489 pfrom->setKnown.insert(alert.GetHash());
2490 CRITICAL_BLOCK(cs_vNodes)
2491 foreach(CNode* pnode, vNodes)
2492 alert.RelayTo(pnode);
2499 // Ignore unknown commands for extensibility
2503 // Update the last seen time for this node's address
2504 if (pfrom->fNetworkNode)
2505 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2506 AddressCurrentlyConnected(pfrom->addr);
2520 bool SendMessages(CNode* pto, bool fSendTrickle)
2522 CRITICAL_BLOCK(cs_main)
2524 // Don't send anything until we get their version message
2525 if (pto->nVersion == 0)
2529 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2530 pto->PushMessage("ping");
2532 // Address refresh broadcast
2533 static int64 nLastRebroadcast;
2534 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2536 nLastRebroadcast = GetTime();
2537 CRITICAL_BLOCK(cs_vNodes)
2539 foreach(CNode* pnode, vNodes)
2541 // Periodically clear setAddrKnown to allow refresh broadcasts
2542 pnode->setAddrKnown.clear();
2544 // Rebroadcast our address
2545 if (addrLocalHost.IsRoutable() && !fUseProxy)
2546 pnode->PushAddress(addrLocalHost);
2551 // Resend wallet transactions that haven't gotten in a block yet
2552 ResendWalletTransactions();
2560 vector<CAddress> vAddr;
2561 vAddr.reserve(pto->vAddrToSend.size());
2562 foreach(const CAddress& addr, pto->vAddrToSend)
2564 // returns true if wasn't already contained in the set
2565 if (pto->setAddrKnown.insert(addr).second)
2567 vAddr.push_back(addr);
2568 // receiver rejects addr messages larger than 1000
2569 if (vAddr.size() >= 1000)
2571 pto->PushMessage("addr", vAddr);
2576 pto->vAddrToSend.clear();
2578 pto->PushMessage("addr", vAddr);
2583 // Message: inventory
2586 vector<CInv> vInvWait;
2587 CRITICAL_BLOCK(pto->cs_inventory)
2589 vInv.reserve(pto->vInventoryToSend.size());
2590 vInvWait.reserve(pto->vInventoryToSend.size());
2591 foreach(const CInv& inv, pto->vInventoryToSend)
2593 if (pto->setInventoryKnown.count(inv))
2596 // trickle out tx inv to protect privacy
2597 if (inv.type == MSG_TX && !fSendTrickle)
2599 // 1/4 of tx invs blast to all immediately
2600 static uint256 hashSalt;
2602 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2603 uint256 hashRand = inv.hash ^ hashSalt;
2604 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2605 bool fTrickleWait = ((hashRand & 3) != 0);
2607 // always trickle our own transactions
2610 TRY_CRITICAL_BLOCK(cs_mapWallet)
2612 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2613 if (mi != mapWallet.end())
2615 CWalletTx& wtx = (*mi).second;
2617 fTrickleWait = true;
2624 vInvWait.push_back(inv);
2629 // returns true if wasn't already contained in the set
2630 if (pto->setInventoryKnown.insert(inv).second)
2632 vInv.push_back(inv);
2633 if (vInv.size() >= 1000)
2635 pto->PushMessage("inv", vInv);
2640 pto->vInventoryToSend = vInvWait;
2643 pto->PushMessage("inv", vInv);
2649 vector<CInv> vGetData;
2650 int64 nNow = GetTime() * 1000000;
2652 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2654 const CInv& inv = (*pto->mapAskFor.begin()).second;
2655 if (!AlreadyHave(txdb, inv))
2657 printf("sending getdata: %s\n", inv.ToString().c_str());
2658 vGetData.push_back(inv);
2659 if (vGetData.size() >= 1000)
2661 pto->PushMessage("getdata", vGetData);
2665 pto->mapAskFor.erase(pto->mapAskFor.begin());
2667 if (!vGetData.empty())
2668 pto->PushMessage("getdata", vGetData);
2687 //////////////////////////////////////////////////////////////////////////////
2692 void GenerateBitcoins(bool fGenerate)
2694 if (fGenerateBitcoins != fGenerate)
2696 fGenerateBitcoins = fGenerate;
2697 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2700 if (fGenerateBitcoins)
2702 int nProcessors = boost::thread::hardware_concurrency();
2703 printf("%d processors\n", nProcessors);
2704 if (nProcessors < 1)
2706 if (fLimitProcessors && nProcessors > nLimitProcessors)
2707 nProcessors = nLimitProcessors;
2708 int nAddThreads = nProcessors - vnThreadsRunning[3];
2709 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2710 for (int i = 0; i < nAddThreads; i++)
2712 if (!CreateThread(ThreadBitcoinMiner, NULL))
2713 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2719 void ThreadBitcoinMiner(void* parg)
2723 vnThreadsRunning[3]++;
2725 vnThreadsRunning[3]--;
2727 catch (std::exception& e) {
2728 vnThreadsRunning[3]--;
2729 PrintException(&e, "ThreadBitcoinMiner()");
2731 vnThreadsRunning[3]--;
2732 PrintException(NULL, "ThreadBitcoinMiner()");
2734 UIThreadCall(bind(CalledSetStatusBar, "", 0));
2736 if (vnThreadsRunning[3] == 0)
2738 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2741 int FormatHashBlocks(void* pbuffer, unsigned int len)
2743 unsigned char* pdata = (unsigned char*)pbuffer;
2744 unsigned int blocks = 1 + ((len + 8) / 64);
2745 unsigned char* pend = pdata + 64 * blocks;
2746 memset(pdata + len, 0, 64 * blocks - len);
2748 unsigned int bits = len * 8;
2749 pend[-1] = (bits >> 0) & 0xff;
2750 pend[-2] = (bits >> 8) & 0xff;
2751 pend[-3] = (bits >> 16) & 0xff;
2752 pend[-4] = (bits >> 24) & 0xff;
2756 using CryptoPP::ByteReverse;
2758 static const unsigned int pSHA256InitState[8] =
2759 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2761 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2763 memcpy(pstate, pinit, 32);
2764 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2767 static const int NPAR = 32;
2768 extern void Double_BlockSHA256(const void* pin, void* pout, const void* pinit, unsigned int hash[8][NPAR], const void* init2);
2770 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2771 void CallCPUID(int in, int& aret, int& cret)
2775 "mov %2, %%eax; " // in into eax
2777 "mov %%eax, %0;" // eax into a
2778 "mov %%ecx, %1;" // eax into c
2779 :"=r"(a),"=r"(c) /* output */
2780 :"r"(in) /* input */
2781 :"%eax","%ecx" /* clobbered register */
2787 bool Detect128BitSSE2()
2790 CallCPUID(0, a, nBrand);
2791 bool fIntel = (nBrand == 0x6c65746e); // ntel
2792 bool fAMD = (nBrand == 0x444d4163); // cAMD
2796 unsigned int nStepping : 4;
2797 unsigned int nModel : 4;
2798 unsigned int nFamily : 4;
2799 unsigned int nProcessorType : 2;
2800 unsigned int nUnused : 2;
2801 unsigned int nExtendedModel : 4;
2802 unsigned int nExtendedFamily : 8;
2806 memcpy(&cpu, &a, sizeof(cpu));
2807 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
2808 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
2810 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
2811 // Nehalem = i3/i5/i7 and some Xeon
2812 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
2813 // Intel Core i5 family 6, model 26 or 30
2814 // Intel Core i7 family 6, model 26 or 30
2815 // Intel Core i3 family 6, model 37
2816 // AMD Phenom family 16, model 10
2817 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
2818 (fAMD && nFamily * 10000 + nModel >= 160010));
2820 static bool fPrinted;
2824 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
2829 bool Detect128BitSSE2() { return false; }
2837 printf("BitcoinMiner started\n");
2838 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2839 bool f4WaySSE2 = Detect128BitSSE2();
2840 if (mapArgs.count("-4way"))
2841 f4WaySSE2 = (mapArgs["-4way"] != "0");
2845 CBigNum bnExtraNonce = 0;
2846 while (fGenerateBitcoins)
2851 while (vNodes.empty() || IsInitialBlockDownload())
2856 if (!fGenerateBitcoins)
2860 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2861 CBlockIndex* pindexPrev = pindexBest;
2862 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2866 // Create coinbase tx
2869 txNew.vin.resize(1);
2870 txNew.vin[0].prevout.SetNull();
2871 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
2872 txNew.vout.resize(1);
2873 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
2879 auto_ptr<CBlock> pblock(new CBlock());
2883 // Add our coinbase tx as first transaction
2884 pblock->vtx.push_back(txNew);
2886 // Collect the latest transactions into the block
2888 CRITICAL_BLOCK(cs_main)
2889 CRITICAL_BLOCK(cs_mapTransactions)
2892 map<uint256, CTxIndex> mapTestPool;
2893 vector<char> vfAlreadyAdded(mapTransactions.size());
2894 bool fFoundSomething = true;
2895 uint64 nBlockSize = 10000;
2896 int nBlockSigOps = 100;
2897 while (fFoundSomething)
2899 fFoundSomething = false;
2901 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
2903 if (vfAlreadyAdded[n])
2905 CTransaction& tx = (*mi).second;
2906 if (tx.IsCoinBase() || !tx.IsFinal())
2908 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2909 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE)
2911 int nTxSigOps = tx.GetSigOpCount();
2912 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2915 // Transaction fee based on block size
2916 int64 nMinFee = tx.GetMinFee(nBlockSize);
2918 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2919 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2921 swap(mapTestPool, mapTestPoolTmp);
2923 pblock->vtx.push_back(tx);
2924 nBlockSize += nTxSize;
2925 nBlockSigOps += nTxSigOps;
2926 vfAlreadyAdded[n] = true;
2927 fFoundSomething = true;
2931 pblock->nBits = nBits;
2932 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(pindexPrev->nHeight+1, nFees);
2933 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2937 // Prebuild hash buffer
2944 uint256 hashPrevBlock;
2945 uint256 hashMerkleRoot;
2948 unsigned int nNonce;
2951 unsigned char pchPadding0[64];
2953 unsigned char pchPadding1[64];
2955 char tmpbuf[sizeof(tmpworkspace)+16];
2956 tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
2958 tmp.block.nVersion = pblock->nVersion;
2959 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
2960 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2961 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
2962 tmp.block.nBits = pblock->nBits = nBits;
2963 tmp.block.nNonce = pblock->nNonce = 0;
2965 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2966 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2968 // Byte swap all the input buffer
2969 for (int i = 0; i < sizeof(tmp)/4; i++)
2970 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2972 // Precalc the first half of the first hash, which stays constant
2973 uint256 midstatebuf[2];
2974 uint256& midstate = *alignup<16>(midstatebuf);
2975 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
2981 int64 nStart = GetTime();
2982 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2984 uint256& hash = *alignup<16>(hashbuf);
2990 // tcatm's 4-way SSE2 SHA-256
2991 tmp.block.nNonce += NPAR;
2992 unsigned int thashbuf[9][NPAR];
2993 unsigned int (&thash)[9][NPAR] = *alignup<16>(&thashbuf);
2994 Double_BlockSHA256((char*)&tmp.block + 64, &tmp.hash1, &midstate, thash, pSHA256InitState);
2995 ((unsigned short*)&hash)[14] = 0xffff;
2996 for (int j = 0; j < NPAR; j++)
2998 if (thash[7][j] == 0)
3000 for (int i = 0; i < sizeof(hash)/4; i++)
3001 ((unsigned int*)&hash)[i] = thash[i][j];
3002 pblock->nNonce = ByteReverse(tmp.block.nNonce + j);
3011 SHA256Transform(&tmp.hash1, (char*)&tmp.block + 64, &midstate);
3012 SHA256Transform(&hash, &tmp.hash1, pSHA256InitState);
3015 if (((unsigned short*)&hash)[14] == 0)
3017 // Byte swap the result after preliminary check
3018 for (int i = 0; i < sizeof(hash)/4; i++)
3019 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3021 if (hash <= hashTarget)
3026 pblock->nNonce = ByteReverse(tmp.block.nNonce);
3027 assert(hash == pblock->GetHash());
3030 printf("BitcoinMiner:\n");
3031 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3033 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3034 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3036 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3037 CRITICAL_BLOCK(cs_main)
3039 if (pindexPrev == pindexBest)
3046 // Track how many getdata requests this block gets
3047 CRITICAL_BLOCK(cs_mapRequestCount)
3048 mapRequestCount[pblock->GetHash()] = 0;
3050 // Process this block the same as if we had received it from another node
3051 if (!ProcessBlock(NULL, pblock.release()))
3052 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
3055 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3062 // Update nTime every few seconds
3063 const unsigned int nMask = 0xffff;
3064 const int nHashesPerCycle = (nMask+1);
3065 if ((tmp.block.nNonce & nMask) == 0)
3068 static int nCycleCounter;
3069 if (nHPSTimerStart == 0)
3071 nHPSTimerStart = GetTimeMillis();
3076 if (GetTimeMillis() - nHPSTimerStart > 4000)
3078 static CCriticalSection cs;
3081 if (GetTimeMillis() - nHPSTimerStart > 4000)
3083 dHashesPerSec = 1000.0 * nHashesPerCycle * nCycleCounter / (GetTimeMillis() - nHPSTimerStart);
3084 nHPSTimerStart = GetTimeMillis();
3086 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3087 UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));
3088 static int64 nLogTime;
3089 if (GetTime() - nLogTime > 30 * 60)
3091 nLogTime = GetTime();
3092 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3093 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3099 // Check for stop or if block needs to be rebuilt
3102 if (!fGenerateBitcoins)
3104 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3108 if (tmp.block.nNonce == 0)
3110 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3112 if (pindexPrev != pindexBest)
3115 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3116 tmp.block.nTime = ByteReverse(pblock->nTime);
3139 //////////////////////////////////////////////////////////////////////////////
3147 int64 nStart = GetTimeMillis();
3150 CRITICAL_BLOCK(cs_mapWallet)
3152 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3154 CWalletTx* pcoin = &(*it).second;
3155 if (!pcoin->IsFinal() || pcoin->fSpent)
3157 nTotal += pcoin->GetCredit(true);
3161 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3166 int GetRandInt(int nMax)
3168 return GetRand(nMax);
3171 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3173 setCoinsRet.clear();
3175 // List of values less than target
3176 int64 nLowestLarger = INT64_MAX;
3177 CWalletTx* pcoinLowestLarger = NULL;
3178 vector<pair<int64, CWalletTx*> > vValue;
3179 int64 nTotalLower = 0;
3181 CRITICAL_BLOCK(cs_mapWallet)
3183 vector<CWalletTx*> vCoins;
3184 vCoins.reserve(mapWallet.size());
3185 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3186 vCoins.push_back(&(*it).second);
3187 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3189 foreach(CWalletTx* pcoin, vCoins)
3191 if (!pcoin->IsFinal() || pcoin->fSpent)
3193 int64 n = pcoin->GetCredit();
3196 if (n < nTargetValue)
3198 vValue.push_back(make_pair(n, pcoin));
3201 else if (n == nTargetValue)
3203 setCoinsRet.insert(pcoin);
3206 else if (n < nLowestLarger)
3209 pcoinLowestLarger = pcoin;
3214 if (nTotalLower < nTargetValue)
3216 if (pcoinLowestLarger == NULL)
3218 setCoinsRet.insert(pcoinLowestLarger);
3222 // Solve subset sum by stochastic approximation
3223 sort(vValue.rbegin(), vValue.rend());
3224 vector<char> vfIncluded;
3225 vector<char> vfBest(vValue.size(), true);
3226 int64 nBest = nTotalLower;
3228 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3230 vfIncluded.assign(vValue.size(), false);
3232 bool fReachedTarget = false;
3233 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3235 for (int i = 0; i < vValue.size(); i++)
3237 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3239 nTotal += vValue[i].first;
3240 vfIncluded[i] = true;
3241 if (nTotal >= nTargetValue)
3243 fReachedTarget = true;
3247 vfBest = vfIncluded;
3249 nTotal -= vValue[i].first;
3250 vfIncluded[i] = false;
3257 // If the next larger is still closer, return it
3258 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3259 setCoinsRet.insert(pcoinLowestLarger);
3262 for (int i = 0; i < vValue.size(); i++)
3264 setCoinsRet.insert(vValue[i].second);
3267 printf("SelectCoins() best subset: ");
3268 for (int i = 0; i < vValue.size(); i++)
3270 printf("%s ", FormatMoney(vValue[i].first).c_str());
3271 printf("total %s\n", FormatMoney(nBest).c_str());
3280 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
3282 nFeeRequiredRet = 0;
3283 CRITICAL_BLOCK(cs_main)
3285 // txdb must be opened before the mapWallet lock
3287 CRITICAL_BLOCK(cs_mapWallet)
3289 int64 nFee = nTransactionFee;
3293 wtxNew.vout.clear();
3294 wtxNew.fFromMe = true;
3297 int64 nValueOut = nValue;
3298 int64 nTotalValue = nValue + nFee;
3300 // Choose coins to use
3301 set<CWalletTx*> setCoins;
3302 if (!SelectCoins(nTotalValue, setCoins))
3305 foreach(CWalletTx* pcoin, setCoins)
3306 nValueIn += pcoin->GetCredit();
3308 // Fill a vout to the payee
3309 bool fChangeFirst = GetRand(2);
3311 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3313 // Fill a vout back to self with any change
3314 int64 nChange = nValueIn - nTotalValue;
3315 if (nChange >= CENT)
3317 // Note: We use a new key here to keep it from being obvious which side is the change.
3318 // The drawback is that by not reusing a previous key, the change may be lost if a
3319 // backup is restored, if the backup doesn't have the new private key for the change.
3320 // If we reused the old key, it would be possible to add code to look for and
3321 // rediscover unknown transactions that were written with keys of ours to recover
3322 // post-backup change.
3325 if (keyRet.IsNull())
3326 keyRet.MakeNewKey();
3328 // Fill a vout to ourself, using same address type as the payment
3329 CScript scriptChange;
3330 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3331 scriptChange.SetBitcoinAddress(keyRet.GetPubKey());
3333 scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;
3334 wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3337 // Fill a vout to the payee
3339 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3342 foreach(CWalletTx* pcoin, setCoins)
3343 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3344 if (pcoin->vout[nOut].IsMine())
3345 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3349 foreach(CWalletTx* pcoin, setCoins)
3350 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3351 if (pcoin->vout[nOut].IsMine())
3352 if (!SignSignature(*pcoin, wtxNew, nIn++))
3355 // Check that enough fee is included
3356 if (nFee < wtxNew.GetMinFee())
3358 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3362 // Fill vtxPrev by copying from previous transactions vtxPrev
3363 wtxNew.AddSupportingTransactions(txdb);
3364 wtxNew.fTimeReceivedIsTxTime = true;
3373 // Call after CreateTransaction unless you want to abort
3374 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)
3376 CRITICAL_BLOCK(cs_main)
3378 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3379 CRITICAL_BLOCK(cs_mapWallet)
3381 // This is only to keep the database open to defeat the auto-flush for the
3382 // duration of this scope. This is the only place where this optimization
3383 // maybe makes sense; please don't do it anywhere else.
3384 CWalletDB walletdb("r");
3386 // Add the change's private key to wallet
3387 if (!key.IsNull() && !AddKey(key))
3388 throw runtime_error("CommitTransaction() : AddKey failed");
3390 // Add tx to wallet, because if it has change it's also ours,
3391 // otherwise just for transaction history.
3392 AddToWallet(wtxNew);
3394 // Mark old coins as spent
3395 set<CWalletTx*> setCoins;
3396 foreach(const CTxIn& txin, wtxNew.vin)
3397 setCoins.insert(&mapWallet[txin.prevout.hash]);
3398 foreach(CWalletTx* pcoin, setCoins)
3400 pcoin->fSpent = true;
3401 pcoin->WriteToDisk();
3402 vWalletUpdated.push_back(pcoin->GetHash());
3406 // Track how many getdata requests our transaction gets
3407 CRITICAL_BLOCK(cs_mapRequestCount)
3408 mapRequestCount[wtxNew.GetHash()] = 0;
3411 if (!wtxNew.AcceptToMemoryPool())
3413 // This must not fail. The transaction has already been signed and recorded.
3414 printf("CommitTransaction() : Error: Transaction not valid");
3417 wtxNew.RelayWalletTransaction();
3426 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3428 CRITICAL_BLOCK(cs_main)
3432 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
3435 if (nValue + nFeeRequired > GetBalance())
3436 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3438 strError = _("Error: Transaction creation failed ");
3439 printf("SendMoney() : %s", strError.c_str());
3443 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3446 if (!CommitTransaction(wtxNew, key))
3447 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.");
3455 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3459 return _("Invalid amount");
3460 if (nValue + nTransactionFee > GetBalance())
3461 return _("Insufficient funds");
3463 // Parse bitcoin address
3464 CScript scriptPubKey;
3465 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3466 return _("Invalid bitcoin address");
3468 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);