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,10).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 vchDefaultKey = walletdb.GetKeyFromKeyPool();
162 walletdb.WriteDefaultKey(vchDefaultKey);
163 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
168 vWalletUpdated.push_back(hash);
176 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
178 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
181 // Get merkle branch if transaction was found in a block
183 wtx.SetMerkleBranch(pblock);
184 return AddToWallet(wtx);
189 bool EraseFromWallet(uint256 hash)
191 CRITICAL_BLOCK(cs_mapWallet)
193 if (mapWallet.erase(hash))
194 CWalletDB().EraseTx(hash);
199 void WalletUpdateSpent(const COutPoint& prevout)
201 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
202 // Update the wallet spent flag if it doesn't know due to wallet.dat being
203 // restored from backup or the user making copies of wallet.dat.
204 CRITICAL_BLOCK(cs_mapWallet)
206 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
207 if (mi != mapWallet.end())
209 CWalletTx& wtx = (*mi).second;
210 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
212 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
215 vWalletUpdated.push_back(prevout.hash);
228 //////////////////////////////////////////////////////////////////////////////
230 // mapOrphanTransactions
233 void AddOrphanTx(const CDataStream& vMsg)
236 CDataStream(vMsg) >> tx;
237 uint256 hash = tx.GetHash();
238 if (mapOrphanTransactions.count(hash))
240 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
241 foreach(const CTxIn& txin, tx.vin)
242 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
245 void EraseOrphanTx(uint256 hash)
247 if (!mapOrphanTransactions.count(hash))
249 const CDataStream* pvMsg = mapOrphanTransactions[hash];
251 CDataStream(*pvMsg) >> tx;
252 foreach(const CTxIn& txin, tx.vin)
254 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
255 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
257 if ((*mi).second == pvMsg)
258 mapOrphanTransactionsByPrev.erase(mi++);
264 mapOrphanTransactions.erase(hash);
274 //////////////////////////////////////////////////////////////////////////////
279 bool CTxIn::IsMine() const
281 CRITICAL_BLOCK(cs_mapWallet)
283 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
284 if (mi != mapWallet.end())
286 const CWalletTx& prev = (*mi).second;
287 if (prevout.n < prev.vout.size())
288 if (prev.vout[prevout.n].IsMine())
295 int64 CTxIn::GetDebit() const
297 CRITICAL_BLOCK(cs_mapWallet)
299 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
300 if (mi != mapWallet.end())
302 const CWalletTx& prev = (*mi).second;
303 if (prevout.n < prev.vout.size())
304 if (prev.vout[prevout.n].IsMine())
305 return prev.vout[prevout.n].nValue;
311 int64 CWalletTx::GetTxTime() const
313 if (!fTimeReceivedIsTxTime && hashBlock != 0)
315 // If we did not receive the transaction directly, we rely on the block's
316 // time to figure out when it happened. We use the median over a range
317 // of blocks to try to filter out inaccurate block times.
318 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
319 if (mi != mapBlockIndex.end())
321 CBlockIndex* pindex = (*mi).second;
323 return pindex->GetMedianTime();
326 return nTimeReceived;
329 int CWalletTx::GetRequestCount() const
331 // Returns -1 if it wasn't being tracked
333 CRITICAL_BLOCK(cs_mapRequestCount)
340 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
341 if (mi != mapRequestCount.end())
342 nRequests = (*mi).second;
347 // Did anyone request this transaction?
348 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
349 if (mi != mapRequestCount.end())
351 nRequests = (*mi).second;
353 // How about the block it's in?
354 if (nRequests == 0 && hashBlock != 0)
356 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
357 if (mi != mapRequestCount.end())
358 nRequests = (*mi).second;
360 nRequests = 1; // If it's in someone else's block it must have got out
371 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
383 // Load the block this tx is in
385 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
387 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
392 // Update the tx's hashBlock
393 hashBlock = pblock->GetHash();
395 // Locate the transaction
396 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
397 if (pblock->vtx[nIndex] == *(CTransaction*)this)
399 if (nIndex == pblock->vtx.size())
401 vMerkleBranch.clear();
403 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
407 // Fill in merkle branch
408 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
411 // Is the tx in a block that's in the main chain
412 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
413 if (mi == mapBlockIndex.end())
415 CBlockIndex* pindex = (*mi).second;
416 if (!pindex || !pindex->IsInMainChain())
419 return pindexBest->nHeight - pindex->nHeight + 1;
424 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
428 const int COPY_DEPTH = 3;
429 if (SetMerkleBranch() < COPY_DEPTH)
431 vector<uint256> vWorkQueue;
432 foreach(const CTxIn& txin, vin)
433 vWorkQueue.push_back(txin.prevout.hash);
435 // This critsect is OK because txdb is already open
436 CRITICAL_BLOCK(cs_mapWallet)
438 map<uint256, const CMerkleTx*> mapWalletPrev;
439 set<uint256> setAlreadyDone;
440 for (int i = 0; i < vWorkQueue.size(); i++)
442 uint256 hash = vWorkQueue[i];
443 if (setAlreadyDone.count(hash))
445 setAlreadyDone.insert(hash);
448 if (mapWallet.count(hash))
450 tx = mapWallet[hash];
451 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
452 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
454 else if (mapWalletPrev.count(hash))
456 tx = *mapWalletPrev[hash];
458 else if (!fClient && txdb.ReadDiskTx(hash, tx))
464 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
468 int nDepth = tx.SetMerkleBranch();
469 vtxPrev.push_back(tx);
471 if (nDepth < COPY_DEPTH)
472 foreach(const CTxIn& txin, tx.vin)
473 vWorkQueue.push_back(txin.prevout.hash);
478 reverse(vtxPrev.begin(), vtxPrev.end());
491 bool CTransaction::CheckTransaction() const
493 // Basic checks that don't depend on any context
494 if (vin.empty() || vout.empty())
495 return error("CTransaction::CheckTransaction() : vin or vout empty");
498 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
499 return error("CTransaction::CheckTransaction() : size limits failed");
501 // Check for negative or overflow output values
503 foreach(const CTxOut& txout, vout)
505 if (txout.nValue < 0)
506 return error("CTransaction::CheckTransaction() : txout.nValue negative");
507 if (txout.nValue > MAX_MONEY)
508 return error("CTransaction::CheckTransaction() : txout.nValue too high");
509 nValueOut += txout.nValue;
510 if (!MoneyRange(nValueOut))
511 return error("CTransaction::CheckTransaction() : txout total out of range");
516 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
517 return error("CTransaction::CheckTransaction() : coinbase script size");
521 foreach(const CTxIn& txin, vin)
522 if (txin.prevout.IsNull())
523 return error("CTransaction::CheckTransaction() : prevout is null");
529 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
532 *pfMissingInputs = false;
534 if (!CheckTransaction())
535 return error("AcceptToMemoryPool() : CheckTransaction failed");
537 // Coinbase is only valid in a block, not as a loose transaction
539 return error("AcceptToMemoryPool() : coinbase as individual tx");
541 // To help v0.1.5 clients who would see it as a negative number
542 if ((int64)nLockTime > INT_MAX)
543 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
545 // Rather not work on nonstandard transactions
546 if (GetSigOpCount() > 2 || ::GetSerializeSize(*this, SER_NETWORK) < 100)
547 return error("AcceptToMemoryPool() : nonstandard transaction");
549 // Do we already have it?
550 uint256 hash = GetHash();
551 CRITICAL_BLOCK(cs_mapTransactions)
552 if (mapTransactions.count(hash))
555 if (txdb.ContainsTx(hash))
558 // Check for conflicts with in-memory transactions
559 CTransaction* ptxOld = NULL;
560 for (int i = 0; i < vin.size(); i++)
562 COutPoint outpoint = vin[i].prevout;
563 if (mapNextTx.count(outpoint))
565 // Disable replacement feature for now
568 // Allow replacing with a newer version of the same transaction
571 ptxOld = mapNextTx[outpoint].ptx;
572 if (!IsNewerThan(*ptxOld))
574 for (int i = 0; i < vin.size(); i++)
576 COutPoint outpoint = vin[i].prevout;
577 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
584 // Check against previous transactions
585 map<uint256, CTxIndex> mapUnused;
587 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
590 *pfMissingInputs = true;
591 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
594 // Store transaction in memory
595 CRITICAL_BLOCK(cs_mapTransactions)
599 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
600 ptxOld->RemoveFromMemoryPool();
602 AddToMemoryPoolUnchecked();
605 ///// are we sure this is ok when loading transactions or restoring block txes
606 // If updated, erase old tx from wallet
608 EraseFromWallet(ptxOld->GetHash());
610 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
615 bool CTransaction::AddToMemoryPoolUnchecked()
617 // Add to memory pool without checking anything. Don't call this directly,
618 // call AcceptToMemoryPool to properly check the transaction first.
619 CRITICAL_BLOCK(cs_mapTransactions)
621 uint256 hash = GetHash();
622 mapTransactions[hash] = *this;
623 for (int i = 0; i < vin.size(); i++)
624 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
625 nTransactionsUpdated++;
631 bool CTransaction::RemoveFromMemoryPool()
633 // Remove transaction from memory pool
634 CRITICAL_BLOCK(cs_mapTransactions)
636 foreach(const CTxIn& txin, vin)
637 mapNextTx.erase(txin.prevout);
638 mapTransactions.erase(GetHash());
639 nTransactionsUpdated++;
649 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
651 if (hashBlock == 0 || nIndex == -1)
654 // Find the block it claims to be in
655 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
656 if (mi == mapBlockIndex.end())
658 CBlockIndex* pindex = (*mi).second;
659 if (!pindex || !pindex->IsInMainChain())
662 // Make sure the merkle branch connects to this block
663 if (!fMerkleVerified)
665 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
667 fMerkleVerified = true;
670 nHeightRet = pindex->nHeight;
671 return pindexBest->nHeight - pindex->nHeight + 1;
675 int CMerkleTx::GetBlocksToMaturity() const
679 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
683 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
687 if (!IsInMainChain() && !ClientConnectInputs())
689 return CTransaction::AcceptToMemoryPool(txdb, false);
693 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
699 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
701 CRITICAL_BLOCK(cs_mapTransactions)
703 // Add previous supporting transactions first
704 foreach(CMerkleTx& tx, vtxPrev)
706 if (!tx.IsCoinBase())
708 uint256 hash = tx.GetHash();
709 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
710 tx.AcceptToMemoryPool(txdb, fCheckInputs);
713 return AcceptToMemoryPool(txdb, fCheckInputs);
718 void ReacceptWalletTransactions()
721 CRITICAL_BLOCK(cs_mapWallet)
723 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
725 CWalletTx& wtx = item.second;
726 if (wtx.fSpent && wtx.IsCoinBase())
730 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
732 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
735 if (txindex.vSpent.size() != wtx.vout.size())
737 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
740 for (int i = 0; i < txindex.vSpent.size(); i++)
742 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
744 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
754 // Reaccept any txes of ours that aren't already in a block
755 if (!wtx.IsCoinBase())
756 wtx.AcceptWalletTransaction(txdb, false);
763 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
765 foreach(const CMerkleTx& tx, vtxPrev)
767 if (!tx.IsCoinBase())
769 uint256 hash = tx.GetHash();
770 if (!txdb.ContainsTx(hash))
771 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
776 uint256 hash = GetHash();
777 if (!txdb.ContainsTx(hash))
779 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
780 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
785 void ResendWalletTransactions()
787 // Do this infrequently and randomly to avoid giving away
788 // that these are our transactions.
789 static int64 nNextTime;
790 if (GetTime() < nNextTime)
792 bool fFirst = (nNextTime == 0);
793 nNextTime = GetTime() + GetRand(30 * 60);
797 // Only do it if there's been a new block since last time
798 static int64 nLastTime;
799 if (nTimeBestReceived < nLastTime)
801 nLastTime = GetTime();
803 // Rebroadcast any of our txes that aren't in a block yet
804 printf("ResendWalletTransactions()\n");
806 CRITICAL_BLOCK(cs_mapWallet)
808 // Sort them in chronological order
809 multimap<unsigned int, CWalletTx*> mapSorted;
810 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
812 CWalletTx& wtx = item.second;
813 // Don't rebroadcast until it's had plenty of time that
814 // it should have gotten in already by now.
815 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
816 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
818 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
820 CWalletTx& wtx = *item.second;
821 wtx.RelayWalletTransaction(txdb);
835 //////////////////////////////////////////////////////////////////////////////
837 // CBlock and CBlockIndex
840 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
842 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
844 if (GetHash() != pindex->GetBlockHash())
845 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
849 uint256 GetOrphanRoot(const CBlock* pblock)
851 // Work back to the first block in the orphan chain
852 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
853 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
854 return pblock->GetHash();
857 int64 GetBlockValue(int nHeight, int64 nFees)
859 int64 nSubsidy = 50 * COIN;
861 // Subsidy is cut in half every 4 years
862 nSubsidy >>= (nHeight / 210000);
864 return nSubsidy + nFees;
867 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
869 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
870 const int64 nTargetSpacing = 10 * 60;
871 const int64 nInterval = nTargetTimespan / nTargetSpacing;
874 if (pindexLast == NULL)
875 return bnProofOfWorkLimit.GetCompact();
877 // Only change once per interval
878 if ((pindexLast->nHeight+1) % nInterval != 0)
879 return pindexLast->nBits;
881 // Go back by what we want to be 14 days worth of blocks
882 const CBlockIndex* pindexFirst = pindexLast;
883 for (int i = 0; pindexFirst && i < nInterval-1; i++)
884 pindexFirst = pindexFirst->pprev;
887 // Limit adjustment step
888 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
889 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
890 if (nActualTimespan < nTargetTimespan/4)
891 nActualTimespan = nTargetTimespan/4;
892 if (nActualTimespan > nTargetTimespan*4)
893 nActualTimespan = nTargetTimespan*4;
897 bnNew.SetCompact(pindexLast->nBits);
898 bnNew *= nActualTimespan;
899 bnNew /= nTargetTimespan;
901 if (bnNew > bnProofOfWorkLimit)
902 bnNew = bnProofOfWorkLimit;
905 printf("GetNextWorkRequired RETARGET\n");
906 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
907 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
908 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
910 return bnNew.GetCompact();
913 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
916 bnTarget.SetCompact(nBits);
919 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
920 return error("CheckProofOfWork() : nBits below minimum work");
922 // Check proof of work matches claimed amount
923 if (hash > bnTarget.getuint256())
924 return error("CheckProofOfWork() : hash doesn't match nBits");
929 bool IsInitialBlockDownload()
931 if (pindexBest == NULL)
933 static int64 nLastUpdate;
934 static CBlockIndex* pindexLastBest;
935 if (pindexBest != pindexLastBest)
937 pindexLastBest = pindexBest;
938 nLastUpdate = GetTime();
940 return (GetTime() - nLastUpdate < 10 &&
941 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
944 void InvalidChainFound(CBlockIndex* pindexNew)
946 if (pindexNew->bnChainWork > bnBestInvalidWork)
948 bnBestInvalidWork = pindexNew->bnChainWork;
949 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
952 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());
953 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
954 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
955 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
968 bool CTransaction::DisconnectInputs(CTxDB& txdb)
970 // Relinquish previous transactions' spent pointers
973 foreach(const CTxIn& txin, vin)
975 COutPoint prevout = txin.prevout;
977 // Get prev txindex from disk
979 if (!txdb.ReadTxIndex(prevout.hash, txindex))
980 return error("DisconnectInputs() : ReadTxIndex failed");
982 if (prevout.n >= txindex.vSpent.size())
983 return error("DisconnectInputs() : prevout.n out of range");
985 // Mark outpoint as not spent
986 txindex.vSpent[prevout.n].SetNull();
989 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
990 return error("DisconnectInputs() : UpdateTxIndex failed");
994 // Remove transaction from index
995 if (!txdb.EraseTxIndex(*this))
996 return error("DisconnectInputs() : EraseTxPos failed");
1002 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1003 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1005 // Take over previous transactions' spent pointers
1009 for (int i = 0; i < vin.size(); i++)
1011 COutPoint prevout = vin[i].prevout;
1016 if (fMiner && mapTestPool.count(prevout.hash))
1018 // Get txindex from current proposed changes
1019 txindex = mapTestPool[prevout.hash];
1023 // Read txindex from txdb
1024 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1026 if (!fFound && (fBlock || fMiner))
1027 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1030 CTransaction txPrev;
1031 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1033 // Get prev tx from single transactions in memory
1034 CRITICAL_BLOCK(cs_mapTransactions)
1036 if (!mapTransactions.count(prevout.hash))
1037 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1038 txPrev = mapTransactions[prevout.hash];
1041 txindex.vSpent.resize(txPrev.vout.size());
1045 // Get prev tx from disk
1046 if (!txPrev.ReadFromDisk(txindex.pos))
1047 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1050 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1051 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
1053 // If prev is coinbase, check that it's matured
1054 if (txPrev.IsCoinBase())
1055 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1056 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1057 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1060 if (!VerifySignature(txPrev, *this, i))
1061 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1063 // Check for conflicts
1064 if (!txindex.vSpent[prevout.n].IsNull())
1065 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1067 // Check for negative or overflow input values
1068 nValueIn += txPrev.vout[prevout.n].nValue;
1069 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1070 return error("ConnectInputs() : txin values out of range");
1072 // Mark outpoints as spent
1073 txindex.vSpent[prevout.n] = posThisTx;
1078 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1079 return error("ConnectInputs() : UpdateTxIndex failed");
1083 mapTestPool[prevout.hash] = txindex;
1087 if (nValueIn < GetValueOut())
1088 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1090 // Tally transaction fees
1091 int64 nTxFee = nValueIn - GetValueOut();
1093 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1094 if (nTxFee < nMinFee)
1097 if (!MoneyRange(nFees))
1098 return error("ConnectInputs() : nFees out of range");
1103 // Add transaction to disk index
1104 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1105 return error("ConnectInputs() : AddTxPos failed");
1109 // Add transaction to test pool
1110 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1117 bool CTransaction::ClientConnectInputs()
1122 // Take over previous transactions' spent pointers
1123 CRITICAL_BLOCK(cs_mapTransactions)
1126 for (int i = 0; i < vin.size(); i++)
1128 // Get prev tx from single transactions in memory
1129 COutPoint prevout = vin[i].prevout;
1130 if (!mapTransactions.count(prevout.hash))
1132 CTransaction& txPrev = mapTransactions[prevout.hash];
1134 if (prevout.n >= txPrev.vout.size())
1138 if (!VerifySignature(txPrev, *this, i))
1139 return error("ConnectInputs() : VerifySignature failed");
1141 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1142 ///// this has to go away now that posNext is gone
1143 // // Check for conflicts
1144 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1145 // return error("ConnectInputs() : prev tx already used");
1147 // // Flag outpoints as used
1148 // txPrev.vout[prevout.n].posNext = posThisTx;
1150 nValueIn += txPrev.vout[prevout.n].nValue;
1152 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1153 return error("ClientConnectInputs() : txin values out of range");
1155 if (GetValueOut() > nValueIn)
1165 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1167 // Disconnect in reverse order
1168 for (int i = vtx.size()-1; i >= 0; i--)
1169 if (!vtx[i].DisconnectInputs(txdb))
1172 // Update block index on disk without changing it in memory.
1173 // The memory index structure will be changed after the db commits.
1176 CDiskBlockIndex blockindexPrev(pindex->pprev);
1177 blockindexPrev.hashNext = 0;
1178 if (!txdb.WriteBlockIndex(blockindexPrev))
1179 return error("DisconnectBlock() : WriteBlockIndex failed");
1185 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1187 // Check it again in case a previous version let a bad block in
1191 //// issue here: it doesn't know the version
1192 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1194 map<uint256, CTxIndex> mapUnused;
1196 foreach(CTransaction& tx, vtx)
1198 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1199 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1201 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1205 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1208 // Update block index on disk without changing it in memory.
1209 // The memory index structure will be changed after the db commits.
1212 CDiskBlockIndex blockindexPrev(pindex->pprev);
1213 blockindexPrev.hashNext = pindex->GetBlockHash();
1214 if (!txdb.WriteBlockIndex(blockindexPrev))
1215 return error("ConnectBlock() : WriteBlockIndex failed");
1218 // Watch for transactions paying to me
1219 foreach(CTransaction& tx, vtx)
1220 AddToWalletIfMine(tx, this);
1227 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1229 printf("REORGANIZE\n");
1232 CBlockIndex* pfork = pindexBest;
1233 CBlockIndex* plonger = pindexNew;
1234 while (pfork != plonger)
1236 while (plonger->nHeight > pfork->nHeight)
1237 if (!(plonger = plonger->pprev))
1238 return error("Reorganize() : plonger->pprev is null");
1239 if (pfork == plonger)
1241 if (!(pfork = pfork->pprev))
1242 return error("Reorganize() : pfork->pprev is null");
1245 // List of what to disconnect
1246 vector<CBlockIndex*> vDisconnect;
1247 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1248 vDisconnect.push_back(pindex);
1250 // List of what to connect
1251 vector<CBlockIndex*> vConnect;
1252 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1253 vConnect.push_back(pindex);
1254 reverse(vConnect.begin(), vConnect.end());
1256 // Disconnect shorter branch
1257 vector<CTransaction> vResurrect;
1258 foreach(CBlockIndex* pindex, vDisconnect)
1261 if (!block.ReadFromDisk(pindex))
1262 return error("Reorganize() : ReadFromDisk for disconnect failed");
1263 if (!block.DisconnectBlock(txdb, pindex))
1264 return error("Reorganize() : DisconnectBlock failed");
1266 // Queue memory transactions to resurrect
1267 foreach(const CTransaction& tx, block.vtx)
1268 if (!tx.IsCoinBase())
1269 vResurrect.push_back(tx);
1272 // Connect longer branch
1273 vector<CTransaction> vDelete;
1274 for (int i = 0; i < vConnect.size(); i++)
1276 CBlockIndex* pindex = vConnect[i];
1278 if (!block.ReadFromDisk(pindex))
1279 return error("Reorganize() : ReadFromDisk for connect failed");
1280 if (!block.ConnectBlock(txdb, pindex))
1284 return error("Reorganize() : ConnectBlock failed");
1287 // Queue memory transactions to delete
1288 foreach(const CTransaction& tx, block.vtx)
1289 vDelete.push_back(tx);
1291 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1292 return error("Reorganize() : WriteHashBestChain failed");
1294 // Make sure it's successfully written to disk before changing memory structure
1295 if (!txdb.TxnCommit())
1296 return error("Reorganize() : TxnCommit failed");
1298 // Disconnect shorter branch
1299 foreach(CBlockIndex* pindex, vDisconnect)
1301 pindex->pprev->pnext = NULL;
1303 // Connect longer branch
1304 foreach(CBlockIndex* pindex, vConnect)
1306 pindex->pprev->pnext = pindex;
1308 // Resurrect memory transactions that were in the disconnected branch
1309 foreach(CTransaction& tx, vResurrect)
1310 tx.AcceptToMemoryPool(txdb, false);
1312 // Delete redundant memory transactions that are in the connected branch
1313 foreach(CTransaction& tx, vDelete)
1314 tx.RemoveFromMemoryPool();
1320 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1322 uint256 hash = GetHash();
1325 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1327 txdb.WriteHashBestChain(hash);
1328 if (!txdb.TxnCommit())
1329 return error("SetBestChain() : TxnCommit failed");
1330 pindexGenesisBlock = pindexNew;
1332 else if (hashPrevBlock == hashBestChain)
1334 // Adding to current best branch
1335 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1338 InvalidChainFound(pindexNew);
1339 return error("SetBestChain() : ConnectBlock failed");
1341 if (!txdb.TxnCommit())
1342 return error("SetBestChain() : TxnCommit failed");
1344 // Add to current best branch
1345 pindexNew->pprev->pnext = pindexNew;
1347 // Delete redundant memory transactions
1348 foreach(CTransaction& tx, vtx)
1349 tx.RemoveFromMemoryPool();
1354 if (!Reorganize(txdb, pindexNew))
1357 InvalidChainFound(pindexNew);
1358 return error("SetBestChain() : Reorganize failed");
1363 hashBestChain = hash;
1364 pindexBest = pindexNew;
1365 nBestHeight = pindexBest->nHeight;
1366 bnBestChainWork = pindexNew->bnChainWork;
1367 nTimeBestReceived = GetTime();
1368 nTransactionsUpdated++;
1369 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1375 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1377 // Check for duplicate
1378 uint256 hash = GetHash();
1379 if (mapBlockIndex.count(hash))
1380 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1382 // Construct new block index object
1383 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1385 return error("AddToBlockIndex() : new CBlockIndex failed");
1386 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1387 pindexNew->phashBlock = &((*mi).first);
1388 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1389 if (miPrev != mapBlockIndex.end())
1391 pindexNew->pprev = (*miPrev).second;
1392 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1394 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1397 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1400 if (pindexNew->bnChainWork > bnBestChainWork)
1401 if (!SetBestChain(txdb, pindexNew))
1406 if (pindexNew == pindexBest)
1408 // Notify UI to display prev block's coinbase if it was ours
1409 static uint256 hashPrevBestCoinBase;
1410 CRITICAL_BLOCK(cs_mapWallet)
1411 vWalletUpdated.push_back(hashPrevBestCoinBase);
1412 hashPrevBestCoinBase = vtx[0].GetHash();
1422 bool CBlock::CheckBlock() const
1424 // These are checks that are independent of context
1425 // that can be verified before saving an orphan block.
1428 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1429 return error("CheckBlock() : size limits failed");
1431 // Check proof of work matches claimed amount
1432 if (!CheckProofOfWork(GetHash(), nBits))
1433 return error("CheckBlock() : proof of work failed");
1436 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1437 return error("CheckBlock() : block timestamp too far in the future");
1439 // First transaction must be coinbase, the rest must not be
1440 if (vtx.empty() || !vtx[0].IsCoinBase())
1441 return error("CheckBlock() : first tx is not coinbase");
1442 for (int i = 1; i < vtx.size(); i++)
1443 if (vtx[i].IsCoinBase())
1444 return error("CheckBlock() : more than one coinbase");
1446 // Check transactions
1447 foreach(const CTransaction& tx, vtx)
1448 if (!tx.CheckTransaction())
1449 return error("CheckBlock() : CheckTransaction failed");
1451 // Check that it's not full of nonstandard transactions
1452 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1453 return error("CheckBlock() : too many nonstandard transactions");
1456 if (hashMerkleRoot != BuildMerkleTree())
1457 return error("CheckBlock() : hashMerkleRoot mismatch");
1462 bool CBlock::AcceptBlock()
1464 // Check for duplicate
1465 uint256 hash = GetHash();
1466 if (mapBlockIndex.count(hash))
1467 return error("AcceptBlock() : block already in mapBlockIndex");
1469 // Get prev block index
1470 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1471 if (mi == mapBlockIndex.end())
1472 return error("AcceptBlock() : prev block not found");
1473 CBlockIndex* pindexPrev = (*mi).second;
1474 int nHeight = pindexPrev->nHeight+1;
1476 // Check proof of work
1477 if (nBits != GetNextWorkRequired(pindexPrev))
1478 return error("AcceptBlock() : incorrect proof of work");
1480 // Check timestamp against prev
1481 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1482 return error("AcceptBlock() : block's timestamp is too early");
1484 // Check that all transactions are finalized
1485 foreach(const CTransaction& tx, vtx)
1486 if (!tx.IsFinal(nHeight, GetBlockTime()))
1487 return error("AcceptBlock() : contains a non-final transaction");
1489 // Check that the block chain matches the known block chain up to a checkpoint
1490 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1491 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1492 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1493 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1494 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1495 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1497 // Write block to history file
1498 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1499 return error("AcceptBlock() : out of disk space");
1501 unsigned int nBlockPos;
1502 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1503 return error("AcceptBlock() : WriteToDisk failed");
1504 if (!AddToBlockIndex(nFile, nBlockPos))
1505 return error("AcceptBlock() : AddToBlockIndex failed");
1507 // Relay inventory, but don't relay old inventory during initial block download
1508 if (hashBestChain == hash)
1509 CRITICAL_BLOCK(cs_vNodes)
1510 foreach(CNode* pnode, vNodes)
1511 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1512 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1517 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1519 // Check for duplicate
1520 uint256 hash = pblock->GetHash();
1521 if (mapBlockIndex.count(hash))
1522 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1523 if (mapOrphanBlocks.count(hash))
1524 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1526 // Preliminary checks
1527 if (!pblock->CheckBlock())
1530 return error("ProcessBlock() : CheckBlock FAILED");
1533 // If don't already have its previous block, shunt it off to holding area until we get it
1534 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1536 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1537 mapOrphanBlocks.insert(make_pair(hash, pblock));
1538 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1540 // Ask this guy to fill in what we're missing
1542 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1547 if (!pblock->AcceptBlock())
1550 return error("ProcessBlock() : AcceptBlock FAILED");
1554 // Recursively process any orphan blocks that depended on this one
1555 vector<uint256> vWorkQueue;
1556 vWorkQueue.push_back(hash);
1557 for (int i = 0; i < vWorkQueue.size(); i++)
1559 uint256 hashPrev = vWorkQueue[i];
1560 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1561 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1564 CBlock* pblockOrphan = (*mi).second;
1565 if (pblockOrphan->AcceptBlock())
1566 vWorkQueue.push_back(pblockOrphan->GetHash());
1567 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1568 delete pblockOrphan;
1570 mapOrphanBlocksByPrev.erase(hashPrev);
1573 printf("ProcessBlock: ACCEPTED\n");
1584 template<typename Stream>
1585 bool ScanMessageStart(Stream& s)
1587 // Scan ahead to the next pchMessageStart, which should normally be immediately
1588 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1590 short prevmask = s.exceptions(0);
1591 const char* p = BEGIN(pchMessageStart);
1601 s.exceptions(prevmask);
1605 p = BEGIN(pchMessageStart);
1608 if (++p == END(pchMessageStart))
1611 s.exceptions(prevmask);
1620 s.exceptions(prevmask);
1625 bool CheckDiskSpace(uint64 nAdditionalBytes)
1627 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1629 // Check for 15MB because database could create another 10MB log file at any time
1630 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1633 string strMessage = _("Warning: Disk space is low ");
1634 strMiscWarning = strMessage;
1635 printf("*** %s\n", strMessage.c_str());
1636 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1637 CreateThread(Shutdown, NULL);
1643 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1647 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1650 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1652 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1661 static unsigned int nCurrentBlockFile = 1;
1663 FILE* AppendBlockFile(unsigned int& nFileRet)
1668 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1671 if (fseek(file, 0, SEEK_END) != 0)
1673 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1674 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1676 nFileRet = nCurrentBlockFile;
1680 nCurrentBlockFile++;
1684 bool LoadBlockIndex(bool fAllowNew)
1690 if (!txdb.LoadBlockIndex())
1695 // Init with genesis block
1697 if (mapBlockIndex.empty())
1703 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1704 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1705 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1706 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1707 // vMerkleTree: 4a5e1e
1710 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1712 txNew.vin.resize(1);
1713 txNew.vout.resize(1);
1714 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1715 txNew.vout[0].nValue = 50 * COIN;
1716 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1718 block.vtx.push_back(txNew);
1719 block.hashPrevBlock = 0;
1720 block.hashMerkleRoot = block.BuildMerkleTree();
1722 block.nTime = 1231006505;
1723 block.nBits = 0x1d00ffff;
1724 block.nNonce = 2083236893;
1727 printf("%s\n", block.GetHash().ToString().c_str());
1728 printf("%s\n", hashGenesisBlock.ToString().c_str());
1729 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1730 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1733 assert(block.GetHash() == hashGenesisBlock);
1735 // Start new block file
1737 unsigned int nBlockPos;
1738 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1739 return error("LoadBlockIndex() : writing genesis block to disk failed");
1740 if (!block.AddToBlockIndex(nFile, nBlockPos))
1741 return error("LoadBlockIndex() : genesis block not accepted");
1749 void PrintBlockTree()
1751 // precompute tree structure
1752 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1753 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1755 CBlockIndex* pindex = (*mi).second;
1756 mapNext[pindex->pprev].push_back(pindex);
1758 //while (rand() % 3 == 0)
1759 // mapNext[pindex->pprev].push_back(pindex);
1762 vector<pair<int, CBlockIndex*> > vStack;
1763 vStack.push_back(make_pair(0, pindexGenesisBlock));
1766 while (!vStack.empty())
1768 int nCol = vStack.back().first;
1769 CBlockIndex* pindex = vStack.back().second;
1772 // print split or gap
1773 if (nCol > nPrevCol)
1775 for (int i = 0; i < nCol-1; i++)
1779 else if (nCol < nPrevCol)
1781 for (int i = 0; i < nCol; i++)
1788 for (int i = 0; i < nCol; i++)
1793 block.ReadFromDisk(pindex);
1794 printf("%d (%u,%u) %s %s tx %d",
1798 block.GetHash().ToString().substr(0,20).c_str(),
1799 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1802 CRITICAL_BLOCK(cs_mapWallet)
1804 if (mapWallet.count(block.vtx[0].GetHash()))
1806 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1807 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1813 // put the main timechain first
1814 vector<CBlockIndex*>& vNext = mapNext[pindex];
1815 for (int i = 0; i < vNext.size(); i++)
1817 if (vNext[i]->pnext)
1819 swap(vNext[0], vNext[i]);
1825 for (int i = 0; i < vNext.size(); i++)
1826 vStack.push_back(make_pair(nCol+i, vNext[i]));
1839 //////////////////////////////////////////////////////////////////////////////
1844 map<uint256, CAlert> mapAlerts;
1845 CCriticalSection cs_mapAlerts;
1847 string GetWarnings(string strFor)
1850 string strStatusBar;
1852 if (mapArgs.count("-testsafemode"))
1855 // Misc warnings like out of disk space and clock is wrong
1856 if (strMiscWarning != "")
1859 strStatusBar = strMiscWarning;
1862 // Longer invalid proof-of-work chain
1863 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1866 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1870 CRITICAL_BLOCK(cs_mapAlerts)
1872 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1874 const CAlert& alert = item.second;
1875 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1877 nPriority = alert.nPriority;
1878 strStatusBar = alert.strStatusBar;
1879 strRPC = alert.strRPCError;
1884 if (strFor == "statusbar")
1885 return strStatusBar;
1886 else if (strFor == "rpc")
1888 assert(("GetWarnings() : invalid parameter", false));
1892 bool CAlert::ProcessAlert()
1894 if (!CheckSignature())
1899 CRITICAL_BLOCK(cs_mapAlerts)
1901 // Cancel previous alerts
1902 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1904 const CAlert& alert = (*mi).second;
1907 printf("cancelling alert %d\n", alert.nID);
1908 mapAlerts.erase(mi++);
1910 else if (!alert.IsInEffect())
1912 printf("expiring alert %d\n", alert.nID);
1913 mapAlerts.erase(mi++);
1919 // Check if this alert has been cancelled
1920 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1922 const CAlert& alert = item.second;
1923 if (alert.Cancels(*this))
1925 printf("alert already cancelled by %d\n", alert.nID);
1931 mapAlerts.insert(make_pair(GetHash(), *this));
1934 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1946 //////////////////////////////////////////////////////////////////////////////
1952 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1956 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1957 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1959 // Don't know what it is, just say we already got one
1969 bool ProcessMessages(CNode* pfrom)
1971 CDataStream& vRecv = pfrom->vRecv;
1975 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
1979 // (4) message start
1988 // Scan for message start
1989 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
1990 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
1991 if (vRecv.end() - pstart < nHeaderSize)
1993 if (vRecv.size() > nHeaderSize)
1995 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
1996 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2000 if (pstart - vRecv.begin() > 0)
2001 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2002 vRecv.erase(vRecv.begin(), pstart);
2005 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2010 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2013 string strCommand = hdr.GetCommand();
2016 unsigned int nMessageSize = hdr.nMessageSize;
2017 if (nMessageSize > MAX_SIZE)
2019 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2022 if (nMessageSize > vRecv.size())
2024 // Rewind and wait for rest of message
2025 ///// need a mechanism to give up waiting for overlong message size error
2026 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2030 // Copy message to its own buffer
2031 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2032 vRecv.ignore(nMessageSize);
2035 if (vRecv.GetVersion() >= 209)
2037 uint256 hash = Hash(vMsg.begin(), vMsg.end());
2038 unsigned int nChecksum = 0;
2039 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2040 if (nChecksum != hdr.nChecksum)
2042 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2043 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2052 CRITICAL_BLOCK(cs_main)
2053 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2057 catch (std::ios_base::failure& e)
2059 if (strstr(e.what(), "end of data"))
2061 // Allow exceptions from underlength message on vRecv
2062 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());
2064 else if (strstr(e.what(), "size too large"))
2066 // Allow exceptions from overlong size
2067 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2071 PrintExceptionContinue(&e, "ProcessMessage()");
2074 catch (std::exception& e) {
2075 PrintExceptionContinue(&e, "ProcessMessage()");
2077 PrintExceptionContinue(NULL, "ProcessMessage()");
2081 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2091 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2093 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2094 RandAddSeedPerfmon();
2096 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2097 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2098 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2100 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2108 if (strCommand == "version")
2110 // Each connection can only send one version message
2111 if (pfrom->nVersion != 0)
2118 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2119 if (pfrom->nVersion == 10300)
2120 pfrom->nVersion = 300;
2121 if (pfrom->nVersion >= 106 && !vRecv.empty())
2122 vRecv >> addrFrom >> nNonce;
2123 if (pfrom->nVersion >= 106 && !vRecv.empty())
2124 vRecv >> pfrom->strSubVer;
2125 if (pfrom->nVersion >= 209 && !vRecv.empty())
2126 vRecv >> pfrom->nStartingHeight;
2128 if (pfrom->nVersion == 0)
2131 // Disconnect if we connected to ourself
2132 if (nNonce == nLocalHostNonce && nNonce > 1)
2134 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2135 pfrom->fDisconnect = true;
2139 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2142 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
2143 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
2146 AddTimeData(pfrom->addr.ip, nTime);
2149 if (pfrom->nVersion >= 209)
2150 pfrom->PushMessage("verack");
2151 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2152 if (pfrom->nVersion < 209)
2153 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2155 // Ask the first connected node for block updates
2156 static int nAskedForBlocks;
2157 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2160 pfrom->PushGetBlocks(pindexBest, uint256(0));
2164 CRITICAL_BLOCK(cs_mapAlerts)
2165 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2166 item.second.RelayTo(pfrom);
2168 pfrom->fSuccessfullyConnected = true;
2170 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2174 else if (pfrom->nVersion == 0)
2176 // Must have a version message before anything else
2181 else if (strCommand == "verack")
2183 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2187 else if (strCommand == "addr")
2189 vector<CAddress> vAddr;
2191 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
2193 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
2195 if (vAddr.size() > 1000)
2196 return error("message addr size() = %d", vAddr.size());
2198 // Store the new addresses
2199 foreach(CAddress& addr, vAddr)
2203 // ignore IPv6 for now, since it isn't implemented anyway
2206 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
2207 if (pfrom->fGetAddr || vAddr.size() > 10)
2208 addr.nTime -= 5 * 24 * 60 * 60;
2210 pfrom->AddAddressKnown(addr);
2211 if (!pfrom->fGetAddr && addr.IsRoutable())
2213 // Relay to a limited number of other nodes
2214 CRITICAL_BLOCK(cs_vNodes)
2216 // Use deterministic randomness to send to
2217 // the same places for 12 hours at a time
2218 static uint256 hashSalt;
2220 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2221 uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
2222 multimap<uint256, CNode*> mapMix;
2223 foreach(CNode* pnode, vNodes)
2224 mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
2225 int nRelayNodes = 2;
2226 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2227 ((*mi).second)->PushAddress(addr);
2231 if (vAddr.size() < 1000)
2232 pfrom->fGetAddr = false;
2236 else if (strCommand == "inv")
2240 if (vInv.size() > 50000)
2241 return error("message inv size() = %d", vInv.size());
2244 foreach(const CInv& inv, vInv)
2248 pfrom->AddInventoryKnown(inv);
2250 bool fAlreadyHave = AlreadyHave(txdb, inv);
2251 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2255 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2256 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2258 // Track requests for our stuff
2259 CRITICAL_BLOCK(cs_mapRequestCount)
2261 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2262 if (mi != mapRequestCount.end())
2269 else if (strCommand == "getdata")
2273 if (vInv.size() > 50000)
2274 return error("message getdata size() = %d", vInv.size());
2276 foreach(const CInv& inv, vInv)
2280 printf("received getdata for: %s\n", inv.ToString().c_str());
2282 if (inv.type == MSG_BLOCK)
2284 // Send block from disk
2285 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2286 if (mi != mapBlockIndex.end())
2288 //// could optimize this to send header straight from blockindex for client
2290 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2291 pfrom->PushMessage("block", block);
2293 // Trigger them to send a getblocks request for the next batch of inventory
2294 if (inv.hash == pfrom->hashContinue)
2296 // Bypass PushInventory, this must send even if redundant,
2297 // and we want it right after the last block so they don't
2298 // wait for other stuff first.
2300 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2301 pfrom->PushMessage("inv", vInv);
2302 pfrom->hashContinue = 0;
2306 else if (inv.IsKnownType())
2308 // Send stream from relay memory
2309 CRITICAL_BLOCK(cs_mapRelay)
2311 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2312 if (mi != mapRelay.end())
2313 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2317 // Track requests for our stuff
2318 CRITICAL_BLOCK(cs_mapRequestCount)
2320 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2321 if (mi != mapRequestCount.end())
2328 else if (strCommand == "getblocks")
2330 CBlockLocator locator;
2332 vRecv >> locator >> hashStop;
2334 // Find the first block the caller has in the main chain
2335 CBlockIndex* pindex = locator.GetBlockIndex();
2337 // Send the rest of the chain
2339 pindex = pindex->pnext;
2340 int nLimit = 500 + locator.GetDistanceBack();
2341 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2342 for (; pindex; pindex = pindex->pnext)
2344 if (pindex->GetBlockHash() == hashStop)
2346 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2349 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2352 // When this block is requested, we'll send an inv that'll make them
2353 // getblocks the next batch of inventory.
2354 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2355 pfrom->hashContinue = pindex->GetBlockHash();
2362 else if (strCommand == "tx")
2364 vector<uint256> vWorkQueue;
2365 CDataStream vMsg(vRecv);
2369 CInv inv(MSG_TX, tx.GetHash());
2370 pfrom->AddInventoryKnown(inv);
2372 bool fMissingInputs = false;
2373 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2375 AddToWalletIfMine(tx, NULL);
2376 RelayMessage(inv, vMsg);
2377 mapAlreadyAskedFor.erase(inv);
2378 vWorkQueue.push_back(inv.hash);
2380 // Recursively process any orphan transactions that depended on this one
2381 for (int i = 0; i < vWorkQueue.size(); i++)
2383 uint256 hashPrev = vWorkQueue[i];
2384 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2385 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2388 const CDataStream& vMsg = *((*mi).second);
2390 CDataStream(vMsg) >> tx;
2391 CInv inv(MSG_TX, tx.GetHash());
2393 if (tx.AcceptToMemoryPool(true))
2395 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2396 AddToWalletIfMine(tx, NULL);
2397 RelayMessage(inv, vMsg);
2398 mapAlreadyAskedFor.erase(inv);
2399 vWorkQueue.push_back(inv.hash);
2404 foreach(uint256 hash, vWorkQueue)
2405 EraseOrphanTx(hash);
2407 else if (fMissingInputs)
2409 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2415 else if (strCommand == "block")
2417 auto_ptr<CBlock> pblock(new CBlock);
2421 printf("received block %s\n", pblock->GetHash().ToString().substr(0,20).c_str());
2424 CInv inv(MSG_BLOCK, pblock->GetHash());
2425 pfrom->AddInventoryKnown(inv);
2427 if (ProcessBlock(pfrom, pblock.release()))
2428 mapAlreadyAskedFor.erase(inv);
2432 else if (strCommand == "getaddr")
2434 // Nodes rebroadcast an addr every 24 hours
2435 pfrom->vAddrToSend.clear();
2436 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2437 CRITICAL_BLOCK(cs_mapAddresses)
2439 unsigned int nCount = 0;
2440 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2442 const CAddress& addr = item.second;
2443 if (addr.nTime > nSince)
2446 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2448 const CAddress& addr = item.second;
2449 if (addr.nTime > nSince && GetRand(nCount) < 2000)
2450 pfrom->PushAddress(addr);
2456 else if (strCommand == "checkorder")
2460 vRecv >> hashReply >> order;
2462 if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2464 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2468 /// we have a chance to check the order here
2470 // Keep giving the same key to the same ip until they use it
2471 if (!mapReuseKey.count(pfrom->addr.ip))
2472 mapReuseKey[pfrom->addr.ip] = CWalletDB().GetKeyFromKeyPool();
2474 // Send back approval of order and pubkey to use
2475 CScript scriptPubKey;
2476 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2477 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2481 else if (strCommand == "submitorder")
2485 vRecv >> hashReply >> wtxNew;
2486 wtxNew.fFromMe = false;
2488 if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2490 pfrom->PushMessage("reply", hashReply, (int)2);
2495 if (!wtxNew.AcceptWalletTransaction())
2497 pfrom->PushMessage("reply", hashReply, (int)1);
2498 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2500 wtxNew.fTimeReceivedIsTxTime = true;
2501 AddToWallet(wtxNew);
2502 wtxNew.RelayWalletTransaction();
2503 mapReuseKey.erase(pfrom->addr.ip);
2505 // Send back confirmation
2506 pfrom->PushMessage("reply", hashReply, (int)0);
2510 else if (strCommand == "reply")
2515 CRequestTracker tracker;
2516 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2518 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2519 if (mi != pfrom->mapRequests.end())
2521 tracker = (*mi).second;
2522 pfrom->mapRequests.erase(mi);
2525 if (!tracker.IsNull())
2526 tracker.fn(tracker.param1, vRecv);
2530 else if (strCommand == "ping")
2535 else if (strCommand == "alert")
2540 if (alert.ProcessAlert())
2543 pfrom->setKnown.insert(alert.GetHash());
2544 CRITICAL_BLOCK(cs_vNodes)
2545 foreach(CNode* pnode, vNodes)
2546 alert.RelayTo(pnode);
2553 // Ignore unknown commands for extensibility
2557 // Update the last seen time for this node's address
2558 if (pfrom->fNetworkNode)
2559 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2560 AddressCurrentlyConnected(pfrom->addr);
2574 bool SendMessages(CNode* pto, bool fSendTrickle)
2576 CRITICAL_BLOCK(cs_main)
2578 // Don't send anything until we get their version message
2579 if (pto->nVersion == 0)
2583 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2584 pto->PushMessage("ping");
2586 // Address refresh broadcast
2587 static int64 nLastRebroadcast;
2588 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2590 nLastRebroadcast = GetTime();
2591 CRITICAL_BLOCK(cs_vNodes)
2593 foreach(CNode* pnode, vNodes)
2595 // Periodically clear setAddrKnown to allow refresh broadcasts
2596 pnode->setAddrKnown.clear();
2598 // Rebroadcast our address
2599 if (addrLocalHost.IsRoutable() && !fUseProxy)
2600 pnode->PushAddress(addrLocalHost);
2605 // Resend wallet transactions that haven't gotten in a block yet
2606 ResendWalletTransactions();
2614 vector<CAddress> vAddr;
2615 vAddr.reserve(pto->vAddrToSend.size());
2616 foreach(const CAddress& addr, pto->vAddrToSend)
2618 // returns true if wasn't already contained in the set
2619 if (pto->setAddrKnown.insert(addr).second)
2621 vAddr.push_back(addr);
2622 // receiver rejects addr messages larger than 1000
2623 if (vAddr.size() >= 1000)
2625 pto->PushMessage("addr", vAddr);
2630 pto->vAddrToSend.clear();
2632 pto->PushMessage("addr", vAddr);
2637 // Message: inventory
2640 vector<CInv> vInvWait;
2641 CRITICAL_BLOCK(pto->cs_inventory)
2643 vInv.reserve(pto->vInventoryToSend.size());
2644 vInvWait.reserve(pto->vInventoryToSend.size());
2645 foreach(const CInv& inv, pto->vInventoryToSend)
2647 if (pto->setInventoryKnown.count(inv))
2650 // trickle out tx inv to protect privacy
2651 if (inv.type == MSG_TX && !fSendTrickle)
2653 // 1/4 of tx invs blast to all immediately
2654 static uint256 hashSalt;
2656 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2657 uint256 hashRand = inv.hash ^ hashSalt;
2658 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2659 bool fTrickleWait = ((hashRand & 3) != 0);
2661 // always trickle our own transactions
2664 TRY_CRITICAL_BLOCK(cs_mapWallet)
2666 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2667 if (mi != mapWallet.end())
2669 CWalletTx& wtx = (*mi).second;
2671 fTrickleWait = true;
2678 vInvWait.push_back(inv);
2683 // returns true if wasn't already contained in the set
2684 if (pto->setInventoryKnown.insert(inv).second)
2686 vInv.push_back(inv);
2687 if (vInv.size() >= 1000)
2689 pto->PushMessage("inv", vInv);
2694 pto->vInventoryToSend = vInvWait;
2697 pto->PushMessage("inv", vInv);
2703 vector<CInv> vGetData;
2704 int64 nNow = GetTime() * 1000000;
2706 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2708 const CInv& inv = (*pto->mapAskFor.begin()).second;
2709 if (!AlreadyHave(txdb, inv))
2711 printf("sending getdata: %s\n", inv.ToString().c_str());
2712 vGetData.push_back(inv);
2713 if (vGetData.size() >= 1000)
2715 pto->PushMessage("getdata", vGetData);
2719 pto->mapAskFor.erase(pto->mapAskFor.begin());
2721 if (!vGetData.empty())
2722 pto->PushMessage("getdata", vGetData);
2741 //////////////////////////////////////////////////////////////////////////////
2746 void GenerateBitcoins(bool fGenerate)
2748 if (fGenerateBitcoins != fGenerate)
2750 fGenerateBitcoins = fGenerate;
2751 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2754 if (fGenerateBitcoins)
2756 int nProcessors = boost::thread::hardware_concurrency();
2757 printf("%d processors\n", nProcessors);
2758 if (nProcessors < 1)
2760 if (fLimitProcessors && nProcessors > nLimitProcessors)
2761 nProcessors = nLimitProcessors;
2762 int nAddThreads = nProcessors - vnThreadsRunning[3];
2763 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2764 for (int i = 0; i < nAddThreads; i++)
2766 if (!CreateThread(ThreadBitcoinMiner, NULL))
2767 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2773 void ThreadBitcoinMiner(void* parg)
2777 vnThreadsRunning[3]++;
2779 vnThreadsRunning[3]--;
2781 catch (std::exception& e) {
2782 vnThreadsRunning[3]--;
2783 PrintException(&e, "ThreadBitcoinMiner()");
2785 vnThreadsRunning[3]--;
2786 PrintException(NULL, "ThreadBitcoinMiner()");
2788 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
2790 if (vnThreadsRunning[3] == 0)
2792 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2795 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2796 void CallCPUID(int in, int& aret, int& cret)
2800 "mov %2, %%eax; " // in into eax
2802 "mov %%eax, %0;" // eax into a
2803 "mov %%ecx, %1;" // eax into c
2804 :"=r"(a),"=r"(c) /* output */
2805 :"r"(in) /* input */
2806 :"%eax","%ecx" /* clobbered register */
2812 bool Detect128BitSSE2()
2815 CallCPUID(0, a, nBrand);
2816 bool fIntel = (nBrand == 0x6c65746e); // ntel
2817 bool fAMD = (nBrand == 0x444d4163); // cAMD
2821 unsigned int nStepping : 4;
2822 unsigned int nModel : 4;
2823 unsigned int nFamily : 4;
2824 unsigned int nProcessorType : 2;
2825 unsigned int nUnused : 2;
2826 unsigned int nExtendedModel : 4;
2827 unsigned int nExtendedFamily : 8;
2831 memcpy(&cpu, &a, sizeof(cpu));
2832 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
2833 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
2835 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
2836 // Nehalem = i3/i5/i7 and some Xeon
2837 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
2838 // Intel Core i5 family 6, model 26 or 30
2839 // Intel Core i7 family 6, model 26 or 30
2840 // Intel Core i3 family 6, model 37
2841 // AMD Phenom family 16, model 10
2842 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
2843 (fAMD && nFamily * 10000 + nModel >= 160010));
2845 // AMD reports a lower model number in 64-bit mode
2846 if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
2849 static bool fPrinted;
2853 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
2858 bool Detect128BitSSE2() { return false; }
2861 int FormatHashBlocks(void* pbuffer, unsigned int len)
2863 unsigned char* pdata = (unsigned char*)pbuffer;
2864 unsigned int blocks = 1 + ((len + 8) / 64);
2865 unsigned char* pend = pdata + 64 * blocks;
2866 memset(pdata + len, 0, 64 * blocks - len);
2868 unsigned int bits = len * 8;
2869 pend[-1] = (bits >> 0) & 0xff;
2870 pend[-2] = (bits >> 8) & 0xff;
2871 pend[-3] = (bits >> 16) & 0xff;
2872 pend[-4] = (bits >> 24) & 0xff;
2876 using CryptoPP::ByteReverse;
2878 static const unsigned int pSHA256InitState[8] =
2879 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2881 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2883 memcpy(pstate, pinit, 32);
2884 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2888 // ScanHash scans nonces looking for a hash with at least some zero bits.
2889 // It operates on big endian data. Caller does the byte reversing.
2890 // All input buffers are 16-byte aligned. nNonce is usually preserved
2891 // between calls, but periodically or if nNonce is above 0xff000000,
2892 // the block is rebuilt and nNonce starts over at zero.
2894 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone)
2896 unsigned int& nNonce = *(unsigned int*)(pblock + 12);
2900 // Hash pblock using pmidstate as the starting state into
2901 // preformatted buffer phash1, then hash phash1 into phash
2903 SHA256Transform(phash1, pblock, pmidstate);
2904 SHA256Transform(phash, phash1, pSHA256InitState);
2906 // Return the nonce if the hash has at least some zero bits,
2907 // caller will check if it has enough to reach the target
2908 if (((unsigned short*)phash)[14] == 0)
2911 // If nothing found after trying for a while, return -1
2912 if ((nNonce & 0xffff) == 0)
2914 nHashesDone = 0xffff+1;
2920 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
2927 printf("BitcoinMiner started\n");
2928 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2929 bool f4WaySSE2 = Detect128BitSSE2();
2930 if (mapArgs.count("-4way"))
2931 f4WaySSE2 = (mapArgs["-4way"] != "0");
2933 CReserveKey reservekey;
2934 CBigNum bnExtraNonce = 0;
2935 while (fGenerateBitcoins)
2940 while (vNodes.empty() || IsInitialBlockDownload())
2945 if (!fGenerateBitcoins)
2949 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2950 CBlockIndex* pindexPrev = pindexBest;
2951 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2955 // Create coinbase tx
2958 txNew.vin.resize(1);
2959 txNew.vin[0].prevout.SetNull();
2960 txNew.vin[0].scriptSig << ++bnExtraNonce;
2961 txNew.vout.resize(1);
2962 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2968 auto_ptr<CBlock> pblock(new CBlock());
2972 // Add our coinbase tx as first transaction
2973 pblock->vtx.push_back(txNew);
2975 // Collect memory pool transactions into the block
2977 CRITICAL_BLOCK(cs_main)
2978 CRITICAL_BLOCK(cs_mapTransactions)
2981 map<uint256, CTxIndex> mapTestPool;
2982 vector<char> vfAlreadyAdded(mapTransactions.size());
2983 uint64 nBlockSize = 1000;
2984 int nBlockSigOps = 100;
2985 bool fFoundSomething = true;
2986 while (fFoundSomething)
2988 fFoundSomething = false;
2990 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
2992 if (vfAlreadyAdded[n])
2994 CTransaction& tx = (*mi).second;
2995 if (tx.IsCoinBase() || !tx.IsFinal())
2997 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2998 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3000 int nTxSigOps = tx.GetSigOpCount();
3001 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3004 // Transaction fee based on block size
3005 int64 nMinFee = tx.GetMinFee(nBlockSize);
3007 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3008 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3010 swap(mapTestPool, mapTestPoolTmp);
3012 pblock->vtx.push_back(tx);
3013 nBlockSize += nTxSize;
3014 nBlockSigOps += nTxSigOps;
3015 vfAlreadyAdded[n] = true;
3016 fFoundSomething = true;
3020 pblock->nBits = nBits;
3021 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3022 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3026 // Prebuild hash buffer
3033 uint256 hashPrevBlock;
3034 uint256 hashMerkleRoot;
3037 unsigned int nNonce;
3040 unsigned char pchPadding0[64];
3042 unsigned char pchPadding1[64];
3044 char tmpbuf[sizeof(tmpworkspace)+16];
3045 tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
3047 tmp.block.nVersion = pblock->nVersion;
3048 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
3049 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3050 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
3051 tmp.block.nBits = pblock->nBits = nBits;
3052 tmp.block.nNonce = pblock->nNonce = 0;
3054 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3055 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3057 // Byte swap all the input buffer
3058 for (int i = 0; i < sizeof(tmp)/4; i++)
3059 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3061 // Precalc the first half of the first hash, which stays constant
3062 uint256 midstatebuf[2];
3063 uint256& midstate = *alignup<16>(midstatebuf);
3064 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
3070 int64 nStart = GetTime();
3071 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3073 uint256& hash = *alignup<16>(hashbuf);
3076 unsigned int nHashesDone = 0;
3077 unsigned int nNonceFound;
3081 // tcatm's 4-way 128-bit SSE2 SHA-256
3082 nNonceFound = ScanHash_4WaySSE2((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3086 nNonceFound = ScanHash_CryptoPP((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3088 // Check if something found
3089 if (nNonceFound != -1)
3091 for (int i = 0; i < sizeof(hash)/4; i++)
3092 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3094 if (hash <= hashTarget)
3097 pblock->nNonce = ByteReverse(nNonceFound);
3098 assert(hash == pblock->GetHash());
3101 printf("BitcoinMiner:\n");
3102 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3104 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3105 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3107 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3108 CRITICAL_BLOCK(cs_main)
3110 if (pindexPrev == pindexBest)
3112 // Remove key from key pool
3113 reservekey.KeepKey();
3115 // Track how many getdata requests this block gets
3116 CRITICAL_BLOCK(cs_mapRequestCount)
3117 mapRequestCount[pblock->GetHash()] = 0;
3119 // Process this block the same as if we had received it from another node
3120 if (!ProcessBlock(NULL, pblock.release()))
3121 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
3124 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3132 static int64 nHashCounter;
3133 if (nHPSTimerStart == 0)
3135 nHPSTimerStart = GetTimeMillis();
3139 nHashCounter += nHashesDone;
3140 if (GetTimeMillis() - nHPSTimerStart > 4000)
3142 static CCriticalSection cs;
3145 if (GetTimeMillis() - nHPSTimerStart > 4000)
3147 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3148 nHPSTimerStart = GetTimeMillis();
3150 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3151 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3152 static int64 nLogTime;
3153 if (GetTime() - nLogTime > 30 * 60)
3155 nLogTime = GetTime();
3156 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3157 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3163 // Check for stop or if block needs to be rebuilt
3166 if (!fGenerateBitcoins)
3168 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3172 if (tmp.block.nNonce >= 0xff000000)
3174 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3176 if (pindexPrev != pindexBest)
3179 // Update nTime every few seconds
3180 int64 nNewTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3181 if (nNewTime != pblock->nTime && bnExtraNonce > 10)
3183 pblock->nTime = nNewTime;
3184 tmp.block.nTime = ByteReverse(pblock->nTime);
3206 //////////////////////////////////////////////////////////////////////////////
3214 int64 nStart = GetTimeMillis();
3217 CRITICAL_BLOCK(cs_mapWallet)
3219 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3221 CWalletTx* pcoin = &(*it).second;
3222 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3224 nTotal += pcoin->GetCredit(true);
3228 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3233 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3235 setCoinsRet.clear();
3237 // List of values less than target
3238 int64 nLowestLarger = INT64_MAX;
3239 CWalletTx* pcoinLowestLarger = NULL;
3240 vector<pair<int64, CWalletTx*> > vValue;
3241 int64 nTotalLower = 0;
3243 CRITICAL_BLOCK(cs_mapWallet)
3245 vector<CWalletTx*> vCoins;
3246 vCoins.reserve(mapWallet.size());
3247 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3248 vCoins.push_back(&(*it).second);
3249 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3251 foreach(CWalletTx* pcoin, vCoins)
3253 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3255 int64 n = pcoin->GetCredit();
3258 if (n < nTargetValue)
3260 vValue.push_back(make_pair(n, pcoin));
3263 else if (n == nTargetValue)
3265 setCoinsRet.insert(pcoin);
3268 else if (n < nLowestLarger)
3271 pcoinLowestLarger = pcoin;
3276 if (nTotalLower < nTargetValue)
3278 if (pcoinLowestLarger == NULL)
3280 setCoinsRet.insert(pcoinLowestLarger);
3284 // Solve subset sum by stochastic approximation
3285 sort(vValue.rbegin(), vValue.rend());
3286 vector<char> vfIncluded;
3287 vector<char> vfBest(vValue.size(), true);
3288 int64 nBest = nTotalLower;
3290 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3292 vfIncluded.assign(vValue.size(), false);
3294 bool fReachedTarget = false;
3295 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3297 for (int i = 0; i < vValue.size(); i++)
3299 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3301 nTotal += vValue[i].first;
3302 vfIncluded[i] = true;
3303 if (nTotal >= nTargetValue)
3305 fReachedTarget = true;
3309 vfBest = vfIncluded;
3311 nTotal -= vValue[i].first;
3312 vfIncluded[i] = false;
3319 // If the next larger is still closer, return it
3320 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3321 setCoinsRet.insert(pcoinLowestLarger);
3324 for (int i = 0; i < vValue.size(); i++)
3326 setCoinsRet.insert(vValue[i].second);
3329 printf("SelectCoins() best subset: ");
3330 for (int i = 0; i < vValue.size(); i++)
3332 printf("%s ", FormatMoney(vValue[i].first).c_str());
3333 printf("total %s\n", FormatMoney(nBest).c_str());
3342 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRequiredRet)
3344 nFeeRequiredRet = 0;
3345 CRITICAL_BLOCK(cs_main)
3347 // txdb must be opened before the mapWallet lock
3349 CRITICAL_BLOCK(cs_mapWallet)
3351 int64 nFee = nTransactionFee;
3355 wtxNew.vout.clear();
3356 wtxNew.fFromMe = true;
3359 int64 nValueOut = nValue;
3360 int64 nTotalValue = nValue + nFee;
3362 // Choose coins to use
3363 set<CWalletTx*> setCoins;
3364 if (!SelectCoins(nTotalValue, setCoins))
3367 foreach(CWalletTx* pcoin, setCoins)
3368 nValueIn += pcoin->GetCredit();
3370 // Fill a vout to the payee
3371 bool fChangeFirst = GetRand(2);
3373 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3375 // Fill a vout back to self with any change
3376 int64 nChange = nValueIn - nTotalValue;
3377 if (nChange >= CENT)
3379 // Note: We use a new key here to keep it from being obvious which side is the change.
3380 // The drawback is that by not reusing a previous key, the change may be lost if a
3381 // backup is restored, if the backup doesn't have the new private key for the change.
3382 // If we reused the old key, it would be possible to add code to look for and
3383 // rediscover unknown transactions that were written with keys of ours to recover
3384 // post-backup change.
3386 // Reserve a new key pair from key pool
3387 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3388 assert(mapKeys.count(vchPubKey));
3390 // Fill a vout to ourself, using same address type as the payment
3391 CScript scriptChange;
3392 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3393 scriptChange.SetBitcoinAddress(vchPubKey);
3395 scriptChange << vchPubKey << OP_CHECKSIG;
3396 wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3399 reservekey.ReturnKey();
3401 // Fill a vout to the payee
3403 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3406 foreach(CWalletTx* pcoin, setCoins)
3407 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3408 if (pcoin->vout[nOut].IsMine())
3409 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3413 foreach(CWalletTx* pcoin, setCoins)
3414 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3415 if (pcoin->vout[nOut].IsMine())
3416 if (!SignSignature(*pcoin, wtxNew, nIn++))
3420 if (::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK) >= MAX_BLOCK_SIZE_GEN/5)
3423 // Check that enough fee is included
3424 if (nFee < wtxNew.GetMinFee())
3426 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3430 // Fill vtxPrev by copying from previous transactions vtxPrev
3431 wtxNew.AddSupportingTransactions(txdb);
3432 wtxNew.fTimeReceivedIsTxTime = true;
3441 // Call after CreateTransaction unless you want to abort
3442 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3444 CRITICAL_BLOCK(cs_main)
3446 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3447 CRITICAL_BLOCK(cs_mapWallet)
3449 // This is only to keep the database open to defeat the auto-flush for the
3450 // duration of this scope. This is the only place where this optimization
3451 // maybe makes sense; please don't do it anywhere else.
3452 CWalletDB walletdb("r");
3454 // Take key pair from key pool so it won't be used again
3455 reservekey.KeepKey();
3457 // Add tx to wallet, because if it has change it's also ours,
3458 // otherwise just for transaction history.
3459 AddToWallet(wtxNew);
3461 // Mark old coins as spent
3462 set<CWalletTx*> setCoins;
3463 foreach(const CTxIn& txin, wtxNew.vin)
3464 setCoins.insert(&mapWallet[txin.prevout.hash]);
3465 foreach(CWalletTx* pcoin, setCoins)
3467 pcoin->fSpent = true;
3468 pcoin->WriteToDisk();
3469 vWalletUpdated.push_back(pcoin->GetHash());
3473 // Track how many getdata requests our transaction gets
3474 CRITICAL_BLOCK(cs_mapRequestCount)
3475 mapRequestCount[wtxNew.GetHash()] = 0;
3478 if (!wtxNew.AcceptToMemoryPool())
3480 // This must not fail. The transaction has already been signed and recorded.
3481 printf("CommitTransaction() : Error: Transaction not valid");
3484 wtxNew.RelayWalletTransaction();
3493 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3495 CRITICAL_BLOCK(cs_main)
3497 CReserveKey reservekey;
3499 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3502 if (nValue + nFeeRequired > GetBalance())
3503 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3505 strError = _("Error: Transaction creation failed ");
3506 printf("SendMoney() : %s", strError.c_str());
3510 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3513 if (!CommitTransaction(wtxNew, reservekey))
3514 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.");
3522 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3526 return _("Invalid amount");
3527 if (nValue + nTransactionFee > GetBalance())
3528 return _("Insufficient funds");
3530 // Parse bitcoin address
3531 CScript scriptPubKey;
3532 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3533 return _("Invalid bitcoin address");
3535 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);