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 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
25 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
26 CBlockIndex* pindexGenesisBlock = NULL;
28 CBigNum bnBestChainWork = 0;
29 CBigNum bnBestInvalidWork = 0;
30 uint256 hashBestChain = 0;
31 CBlockIndex* pindexBest = NULL;
32 int64 nTimeBestReceived = 0;
34 map<uint256, CBlock*> mapOrphanBlocks;
35 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
37 map<uint256, CDataStream*> mapOrphanTransactions;
38 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
40 map<uint256, CWalletTx> mapWallet;
41 vector<uint256> vWalletUpdated;
42 CCriticalSection cs_mapWallet;
44 map<vector<unsigned char>, CPrivKey> mapKeys;
45 map<uint160, vector<unsigned char> > mapPubKeys;
46 CCriticalSection cs_mapKeys;
49 map<uint256, int> mapRequestCount;
50 CCriticalSection cs_mapRequestCount;
52 map<string, string> mapAddressBook;
53 CCriticalSection cs_mapAddressBook;
55 vector<unsigned char> vchDefaultKey;
61 int fGenerateBitcoins = false;
62 int64 nTransactionFee = 0;
63 CAddress addrIncoming;
64 int fLimitProcessors = false;
65 int nLimitProcessors = 1;
66 int fMinimizeToTray = true;
67 int fMinimizeOnClose = true;
82 //////////////////////////////////////////////////////////////////////////////
87 bool AddKey(const CKey& key)
89 CRITICAL_BLOCK(cs_mapKeys)
91 mapKeys[key.GetPubKey()] = key.GetPrivKey();
92 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
94 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
97 vector<unsigned char> GenerateNewKey()
103 throw runtime_error("GenerateNewKey() : AddKey failed");
104 return key.GetPubKey();
110 //////////////////////////////////////////////////////////////////////////////
115 bool AddToWallet(const CWalletTx& wtxIn)
117 uint256 hash = wtxIn.GetHash();
118 CRITICAL_BLOCK(cs_mapWallet)
120 // Inserts only if not already there, returns tx inserted or tx found
121 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
122 CWalletTx& wtx = (*ret.first).second;
123 bool fInsertedNew = ret.second;
125 wtx.nTimeReceived = GetAdjustedTime();
127 bool fUpdated = false;
131 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
133 wtx.hashBlock = wtxIn.hashBlock;
136 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
138 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
139 wtx.nIndex = wtxIn.nIndex;
142 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
144 wtx.fFromMe = wtxIn.fFromMe;
147 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
151 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
154 if (fInsertedNew || fUpdated)
155 if (!wtx.WriteToDisk())
158 // If default receiving address gets used, replace it with a new one
159 CScript scriptDefaultKey;
160 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
161 foreach(const CTxOut& txout, wtx.vout)
163 if (txout.scriptPubKey == scriptDefaultKey)
166 vchDefaultKey = GetKeyFromKeyPool();
167 walletdb.WriteDefaultKey(vchDefaultKey);
168 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
173 vWalletUpdated.push_back(hash);
181 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
183 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
186 // Get merkle branch if transaction was found in a block
188 wtx.SetMerkleBranch(pblock);
189 return AddToWallet(wtx);
194 bool AddToWalletIfFromMe(const CTransaction& tx, const CBlock* pblock)
196 if (tx.IsFromMe() || mapWallet.count(tx.GetHash()))
199 // Get merkle branch if transaction was found in a block
201 wtx.SetMerkleBranch(pblock);
202 return AddToWallet(wtx);
207 bool EraseFromWallet(uint256 hash)
209 CRITICAL_BLOCK(cs_mapWallet)
211 if (mapWallet.erase(hash))
212 CWalletDB().EraseTx(hash);
217 void WalletUpdateSpent(const COutPoint& prevout)
219 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
220 // Update the wallet spent flag if it doesn't know due to wallet.dat being
221 // restored from backup or the user making copies of wallet.dat.
222 CRITICAL_BLOCK(cs_mapWallet)
224 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
225 if (mi != mapWallet.end())
227 CWalletTx& wtx = (*mi).second;
228 if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())
230 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
231 wtx.MarkSpent(prevout.n);
233 vWalletUpdated.push_back(prevout.hash);
246 //////////////////////////////////////////////////////////////////////////////
248 // mapOrphanTransactions
251 void AddOrphanTx(const CDataStream& vMsg)
254 CDataStream(vMsg) >> tx;
255 uint256 hash = tx.GetHash();
256 if (mapOrphanTransactions.count(hash))
258 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
259 foreach(const CTxIn& txin, tx.vin)
260 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
263 void EraseOrphanTx(uint256 hash)
265 if (!mapOrphanTransactions.count(hash))
267 const CDataStream* pvMsg = mapOrphanTransactions[hash];
269 CDataStream(*pvMsg) >> tx;
270 foreach(const CTxIn& txin, tx.vin)
272 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
273 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
275 if ((*mi).second == pvMsg)
276 mapOrphanTransactionsByPrev.erase(mi++);
282 mapOrphanTransactions.erase(hash);
292 //////////////////////////////////////////////////////////////////////////////
294 // CTransaction and CTxIndex
297 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
300 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
302 if (!ReadFromDisk(txindexRet.pos))
304 if (prevout.n >= vout.size())
312 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
315 return ReadFromDisk(txdb, prevout, txindex);
318 bool CTransaction::ReadFromDisk(COutPoint prevout)
322 return ReadFromDisk(txdb, prevout, txindex);
325 bool CTxIn::IsMine() const
327 CRITICAL_BLOCK(cs_mapWallet)
329 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
330 if (mi != mapWallet.end())
332 const CWalletTx& prev = (*mi).second;
333 if (prevout.n < prev.vout.size())
334 if (prev.vout[prevout.n].IsMine())
341 int64 CTxIn::GetDebit() const
343 CRITICAL_BLOCK(cs_mapWallet)
345 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
346 if (mi != mapWallet.end())
348 const CWalletTx& prev = (*mi).second;
349 if (prevout.n < prev.vout.size())
350 if (prev.vout[prevout.n].IsMine())
351 return prev.vout[prevout.n].nValue;
357 int64 CWalletTx::GetTxTime() const
359 if (!fTimeReceivedIsTxTime && hashBlock != 0)
361 // If we did not receive the transaction directly, we rely on the block's
362 // time to figure out when it happened. We use the median over a range
363 // of blocks to try to filter out inaccurate block times.
364 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
365 if (mi != mapBlockIndex.end())
367 CBlockIndex* pindex = (*mi).second;
369 return pindex->GetMedianTime();
372 return nTimeReceived;
375 int CWalletTx::GetRequestCount() const
377 // Returns -1 if it wasn't being tracked
379 CRITICAL_BLOCK(cs_mapRequestCount)
386 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
387 if (mi != mapRequestCount.end())
388 nRequests = (*mi).second;
393 // Did anyone request this transaction?
394 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
395 if (mi != mapRequestCount.end())
397 nRequests = (*mi).second;
399 // How about the block it's in?
400 if (nRequests == 0 && hashBlock != 0)
402 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
403 if (mi != mapRequestCount.end())
404 nRequests = (*mi).second;
406 nRequests = 1; // If it's in someone else's block it must have got out
414 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
415 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
417 nGeneratedImmature = nGeneratedMature = nFee = 0;
418 listReceived.clear();
420 strSentAccount = strFromAccount;
424 if (GetBlocksToMaturity() > 0)
425 nGeneratedImmature = CTransaction::GetCredit();
427 nGeneratedMature = GetCredit();
432 int64 nDebit = GetDebit();
433 if (nDebit > 0) // debit>0 means we signed/sent this transaction
435 int64 nValueOut = GetValueOut();
436 nFee = nDebit - nValueOut;
439 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
440 // but non-standard clients might (so return a list of address/amount pairs)
441 foreach(const CTxOut& txout, vout)
445 vector<unsigned char> vchPubKey;
446 if (ExtractHash160(txout.scriptPubKey, hash160))
447 address = Hash160ToAddress(hash160);
448 else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))
449 address = PubKeyToAddress(vchPubKey);
452 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
453 this->GetHash().ToString().c_str());
454 address = " unknown ";
457 // Don't report 'change' txouts
458 if (nDebit > 0 && txout.IsChange())
462 listSent.push_back(make_pair(address, txout.nValue));
465 listReceived.push_back(make_pair(address, txout.nValue));
470 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
471 int64& nSent, int64& nFee) const
473 nGenerated = nReceived = nSent = nFee = 0;
475 int64 allGeneratedImmature, allGeneratedMature, allFee;
476 allGeneratedImmature = allGeneratedMature = allFee = 0;
477 string strSentAccount;
478 list<pair<string, int64> > listReceived;
479 list<pair<string, int64> > listSent;
480 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
482 if (strAccount == "")
483 nGenerated = allGeneratedMature;
484 if (strAccount == strSentAccount)
486 foreach(const PAIRTYPE(string,int64)& s, listSent)
490 CRITICAL_BLOCK(cs_mapAddressBook)
492 foreach(const PAIRTYPE(string,int64)& r, listReceived)
494 if (mapAddressBook.count(r.first))
496 if (mapAddressBook[r.first] == strAccount)
498 nReceived += r.second;
501 else if (strAccount.empty())
503 nReceived += r.second;
511 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
523 // Load the block this tx is in
525 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
527 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
532 // Update the tx's hashBlock
533 hashBlock = pblock->GetHash();
535 // Locate the transaction
536 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
537 if (pblock->vtx[nIndex] == *(CTransaction*)this)
539 if (nIndex == pblock->vtx.size())
541 vMerkleBranch.clear();
543 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
547 // Fill in merkle branch
548 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
551 // Is the tx in a block that's in the main chain
552 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
553 if (mi == mapBlockIndex.end())
555 CBlockIndex* pindex = (*mi).second;
556 if (!pindex || !pindex->IsInMainChain())
559 return pindexBest->nHeight - pindex->nHeight + 1;
564 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
568 const int COPY_DEPTH = 3;
569 if (SetMerkleBranch() < COPY_DEPTH)
571 vector<uint256> vWorkQueue;
572 foreach(const CTxIn& txin, vin)
573 vWorkQueue.push_back(txin.prevout.hash);
575 // This critsect is OK because txdb is already open
576 CRITICAL_BLOCK(cs_mapWallet)
578 map<uint256, const CMerkleTx*> mapWalletPrev;
579 set<uint256> setAlreadyDone;
580 for (int i = 0; i < vWorkQueue.size(); i++)
582 uint256 hash = vWorkQueue[i];
583 if (setAlreadyDone.count(hash))
585 setAlreadyDone.insert(hash);
588 if (mapWallet.count(hash))
590 tx = mapWallet[hash];
591 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
592 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
594 else if (mapWalletPrev.count(hash))
596 tx = *mapWalletPrev[hash];
598 else if (!fClient && txdb.ReadDiskTx(hash, tx))
604 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
608 int nDepth = tx.SetMerkleBranch();
609 vtxPrev.push_back(tx);
611 if (nDepth < COPY_DEPTH)
612 foreach(const CTxIn& txin, tx.vin)
613 vWorkQueue.push_back(txin.prevout.hash);
618 reverse(vtxPrev.begin(), vtxPrev.end());
631 bool CTransaction::CheckTransaction() const
633 // Basic checks that don't depend on any context
634 if (vin.empty() || vout.empty())
635 return error("CTransaction::CheckTransaction() : vin or vout empty");
638 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
639 return error("CTransaction::CheckTransaction() : size limits failed");
641 // Check for negative or overflow output values
643 foreach(const CTxOut& txout, vout)
645 if (txout.nValue < 0)
646 return error("CTransaction::CheckTransaction() : txout.nValue negative");
647 if (txout.nValue > MAX_MONEY)
648 return error("CTransaction::CheckTransaction() : txout.nValue too high");
649 nValueOut += txout.nValue;
650 if (!MoneyRange(nValueOut))
651 return error("CTransaction::CheckTransaction() : txout total out of range");
656 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
657 return error("CTransaction::CheckTransaction() : coinbase script size");
661 foreach(const CTxIn& txin, vin)
662 if (txin.prevout.IsNull())
663 return error("CTransaction::CheckTransaction() : prevout is null");
669 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
672 *pfMissingInputs = false;
674 if (!CheckTransaction())
675 return error("AcceptToMemoryPool() : CheckTransaction failed");
677 // Coinbase is only valid in a block, not as a loose transaction
679 return error("AcceptToMemoryPool() : coinbase as individual tx");
681 // To help v0.1.5 clients who would see it as a negative number
682 if ((int64)nLockTime > INT_MAX)
683 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
686 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
687 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
688 // attacks disallow transactions with more than one SigOp per 34 bytes.
689 // 34 bytes because a TxOut is:
690 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
691 if (GetSigOpCount() > nSize / 34 || nSize < 100)
692 return error("AcceptToMemoryPool() : nonstandard transaction");
694 // Rather not work on nonstandard transactions
696 return error("AcceptToMemoryPool() : nonstandard transaction type");
698 // Do we already have it?
699 uint256 hash = GetHash();
700 CRITICAL_BLOCK(cs_mapTransactions)
701 if (mapTransactions.count(hash))
704 if (txdb.ContainsTx(hash))
707 // Check for conflicts with in-memory transactions
708 CTransaction* ptxOld = NULL;
709 for (int i = 0; i < vin.size(); i++)
711 COutPoint outpoint = vin[i].prevout;
712 if (mapNextTx.count(outpoint))
714 // Disable replacement feature for now
717 // Allow replacing with a newer version of the same transaction
720 ptxOld = mapNextTx[outpoint].ptx;
721 if (ptxOld->IsFinal())
723 if (!IsNewerThan(*ptxOld))
725 for (int i = 0; i < vin.size(); i++)
727 COutPoint outpoint = vin[i].prevout;
728 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
737 // Check against previous transactions
738 map<uint256, CTxIndex> mapUnused;
740 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
743 *pfMissingInputs = true;
744 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
747 // Don't accept it if it can't get into a block
748 if (nFees < GetMinFee(1000))
749 return error("AcceptToMemoryPool() : not enough fees");
751 // Continuously rate-limit free transactions
752 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
753 // be annoying or make other's transactions take longer to confirm.
756 static CCriticalSection cs;
757 static double dFreeCount;
758 static int64 nLastTime;
759 int64 nNow = GetTime();
763 // Use an exponentially decaying ~10-minute window:
764 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
766 // -limitfreerelay unit is thousand-bytes-per-minute
767 // At default rate it would take over a month to fill 1GB
768 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())
769 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
771 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
777 // Store transaction in memory
778 CRITICAL_BLOCK(cs_mapTransactions)
782 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
783 ptxOld->RemoveFromMemoryPool();
785 AddToMemoryPoolUnchecked();
788 ///// are we sure this is ok when loading transactions or restoring block txes
789 // If updated, erase old tx from wallet
791 EraseFromWallet(ptxOld->GetHash());
793 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
798 bool CTransaction::AddToMemoryPoolUnchecked()
800 // Add to memory pool without checking anything. Don't call this directly,
801 // call AcceptToMemoryPool to properly check the transaction first.
802 CRITICAL_BLOCK(cs_mapTransactions)
804 uint256 hash = GetHash();
805 mapTransactions[hash] = *this;
806 for (int i = 0; i < vin.size(); i++)
807 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
808 nTransactionsUpdated++;
814 bool CTransaction::RemoveFromMemoryPool()
816 // Remove transaction from memory pool
817 CRITICAL_BLOCK(cs_mapTransactions)
819 foreach(const CTxIn& txin, vin)
820 mapNextTx.erase(txin.prevout);
821 mapTransactions.erase(GetHash());
822 nTransactionsUpdated++;
832 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
834 if (hashBlock == 0 || nIndex == -1)
837 // Find the block it claims to be in
838 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
839 if (mi == mapBlockIndex.end())
841 CBlockIndex* pindex = (*mi).second;
842 if (!pindex || !pindex->IsInMainChain())
845 // Make sure the merkle branch connects to this block
846 if (!fMerkleVerified)
848 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
850 fMerkleVerified = true;
853 nHeightRet = pindex->nHeight;
854 return pindexBest->nHeight - pindex->nHeight + 1;
858 int CMerkleTx::GetBlocksToMaturity() const
862 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
866 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
870 if (!IsInMainChain() && !ClientConnectInputs())
872 return CTransaction::AcceptToMemoryPool(txdb, false);
876 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
882 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
884 CRITICAL_BLOCK(cs_mapTransactions)
886 // Add previous supporting transactions first
887 foreach(CMerkleTx& tx, vtxPrev)
889 if (!tx.IsCoinBase())
891 uint256 hash = tx.GetHash();
892 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
893 tx.AcceptToMemoryPool(txdb, fCheckInputs);
896 return AcceptToMemoryPool(txdb, fCheckInputs);
901 int ScanForWalletTransactions(CBlockIndex* pindexStart)
905 CBlockIndex* pindex = pindexStart;
906 CRITICAL_BLOCK(cs_mapWallet)
911 block.ReadFromDisk(pindex, true);
912 foreach(CTransaction& tx, block.vtx)
914 uint256 hash = tx.GetHash();
915 if (mapWallet.count(hash)) continue;
916 AddToWalletIfMine(tx, &block);
917 if (mapWallet.count(hash))
920 printf("Added missing RECEIVE %s\n", hash.ToString().c_str());
923 AddToWalletIfFromMe(tx, &block);
924 if (mapWallet.count(hash))
927 printf("Added missing SEND %s\n", hash.ToString().c_str());
931 pindex = pindex->pnext;
937 void ReacceptWalletTransactions()
941 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
944 vector<CDiskTxPos> vMissingTx;
945 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
947 CWalletTx& wtx = item.second;
948 if (wtx.IsCoinBase() && wtx.IsSpent(0))
952 bool fUpdated = false;
953 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
955 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
956 if (txindex.vSpent.size() != wtx.vout.size())
958 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
961 for (int i = 0; i < txindex.vSpent.size(); i++)
965 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
969 vMissingTx.push_back(txindex.vSpent[i]);
974 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
981 // Reaccept any txes of ours that aren't already in a block
982 if (!wtx.IsCoinBase())
983 wtx.AcceptWalletTransaction(txdb, false);
986 if (!vMissingTx.empty())
988 // TODO: optimize this to scan just part of the block chain?
989 if (ScanForWalletTransactions(pindexGenesisBlock))
990 fRepeat = true; // Found missing transactions: re-do Reaccept.
996 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
998 foreach(const CMerkleTx& tx, vtxPrev)
1000 if (!tx.IsCoinBase())
1002 uint256 hash = tx.GetHash();
1003 if (!txdb.ContainsTx(hash))
1004 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
1009 uint256 hash = GetHash();
1010 if (!txdb.ContainsTx(hash))
1012 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1013 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
1018 void ResendWalletTransactions()
1020 // Do this infrequently and randomly to avoid giving away
1021 // that these are our transactions.
1022 static int64 nNextTime;
1023 if (GetTime() < nNextTime)
1025 bool fFirst = (nNextTime == 0);
1026 nNextTime = GetTime() + GetRand(30 * 60);
1030 // Only do it if there's been a new block since last time
1031 static int64 nLastTime;
1032 if (nTimeBestReceived < nLastTime)
1034 nLastTime = GetTime();
1036 // Rebroadcast any of our txes that aren't in a block yet
1037 printf("ResendWalletTransactions()\n");
1039 CRITICAL_BLOCK(cs_mapWallet)
1041 // Sort them in chronological order
1042 multimap<unsigned int, CWalletTx*> mapSorted;
1043 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1045 CWalletTx& wtx = item.second;
1046 // Don't rebroadcast until it's had plenty of time that
1047 // it should have gotten in already by now.
1048 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1049 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1051 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1053 CWalletTx& wtx = *item.second;
1054 wtx.RelayWalletTransaction(txdb);
1059 int CTxIndex::GetDepthInMainChain() const
1061 // Read block header
1063 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
1065 // Find the block in the index
1066 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
1067 if (mi == mapBlockIndex.end())
1069 CBlockIndex* pindex = (*mi).second;
1070 if (!pindex || !pindex->IsInMainChain())
1072 return 1 + nBestHeight - pindex->nHeight;
1084 //////////////////////////////////////////////////////////////////////////////
1086 // CBlock and CBlockIndex
1089 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1091 if (!fReadTransactions)
1093 *this = pindex->GetBlockHeader();
1096 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1098 if (GetHash() != pindex->GetBlockHash())
1099 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1103 uint256 GetOrphanRoot(const CBlock* pblock)
1105 // Work back to the first block in the orphan chain
1106 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1107 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1108 return pblock->GetHash();
1111 int64 GetBlockValue(int nHeight, int64 nFees)
1113 int64 nSubsidy = 50 * COIN;
1115 // Subsidy is cut in half every 4 years
1116 nSubsidy >>= (nHeight / 210000);
1118 return nSubsidy + nFees;
1121 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1123 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1124 const int64 nTargetSpacing = 10 * 60;
1125 const int64 nInterval = nTargetTimespan / nTargetSpacing;
1128 if (pindexLast == NULL)
1129 return bnProofOfWorkLimit.GetCompact();
1131 // Only change once per interval
1132 if ((pindexLast->nHeight+1) % nInterval != 0)
1133 return pindexLast->nBits;
1135 // Go back by what we want to be 14 days worth of blocks
1136 const CBlockIndex* pindexFirst = pindexLast;
1137 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1138 pindexFirst = pindexFirst->pprev;
1139 assert(pindexFirst);
1141 // Limit adjustment step
1142 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1143 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1144 if (nActualTimespan < nTargetTimespan/4)
1145 nActualTimespan = nTargetTimespan/4;
1146 if (nActualTimespan > nTargetTimespan*4)
1147 nActualTimespan = nTargetTimespan*4;
1151 bnNew.SetCompact(pindexLast->nBits);
1152 bnNew *= nActualTimespan;
1153 bnNew /= nTargetTimespan;
1155 if (bnNew > bnProofOfWorkLimit)
1156 bnNew = bnProofOfWorkLimit;
1159 printf("GetNextWorkRequired RETARGET\n");
1160 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1161 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1162 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1164 return bnNew.GetCompact();
1167 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1170 bnTarget.SetCompact(nBits);
1173 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1174 return error("CheckProofOfWork() : nBits below minimum work");
1176 // Check proof of work matches claimed amount
1177 if (hash > bnTarget.getuint256())
1178 return error("CheckProofOfWork() : hash doesn't match nBits");
1183 bool IsInitialBlockDownload()
1185 if (pindexBest == NULL || (!fTestNet && nBestHeight < 118000))
1187 static int64 nLastUpdate;
1188 static CBlockIndex* pindexLastBest;
1189 if (pindexBest != pindexLastBest)
1191 pindexLastBest = pindexBest;
1192 nLastUpdate = GetTime();
1194 return (GetTime() - nLastUpdate < 10 &&
1195 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1198 void InvalidChainFound(CBlockIndex* pindexNew)
1200 if (pindexNew->bnChainWork > bnBestInvalidWork)
1202 bnBestInvalidWork = pindexNew->bnChainWork;
1203 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1206 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());
1207 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1208 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1209 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1222 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1224 // Relinquish previous transactions' spent pointers
1227 foreach(const CTxIn& txin, vin)
1229 COutPoint prevout = txin.prevout;
1231 // Get prev txindex from disk
1233 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1234 return error("DisconnectInputs() : ReadTxIndex failed");
1236 if (prevout.n >= txindex.vSpent.size())
1237 return error("DisconnectInputs() : prevout.n out of range");
1239 // Mark outpoint as not spent
1240 txindex.vSpent[prevout.n].SetNull();
1243 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1244 return error("DisconnectInputs() : UpdateTxIndex failed");
1248 // Remove transaction from index
1249 if (!txdb.EraseTxIndex(*this))
1250 return error("DisconnectInputs() : EraseTxPos failed");
1256 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1257 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1259 // Take over previous transactions' spent pointers
1263 for (int i = 0; i < vin.size(); i++)
1265 COutPoint prevout = vin[i].prevout;
1270 if (fMiner && mapTestPool.count(prevout.hash))
1272 // Get txindex from current proposed changes
1273 txindex = mapTestPool[prevout.hash];
1277 // Read txindex from txdb
1278 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1280 if (!fFound && (fBlock || fMiner))
1281 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());
1284 CTransaction txPrev;
1285 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1287 // Get prev tx from single transactions in memory
1288 CRITICAL_BLOCK(cs_mapTransactions)
1290 if (!mapTransactions.count(prevout.hash))
1291 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1292 txPrev = mapTransactions[prevout.hash];
1295 txindex.vSpent.resize(txPrev.vout.size());
1299 // Get prev tx from disk
1300 if (!txPrev.ReadFromDisk(txindex.pos))
1301 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1304 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1305 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());
1307 // If prev is coinbase, check that it's matured
1308 if (txPrev.IsCoinBase())
1309 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1310 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1311 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1314 if (!VerifySignature(txPrev, *this, i))
1315 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1317 // Check for conflicts
1318 if (!txindex.vSpent[prevout.n].IsNull())
1319 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());
1321 // Check for negative or overflow input values
1322 nValueIn += txPrev.vout[prevout.n].nValue;
1323 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1324 return error("ConnectInputs() : txin values out of range");
1326 // Mark outpoints as spent
1327 txindex.vSpent[prevout.n] = posThisTx;
1332 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1333 return error("ConnectInputs() : UpdateTxIndex failed");
1337 mapTestPool[prevout.hash] = txindex;
1341 if (nValueIn < GetValueOut())
1342 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1344 // Tally transaction fees
1345 int64 nTxFee = nValueIn - GetValueOut();
1347 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1348 if (nTxFee < nMinFee)
1351 if (!MoneyRange(nFees))
1352 return error("ConnectInputs() : nFees out of range");
1357 // Add transaction to disk index
1358 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1359 return error("ConnectInputs() : AddTxPos failed");
1363 // Add transaction to test pool
1364 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1371 bool CTransaction::ClientConnectInputs()
1376 // Take over previous transactions' spent pointers
1377 CRITICAL_BLOCK(cs_mapTransactions)
1380 for (int i = 0; i < vin.size(); i++)
1382 // Get prev tx from single transactions in memory
1383 COutPoint prevout = vin[i].prevout;
1384 if (!mapTransactions.count(prevout.hash))
1386 CTransaction& txPrev = mapTransactions[prevout.hash];
1388 if (prevout.n >= txPrev.vout.size())
1392 if (!VerifySignature(txPrev, *this, i))
1393 return error("ConnectInputs() : VerifySignature failed");
1395 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1396 ///// this has to go away now that posNext is gone
1397 // // Check for conflicts
1398 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1399 // return error("ConnectInputs() : prev tx already used");
1401 // // Flag outpoints as used
1402 // txPrev.vout[prevout.n].posNext = posThisTx;
1404 nValueIn += txPrev.vout[prevout.n].nValue;
1406 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1407 return error("ClientConnectInputs() : txin values out of range");
1409 if (GetValueOut() > nValueIn)
1419 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1421 // Disconnect in reverse order
1422 for (int i = vtx.size()-1; i >= 0; i--)
1423 if (!vtx[i].DisconnectInputs(txdb))
1426 // Update block index on disk without changing it in memory.
1427 // The memory index structure will be changed after the db commits.
1430 CDiskBlockIndex blockindexPrev(pindex->pprev);
1431 blockindexPrev.hashNext = 0;
1432 if (!txdb.WriteBlockIndex(blockindexPrev))
1433 return error("DisconnectBlock() : WriteBlockIndex failed");
1439 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1441 // Check it again in case a previous version let a bad block in
1445 //// issue here: it doesn't know the version
1446 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1448 map<uint256, CTxIndex> mapUnused;
1450 foreach(CTransaction& tx, vtx)
1452 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1453 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1455 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1459 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1462 // Update block index on disk without changing it in memory.
1463 // The memory index structure will be changed after the db commits.
1466 CDiskBlockIndex blockindexPrev(pindex->pprev);
1467 blockindexPrev.hashNext = pindex->GetBlockHash();
1468 if (!txdb.WriteBlockIndex(blockindexPrev))
1469 return error("ConnectBlock() : WriteBlockIndex failed");
1472 // Watch for transactions paying to me
1473 foreach(CTransaction& tx, vtx)
1474 AddToWalletIfMine(tx, this);
1479 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1481 printf("REORGANIZE\n");
1484 CBlockIndex* pfork = pindexBest;
1485 CBlockIndex* plonger = pindexNew;
1486 while (pfork != plonger)
1488 while (plonger->nHeight > pfork->nHeight)
1489 if (!(plonger = plonger->pprev))
1490 return error("Reorganize() : plonger->pprev is null");
1491 if (pfork == plonger)
1493 if (!(pfork = pfork->pprev))
1494 return error("Reorganize() : pfork->pprev is null");
1497 // List of what to disconnect
1498 vector<CBlockIndex*> vDisconnect;
1499 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1500 vDisconnect.push_back(pindex);
1502 // List of what to connect
1503 vector<CBlockIndex*> vConnect;
1504 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1505 vConnect.push_back(pindex);
1506 reverse(vConnect.begin(), vConnect.end());
1508 // Disconnect shorter branch
1509 vector<CTransaction> vResurrect;
1510 foreach(CBlockIndex* pindex, vDisconnect)
1513 if (!block.ReadFromDisk(pindex))
1514 return error("Reorganize() : ReadFromDisk for disconnect failed");
1515 if (!block.DisconnectBlock(txdb, pindex))
1516 return error("Reorganize() : DisconnectBlock failed");
1518 // Queue memory transactions to resurrect
1519 foreach(const CTransaction& tx, block.vtx)
1520 if (!tx.IsCoinBase())
1521 vResurrect.push_back(tx);
1524 // Connect longer branch
1525 vector<CTransaction> vDelete;
1526 for (int i = 0; i < vConnect.size(); i++)
1528 CBlockIndex* pindex = vConnect[i];
1530 if (!block.ReadFromDisk(pindex))
1531 return error("Reorganize() : ReadFromDisk for connect failed");
1532 if (!block.ConnectBlock(txdb, pindex))
1536 return error("Reorganize() : ConnectBlock failed");
1539 // Queue memory transactions to delete
1540 foreach(const CTransaction& tx, block.vtx)
1541 vDelete.push_back(tx);
1543 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1544 return error("Reorganize() : WriteHashBestChain failed");
1546 // Make sure it's successfully written to disk before changing memory structure
1547 if (!txdb.TxnCommit())
1548 return error("Reorganize() : TxnCommit failed");
1550 // Disconnect shorter branch
1551 foreach(CBlockIndex* pindex, vDisconnect)
1553 pindex->pprev->pnext = NULL;
1555 // Connect longer branch
1556 foreach(CBlockIndex* pindex, vConnect)
1558 pindex->pprev->pnext = pindex;
1560 // Resurrect memory transactions that were in the disconnected branch
1561 foreach(CTransaction& tx, vResurrect)
1562 tx.AcceptToMemoryPool(txdb, false);
1564 // Delete redundant memory transactions that are in the connected branch
1565 foreach(CTransaction& tx, vDelete)
1566 tx.RemoveFromMemoryPool();
1572 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1574 uint256 hash = GetHash();
1577 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1579 txdb.WriteHashBestChain(hash);
1580 if (!txdb.TxnCommit())
1581 return error("SetBestChain() : TxnCommit failed");
1582 pindexGenesisBlock = pindexNew;
1584 else if (hashPrevBlock == hashBestChain)
1586 // Adding to current best branch
1587 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1590 InvalidChainFound(pindexNew);
1591 return error("SetBestChain() : ConnectBlock failed");
1593 if (!txdb.TxnCommit())
1594 return error("SetBestChain() : TxnCommit failed");
1596 // Add to current best branch
1597 pindexNew->pprev->pnext = pindexNew;
1599 // Delete redundant memory transactions
1600 foreach(CTransaction& tx, vtx)
1601 tx.RemoveFromMemoryPool();
1606 if (!Reorganize(txdb, pindexNew))
1609 InvalidChainFound(pindexNew);
1610 return error("SetBestChain() : Reorganize failed");
1615 hashBestChain = hash;
1616 pindexBest = pindexNew;
1617 nBestHeight = pindexBest->nHeight;
1618 bnBestChainWork = pindexNew->bnChainWork;
1619 nTimeBestReceived = GetTime();
1620 nTransactionsUpdated++;
1621 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1627 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1629 // Check for duplicate
1630 uint256 hash = GetHash();
1631 if (mapBlockIndex.count(hash))
1632 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1634 // Construct new block index object
1635 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1637 return error("AddToBlockIndex() : new CBlockIndex failed");
1638 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1639 pindexNew->phashBlock = &((*mi).first);
1640 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1641 if (miPrev != mapBlockIndex.end())
1643 pindexNew->pprev = (*miPrev).second;
1644 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1646 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1650 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1651 if (!txdb.TxnCommit())
1655 if (pindexNew->bnChainWork > bnBestChainWork)
1656 if (!SetBestChain(txdb, pindexNew))
1661 if (pindexNew == pindexBest)
1663 // Notify UI to display prev block's coinbase if it was ours
1664 static uint256 hashPrevBestCoinBase;
1665 CRITICAL_BLOCK(cs_mapWallet)
1666 vWalletUpdated.push_back(hashPrevBestCoinBase);
1667 hashPrevBestCoinBase = vtx[0].GetHash();
1677 bool CBlock::CheckBlock() const
1679 // These are checks that are independent of context
1680 // that can be verified before saving an orphan block.
1683 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1684 return error("CheckBlock() : size limits failed");
1686 // Check proof of work matches claimed amount
1687 if (!CheckProofOfWork(GetHash(), nBits))
1688 return error("CheckBlock() : proof of work failed");
1691 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1692 return error("CheckBlock() : block timestamp too far in the future");
1694 // First transaction must be coinbase, the rest must not be
1695 if (vtx.empty() || !vtx[0].IsCoinBase())
1696 return error("CheckBlock() : first tx is not coinbase");
1697 for (int i = 1; i < vtx.size(); i++)
1698 if (vtx[i].IsCoinBase())
1699 return error("CheckBlock() : more than one coinbase");
1701 // Check transactions
1702 foreach(const CTransaction& tx, vtx)
1703 if (!tx.CheckTransaction())
1704 return error("CheckBlock() : CheckTransaction failed");
1706 // Check that it's not full of nonstandard transactions
1707 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1708 return error("CheckBlock() : too many nonstandard transactions");
1711 if (hashMerkleRoot != BuildMerkleTree())
1712 return error("CheckBlock() : hashMerkleRoot mismatch");
1717 bool CBlock::AcceptBlock()
1719 // Check for duplicate
1720 uint256 hash = GetHash();
1721 if (mapBlockIndex.count(hash))
1722 return error("AcceptBlock() : block already in mapBlockIndex");
1724 // Get prev block index
1725 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1726 if (mi == mapBlockIndex.end())
1727 return error("AcceptBlock() : prev block not found");
1728 CBlockIndex* pindexPrev = (*mi).second;
1729 int nHeight = pindexPrev->nHeight+1;
1731 // Check proof of work
1732 if (nBits != GetNextWorkRequired(pindexPrev))
1733 return error("AcceptBlock() : incorrect proof of work");
1735 // Check timestamp against prev
1736 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1737 return error("AcceptBlock() : block's timestamp is too early");
1739 // Check that all transactions are finalized
1740 foreach(const CTransaction& tx, vtx)
1741 if (!tx.IsFinal(nHeight, GetBlockTime()))
1742 return error("AcceptBlock() : contains a non-final transaction");
1744 // Check that the block chain matches the known block chain up to a checkpoint
1746 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1747 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1748 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1749 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1750 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1751 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1752 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))
1753 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1755 // Write block to history file
1756 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1757 return error("AcceptBlock() : out of disk space");
1758 unsigned int nFile = -1;
1759 unsigned int nBlockPos = 0;
1760 if (!WriteToDisk(nFile, nBlockPos))
1761 return error("AcceptBlock() : WriteToDisk failed");
1762 if (!AddToBlockIndex(nFile, nBlockPos))
1763 return error("AcceptBlock() : AddToBlockIndex failed");
1765 // Relay inventory, but don't relay old inventory during initial block download
1766 if (hashBestChain == hash)
1767 CRITICAL_BLOCK(cs_vNodes)
1768 foreach(CNode* pnode, vNodes)
1769 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
1770 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1775 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1777 // Check for duplicate
1778 uint256 hash = pblock->GetHash();
1779 if (mapBlockIndex.count(hash))
1780 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1781 if (mapOrphanBlocks.count(hash))
1782 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1784 // Preliminary checks
1785 if (!pblock->CheckBlock())
1786 return error("ProcessBlock() : CheckBlock FAILED");
1788 // If don't already have its previous block, shunt it off to holding area until we get it
1789 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1791 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1792 CBlock* pblock2 = new CBlock(*pblock);
1793 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1794 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1796 // Ask this guy to fill in what we're missing
1798 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1803 if (!pblock->AcceptBlock())
1804 return error("ProcessBlock() : AcceptBlock FAILED");
1806 // Recursively process any orphan blocks that depended on this one
1807 vector<uint256> vWorkQueue;
1808 vWorkQueue.push_back(hash);
1809 for (int i = 0; i < vWorkQueue.size(); i++)
1811 uint256 hashPrev = vWorkQueue[i];
1812 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1813 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1816 CBlock* pblockOrphan = (*mi).second;
1817 if (pblockOrphan->AcceptBlock())
1818 vWorkQueue.push_back(pblockOrphan->GetHash());
1819 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1820 delete pblockOrphan;
1822 mapOrphanBlocksByPrev.erase(hashPrev);
1825 printf("ProcessBlock: ACCEPTED\n");
1836 template<typename Stream>
1837 bool ScanMessageStart(Stream& s)
1839 // Scan ahead to the next pchMessageStart, which should normally be immediately
1840 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1842 short prevmask = s.exceptions(0);
1843 const char* p = BEGIN(pchMessageStart);
1853 s.exceptions(prevmask);
1857 p = BEGIN(pchMessageStart);
1860 if (++p == END(pchMessageStart))
1863 s.exceptions(prevmask);
1872 s.exceptions(prevmask);
1877 bool CheckDiskSpace(uint64 nAdditionalBytes)
1879 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1881 // Check for 15MB because database could create another 10MB log file at any time
1882 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1885 string strMessage = _("Warning: Disk space is low ");
1886 strMiscWarning = strMessage;
1887 printf("*** %s\n", strMessage.c_str());
1888 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1889 CreateThread(Shutdown, NULL);
1895 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1899 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1902 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1904 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1913 static unsigned int nCurrentBlockFile = 1;
1915 FILE* AppendBlockFile(unsigned int& nFileRet)
1920 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1923 if (fseek(file, 0, SEEK_END) != 0)
1925 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1926 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1928 nFileRet = nCurrentBlockFile;
1932 nCurrentBlockFile++;
1936 bool LoadBlockIndex(bool fAllowNew)
1940 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1941 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1942 pchMessageStart[0] = 0xfa;
1943 pchMessageStart[1] = 0xbf;
1944 pchMessageStart[2] = 0xb5;
1945 pchMessageStart[3] = 0xda;
1952 if (!txdb.LoadBlockIndex())
1957 // Init with genesis block
1959 if (mapBlockIndex.empty())
1965 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1966 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1967 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1968 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1969 // vMerkleTree: 4a5e1e
1972 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1974 txNew.vin.resize(1);
1975 txNew.vout.resize(1);
1976 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1977 txNew.vout[0].nValue = 50 * COIN;
1978 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1980 block.vtx.push_back(txNew);
1981 block.hashPrevBlock = 0;
1982 block.hashMerkleRoot = block.BuildMerkleTree();
1984 block.nTime = 1231006505;
1985 block.nBits = 0x1d00ffff;
1986 block.nNonce = 2083236893;
1990 block.nTime = 1296688602;
1991 block.nBits = 0x1d07fff8;
1992 block.nNonce = 384568319;
1996 printf("%s\n", block.GetHash().ToString().c_str());
1997 printf("%s\n", hashGenesisBlock.ToString().c_str());
1998 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1999 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2001 assert(block.GetHash() == hashGenesisBlock);
2003 // Start new block file
2005 unsigned int nBlockPos;
2006 if (!block.WriteToDisk(nFile, nBlockPos))
2007 return error("LoadBlockIndex() : writing genesis block to disk failed");
2008 if (!block.AddToBlockIndex(nFile, nBlockPos))
2009 return error("LoadBlockIndex() : genesis block not accepted");
2017 void PrintBlockTree()
2019 // precompute tree structure
2020 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2021 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2023 CBlockIndex* pindex = (*mi).second;
2024 mapNext[pindex->pprev].push_back(pindex);
2026 //while (rand() % 3 == 0)
2027 // mapNext[pindex->pprev].push_back(pindex);
2030 vector<pair<int, CBlockIndex*> > vStack;
2031 vStack.push_back(make_pair(0, pindexGenesisBlock));
2034 while (!vStack.empty())
2036 int nCol = vStack.back().first;
2037 CBlockIndex* pindex = vStack.back().second;
2040 // print split or gap
2041 if (nCol > nPrevCol)
2043 for (int i = 0; i < nCol-1; i++)
2047 else if (nCol < nPrevCol)
2049 for (int i = 0; i < nCol; i++)
2056 for (int i = 0; i < nCol; i++)
2061 block.ReadFromDisk(pindex);
2062 printf("%d (%u,%u) %s %s tx %d",
2066 block.GetHash().ToString().substr(0,20).c_str(),
2067 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2070 CRITICAL_BLOCK(cs_mapWallet)
2072 if (mapWallet.count(block.vtx[0].GetHash()))
2074 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2075 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2081 // put the main timechain first
2082 vector<CBlockIndex*>& vNext = mapNext[pindex];
2083 for (int i = 0; i < vNext.size(); i++)
2085 if (vNext[i]->pnext)
2087 swap(vNext[0], vNext[i]);
2093 for (int i = 0; i < vNext.size(); i++)
2094 vStack.push_back(make_pair(nCol+i, vNext[i]));
2107 //////////////////////////////////////////////////////////////////////////////
2112 map<uint256, CAlert> mapAlerts;
2113 CCriticalSection cs_mapAlerts;
2115 string GetWarnings(string strFor)
2118 string strStatusBar;
2120 if (GetBoolArg("-testsafemode"))
2123 // Misc warnings like out of disk space and clock is wrong
2124 if (strMiscWarning != "")
2127 strStatusBar = strMiscWarning;
2130 // Longer invalid proof-of-work chain
2131 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2134 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2138 CRITICAL_BLOCK(cs_mapAlerts)
2140 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2142 const CAlert& alert = item.second;
2143 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2145 nPriority = alert.nPriority;
2146 strStatusBar = alert.strStatusBar;
2151 if (strFor == "statusbar")
2152 return strStatusBar;
2153 else if (strFor == "rpc")
2155 assert(("GetWarnings() : invalid parameter", false));
2159 bool CAlert::ProcessAlert()
2161 if (!CheckSignature())
2166 CRITICAL_BLOCK(cs_mapAlerts)
2168 // Cancel previous alerts
2169 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2171 const CAlert& alert = (*mi).second;
2174 printf("cancelling alert %d\n", alert.nID);
2175 mapAlerts.erase(mi++);
2177 else if (!alert.IsInEffect())
2179 printf("expiring alert %d\n", alert.nID);
2180 mapAlerts.erase(mi++);
2186 // Check if this alert has been cancelled
2187 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2189 const CAlert& alert = item.second;
2190 if (alert.Cancels(*this))
2192 printf("alert already cancelled by %d\n", alert.nID);
2198 mapAlerts.insert(make_pair(GetHash(), *this));
2201 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2213 //////////////////////////////////////////////////////////////////////////////
2219 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2223 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2224 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2226 // Don't know what it is, just say we already got one
2233 // The message start string is designed to be unlikely to occur in normal data.
2234 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2235 // a large 4-byte int at any alignment.
2236 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2239 bool ProcessMessages(CNode* pfrom)
2241 CDataStream& vRecv = pfrom->vRecv;
2245 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2249 // (4) message start
2258 // Scan for message start
2259 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2260 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2261 if (vRecv.end() - pstart < nHeaderSize)
2263 if (vRecv.size() > nHeaderSize)
2265 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2266 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2270 if (pstart - vRecv.begin() > 0)
2271 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2272 vRecv.erase(vRecv.begin(), pstart);
2275 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2280 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2283 string strCommand = hdr.GetCommand();
2286 unsigned int nMessageSize = hdr.nMessageSize;
2287 if (nMessageSize > MAX_SIZE)
2289 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2292 if (nMessageSize > vRecv.size())
2294 // Rewind and wait for rest of message
2295 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2300 if (vRecv.GetVersion() >= 209)
2302 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2303 unsigned int nChecksum = 0;
2304 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2305 if (nChecksum != hdr.nChecksum)
2307 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2308 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2313 // Copy message to its own buffer
2314 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2315 vRecv.ignore(nMessageSize);
2321 CRITICAL_BLOCK(cs_main)
2322 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2326 catch (std::ios_base::failure& e)
2328 if (strstr(e.what(), "end of data"))
2330 // Allow exceptions from underlength message on vRecv
2331 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());
2333 else if (strstr(e.what(), "size too large"))
2335 // Allow exceptions from overlong size
2336 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2340 PrintExceptionContinue(&e, "ProcessMessage()");
2343 catch (std::exception& e) {
2344 PrintExceptionContinue(&e, "ProcessMessage()");
2346 PrintExceptionContinue(NULL, "ProcessMessage()");
2350 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2360 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2362 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2363 RandAddSeedPerfmon();
2365 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2366 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2367 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2369 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2377 if (strCommand == "version")
2379 // Each connection can only send one version message
2380 if (pfrom->nVersion != 0)
2387 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2388 if (pfrom->nVersion == 10300)
2389 pfrom->nVersion = 300;
2390 if (pfrom->nVersion >= 106 && !vRecv.empty())
2391 vRecv >> addrFrom >> nNonce;
2392 if (pfrom->nVersion >= 106 && !vRecv.empty())
2393 vRecv >> pfrom->strSubVer;
2394 if (pfrom->nVersion >= 209 && !vRecv.empty())
2395 vRecv >> pfrom->nStartingHeight;
2397 if (pfrom->nVersion == 0)
2400 // Disconnect if we connected to ourself
2401 if (nNonce == nLocalHostNonce && nNonce > 1)
2403 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2404 pfrom->fDisconnect = true;
2408 // Be shy and don't send version until we hear
2409 if (pfrom->fInbound)
2410 pfrom->PushVersion();
2412 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2414 AddTimeData(pfrom->addr.ip, nTime);
2417 if (pfrom->nVersion >= 209)
2418 pfrom->PushMessage("verack");
2419 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2420 if (pfrom->nVersion < 209)
2421 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2423 if (!pfrom->fInbound)
2425 // Advertise our address
2426 if (addrLocalHost.IsRoutable() && !fUseProxy)
2428 CAddress addr(addrLocalHost);
2429 addr.nTime = GetAdjustedTime();
2430 pfrom->PushAddress(addr);
2433 // Get recent addresses
2434 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2436 pfrom->PushMessage("getaddr");
2437 pfrom->fGetAddr = true;
2441 // Ask the first connected node for block updates
2442 static int nAskedForBlocks;
2443 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2446 pfrom->PushGetBlocks(pindexBest, uint256(0));
2450 CRITICAL_BLOCK(cs_mapAlerts)
2451 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2452 item.second.RelayTo(pfrom);
2454 pfrom->fSuccessfullyConnected = true;
2456 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2460 else if (pfrom->nVersion == 0)
2462 // Must have a version message before anything else
2467 else if (strCommand == "verack")
2469 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2473 else if (strCommand == "addr")
2475 vector<CAddress> vAddr;
2478 // Don't want addr from older versions unless seeding
2479 if (pfrom->nVersion < 209)
2481 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2483 if (vAddr.size() > 1000)
2484 return error("message addr size() = %d", vAddr.size());
2486 // Store the new addresses
2487 int64 nNow = GetAdjustedTime();
2488 int64 nSince = nNow - 10 * 60;
2489 foreach(CAddress& addr, vAddr)
2493 // ignore IPv6 for now, since it isn't implemented anyway
2496 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2497 addr.nTime = nNow - 5 * 24 * 60 * 60;
2498 AddAddress(addr, 2 * 60 * 60);
2499 pfrom->AddAddressKnown(addr);
2500 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2502 // Relay to a limited number of other nodes
2503 CRITICAL_BLOCK(cs_vNodes)
2505 // Use deterministic randomness to send to the same nodes for 24 hours
2506 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2507 static uint256 hashSalt;
2509 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2510 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2511 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2512 multimap<uint256, CNode*> mapMix;
2513 foreach(CNode* pnode, vNodes)
2515 if (pnode->nVersion < 31402)
2517 unsigned int nPointer;
2518 memcpy(&nPointer, &pnode, sizeof(nPointer));
2519 uint256 hashKey = hashRand ^ nPointer;
2520 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2521 mapMix.insert(make_pair(hashKey, pnode));
2523 int nRelayNodes = 2;
2524 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2525 ((*mi).second)->PushAddress(addr);
2529 if (vAddr.size() < 1000)
2530 pfrom->fGetAddr = false;
2534 else if (strCommand == "inv")
2538 if (vInv.size() > 50000)
2539 return error("message inv size() = %d", vInv.size());
2542 foreach(const CInv& inv, vInv)
2546 pfrom->AddInventoryKnown(inv);
2548 bool fAlreadyHave = AlreadyHave(txdb, inv);
2549 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2553 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2554 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2556 // Track requests for our stuff
2557 CRITICAL_BLOCK(cs_mapRequestCount)
2559 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2560 if (mi != mapRequestCount.end())
2567 else if (strCommand == "getdata")
2571 if (vInv.size() > 50000)
2572 return error("message getdata size() = %d", vInv.size());
2574 foreach(const CInv& inv, vInv)
2578 printf("received getdata for: %s\n", inv.ToString().c_str());
2580 if (inv.type == MSG_BLOCK)
2582 // Send block from disk
2583 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2584 if (mi != mapBlockIndex.end())
2587 block.ReadFromDisk((*mi).second);
2588 pfrom->PushMessage("block", block);
2590 // Trigger them to send a getblocks request for the next batch of inventory
2591 if (inv.hash == pfrom->hashContinue)
2593 // Bypass PushInventory, this must send even if redundant,
2594 // and we want it right after the last block so they don't
2595 // wait for other stuff first.
2597 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2598 pfrom->PushMessage("inv", vInv);
2599 pfrom->hashContinue = 0;
2603 else if (inv.IsKnownType())
2605 // Send stream from relay memory
2606 CRITICAL_BLOCK(cs_mapRelay)
2608 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2609 if (mi != mapRelay.end())
2610 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2614 // Track requests for our stuff
2615 CRITICAL_BLOCK(cs_mapRequestCount)
2617 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2618 if (mi != mapRequestCount.end())
2625 else if (strCommand == "getblocks")
2627 CBlockLocator locator;
2629 vRecv >> locator >> hashStop;
2631 // Find the last block the caller has in the main chain
2632 CBlockIndex* pindex = locator.GetBlockIndex();
2634 // Send the rest of the chain
2636 pindex = pindex->pnext;
2637 int nLimit = 500 + locator.GetDistanceBack();
2638 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2639 for (; pindex; pindex = pindex->pnext)
2641 if (pindex->GetBlockHash() == hashStop)
2643 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2646 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2649 // When this block is requested, we'll send an inv that'll make them
2650 // getblocks the next batch of inventory.
2651 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2652 pfrom->hashContinue = pindex->GetBlockHash();
2659 else if (strCommand == "getheaders")
2661 CBlockLocator locator;
2663 vRecv >> locator >> hashStop;
2665 CBlockIndex* pindex = NULL;
2666 if (locator.IsNull())
2668 // If locator is null, return the hashStop block
2669 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2670 if (mi == mapBlockIndex.end())
2672 pindex = (*mi).second;
2676 // Find the last block the caller has in the main chain
2677 pindex = locator.GetBlockIndex();
2679 pindex = pindex->pnext;
2682 vector<CBlock> vHeaders;
2683 int nLimit = 2000 + locator.GetDistanceBack();
2684 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2685 for (; pindex; pindex = pindex->pnext)
2687 vHeaders.push_back(pindex->GetBlockHeader());
2688 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2691 pfrom->PushMessage("headers", vHeaders);
2695 else if (strCommand == "tx")
2697 vector<uint256> vWorkQueue;
2698 CDataStream vMsg(vRecv);
2702 CInv inv(MSG_TX, tx.GetHash());
2703 pfrom->AddInventoryKnown(inv);
2705 bool fMissingInputs = false;
2706 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2708 AddToWalletIfMine(tx, NULL);
2709 RelayMessage(inv, vMsg);
2710 mapAlreadyAskedFor.erase(inv);
2711 vWorkQueue.push_back(inv.hash);
2713 // Recursively process any orphan transactions that depended on this one
2714 for (int i = 0; i < vWorkQueue.size(); i++)
2716 uint256 hashPrev = vWorkQueue[i];
2717 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2718 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2721 const CDataStream& vMsg = *((*mi).second);
2723 CDataStream(vMsg) >> tx;
2724 CInv inv(MSG_TX, tx.GetHash());
2726 if (tx.AcceptToMemoryPool(true))
2728 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2729 AddToWalletIfMine(tx, NULL);
2730 RelayMessage(inv, vMsg);
2731 mapAlreadyAskedFor.erase(inv);
2732 vWorkQueue.push_back(inv.hash);
2737 foreach(uint256 hash, vWorkQueue)
2738 EraseOrphanTx(hash);
2740 else if (fMissingInputs)
2742 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2748 else if (strCommand == "block")
2753 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2756 CInv inv(MSG_BLOCK, block.GetHash());
2757 pfrom->AddInventoryKnown(inv);
2759 if (ProcessBlock(pfrom, &block))
2760 mapAlreadyAskedFor.erase(inv);
2764 else if (strCommand == "getaddr")
2766 // Nodes rebroadcast an addr every 24 hours
2767 pfrom->vAddrToSend.clear();
2768 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2769 CRITICAL_BLOCK(cs_mapAddresses)
2771 unsigned int nCount = 0;
2772 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2774 const CAddress& addr = item.second;
2775 if (addr.nTime > nSince)
2778 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2780 const CAddress& addr = item.second;
2781 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2782 pfrom->PushAddress(addr);
2788 else if (strCommand == "checkorder")
2793 if (!GetBoolArg("-allowreceivebyip"))
2795 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2802 /// we have a chance to check the order here
2804 // Keep giving the same key to the same ip until they use it
2805 if (!mapReuseKey.count(pfrom->addr.ip))
2806 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2808 // Send back approval of order and pubkey to use
2809 CScript scriptPubKey;
2810 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2811 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2815 else if (strCommand == "submitorder")
2820 if (!GetBoolArg("-allowreceivebyip"))
2822 pfrom->PushMessage("reply", hashReply, (int)2);
2828 wtxNew.fFromMe = false;
2831 if (!wtxNew.AcceptWalletTransaction())
2833 pfrom->PushMessage("reply", hashReply, (int)1);
2834 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2836 wtxNew.fTimeReceivedIsTxTime = true;
2837 AddToWallet(wtxNew);
2838 wtxNew.RelayWalletTransaction();
2839 mapReuseKey.erase(pfrom->addr.ip);
2841 // Send back confirmation
2842 pfrom->PushMessage("reply", hashReply, (int)0);
2846 else if (strCommand == "reply")
2851 CRequestTracker tracker;
2852 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2854 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2855 if (mi != pfrom->mapRequests.end())
2857 tracker = (*mi).second;
2858 pfrom->mapRequests.erase(mi);
2861 if (!tracker.IsNull())
2862 tracker.fn(tracker.param1, vRecv);
2866 else if (strCommand == "ping")
2871 else if (strCommand == "alert")
2876 if (alert.ProcessAlert())
2879 pfrom->setKnown.insert(alert.GetHash());
2880 CRITICAL_BLOCK(cs_vNodes)
2881 foreach(CNode* pnode, vNodes)
2882 alert.RelayTo(pnode);
2889 // Ignore unknown commands for extensibility
2893 // Update the last seen time for this node's address
2894 if (pfrom->fNetworkNode)
2895 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2896 AddressCurrentlyConnected(pfrom->addr);
2910 bool SendMessages(CNode* pto, bool fSendTrickle)
2912 CRITICAL_BLOCK(cs_main)
2914 // Don't send anything until we get their version message
2915 if (pto->nVersion == 0)
2919 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2920 pto->PushMessage("ping");
2922 // Resend wallet transactions that haven't gotten in a block yet
2923 ResendWalletTransactions();
2925 // Address refresh broadcast
2926 static int64 nLastRebroadcast;
2927 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2929 nLastRebroadcast = GetTime();
2930 CRITICAL_BLOCK(cs_vNodes)
2932 foreach(CNode* pnode, vNodes)
2934 // Periodically clear setAddrKnown to allow refresh broadcasts
2935 pnode->setAddrKnown.clear();
2937 // Rebroadcast our address
2938 if (addrLocalHost.IsRoutable() && !fUseProxy)
2940 CAddress addr(addrLocalHost);
2941 addr.nTime = GetAdjustedTime();
2942 pnode->PushAddress(addr);
2948 // Clear out old addresses periodically so it's not too much work at once
2949 static int64 nLastClear;
2950 if (nLastClear == 0)
2951 nLastClear = GetTime();
2952 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2954 nLastClear = GetTime();
2955 CRITICAL_BLOCK(cs_mapAddresses)
2958 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2959 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2960 mi != mapAddresses.end();)
2962 const CAddress& addr = (*mi).second;
2963 if (addr.nTime < nSince)
2965 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2967 addrdb.EraseAddress(addr);
2968 mapAddresses.erase(mi++);
2982 vector<CAddress> vAddr;
2983 vAddr.reserve(pto->vAddrToSend.size());
2984 foreach(const CAddress& addr, pto->vAddrToSend)
2986 // returns true if wasn't already contained in the set
2987 if (pto->setAddrKnown.insert(addr).second)
2989 vAddr.push_back(addr);
2990 // receiver rejects addr messages larger than 1000
2991 if (vAddr.size() >= 1000)
2993 pto->PushMessage("addr", vAddr);
2998 pto->vAddrToSend.clear();
3000 pto->PushMessage("addr", vAddr);
3005 // Message: inventory
3008 vector<CInv> vInvWait;
3009 CRITICAL_BLOCK(pto->cs_inventory)
3011 vInv.reserve(pto->vInventoryToSend.size());
3012 vInvWait.reserve(pto->vInventoryToSend.size());
3013 foreach(const CInv& inv, pto->vInventoryToSend)
3015 if (pto->setInventoryKnown.count(inv))
3018 // trickle out tx inv to protect privacy
3019 if (inv.type == MSG_TX && !fSendTrickle)
3021 // 1/4 of tx invs blast to all immediately
3022 static uint256 hashSalt;
3024 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
3025 uint256 hashRand = inv.hash ^ hashSalt;
3026 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3027 bool fTrickleWait = ((hashRand & 3) != 0);
3029 // always trickle our own transactions
3032 TRY_CRITICAL_BLOCK(cs_mapWallet)
3034 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
3035 if (mi != mapWallet.end())
3037 CWalletTx& wtx = (*mi).second;
3039 fTrickleWait = true;
3046 vInvWait.push_back(inv);
3051 // returns true if wasn't already contained in the set
3052 if (pto->setInventoryKnown.insert(inv).second)
3054 vInv.push_back(inv);
3055 if (vInv.size() >= 1000)
3057 pto->PushMessage("inv", vInv);
3062 pto->vInventoryToSend = vInvWait;
3065 pto->PushMessage("inv", vInv);
3071 vector<CInv> vGetData;
3072 int64 nNow = GetTime() * 1000000;
3074 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3076 const CInv& inv = (*pto->mapAskFor.begin()).second;
3077 if (!AlreadyHave(txdb, inv))
3079 printf("sending getdata: %s\n", inv.ToString().c_str());
3080 vGetData.push_back(inv);
3081 if (vGetData.size() >= 1000)
3083 pto->PushMessage("getdata", vGetData);
3087 pto->mapAskFor.erase(pto->mapAskFor.begin());
3089 if (!vGetData.empty())
3090 pto->PushMessage("getdata", vGetData);
3109 //////////////////////////////////////////////////////////////////////////////
3114 void GenerateBitcoins(bool fGenerate)
3116 if (fGenerateBitcoins != fGenerate)
3118 fGenerateBitcoins = fGenerate;
3119 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3122 if (fGenerateBitcoins)
3124 int nProcessors = boost::thread::hardware_concurrency();
3125 printf("%d processors\n", nProcessors);
3126 if (nProcessors < 1)
3128 if (fLimitProcessors && nProcessors > nLimitProcessors)
3129 nProcessors = nLimitProcessors;
3130 int nAddThreads = nProcessors - vnThreadsRunning[3];
3131 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3132 for (int i = 0; i < nAddThreads; i++)
3134 if (!CreateThread(ThreadBitcoinMiner, NULL))
3135 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3141 void ThreadBitcoinMiner(void* parg)
3145 vnThreadsRunning[3]++;
3147 vnThreadsRunning[3]--;
3149 catch (std::exception& e) {
3150 vnThreadsRunning[3]--;
3151 PrintException(&e, "ThreadBitcoinMiner()");
3153 vnThreadsRunning[3]--;
3154 PrintException(NULL, "ThreadBitcoinMiner()");
3156 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3158 if (vnThreadsRunning[3] == 0)
3160 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3163 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
3164 void CallCPUID(int in, int& aret, int& cret)
3168 "mov %2, %%eax; " // in into eax
3170 "mov %%eax, %0;" // eax into a
3171 "mov %%ecx, %1;" // ecx into c
3172 :"=r"(a),"=r"(c) /* output */
3173 :"r"(in) /* input */
3174 :"%eax","%ebx","%ecx","%edx" /* clobbered register */
3180 bool Detect128BitSSE2()
3183 CallCPUID(0, a, nBrand);
3184 bool fIntel = (nBrand == 0x6c65746e); // ntel
3185 bool fAMD = (nBrand == 0x444d4163); // cAMD
3189 unsigned int nStepping : 4;
3190 unsigned int nModel : 4;
3191 unsigned int nFamily : 4;
3192 unsigned int nProcessorType : 2;
3193 unsigned int nUnused : 2;
3194 unsigned int nExtendedModel : 4;
3195 unsigned int nExtendedFamily : 8;
3199 memcpy(&cpu, &a, sizeof(cpu));
3200 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
3201 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
3203 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
3204 // Nehalem = i3/i5/i7 and some Xeon
3205 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
3206 // Intel Core i5 family 6, model 26 or 30
3207 // Intel Core i7 family 6, model 26 or 30
3208 // Intel Core i3 family 6, model 37
3209 // AMD Phenom family 16, model 10
3210 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
3211 (fAMD && nFamily * 10000 + nModel >= 160010));
3213 // AMD reports a lower model number in 64-bit mode
3214 if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
3217 static bool fPrinted;
3221 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
3226 bool Detect128BitSSE2() { return false; }
3229 int FormatHashBlocks(void* pbuffer, unsigned int len)
3231 unsigned char* pdata = (unsigned char*)pbuffer;
3232 unsigned int blocks = 1 + ((len + 8) / 64);
3233 unsigned char* pend = pdata + 64 * blocks;
3234 memset(pdata + len, 0, 64 * blocks - len);
3236 unsigned int bits = len * 8;
3237 pend[-1] = (bits >> 0) & 0xff;
3238 pend[-2] = (bits >> 8) & 0xff;
3239 pend[-3] = (bits >> 16) & 0xff;
3240 pend[-4] = (bits >> 24) & 0xff;
3244 using CryptoPP::ByteReverse;
3246 static const unsigned int pSHA256InitState[8] =
3247 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3249 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3251 memcpy(pstate, pinit, 32);
3252 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3256 // ScanHash scans nonces looking for a hash with at least some zero bits.
3257 // It operates on big endian data. Caller does the byte reversing.
3258 // All input buffers are 16-byte aligned. nNonce is usually preserved
3259 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3260 // the block is rebuilt and nNonce starts over at zero.
3262 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3264 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3268 // Hash pdata using pmidstate as the starting state into
3269 // preformatted buffer phash1, then hash phash1 into phash
3271 SHA256Transform(phash1, pdata, pmidstate);
3272 SHA256Transform(phash, phash1, pSHA256InitState);
3274 // Return the nonce if the hash has at least some zero bits,
3275 // caller will check if it has enough to reach the target
3276 if (((unsigned short*)phash)[14] == 0)
3279 // If nothing found after trying for a while, return -1
3280 if ((nNonce & 0xffff) == 0)
3282 nHashesDone = 0xffff+1;
3288 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
3296 set<uint256> setDependsOn;
3299 COrphan(CTransaction* ptxIn)
3307 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3308 foreach(uint256 hash, setDependsOn)
3309 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3314 CBlock* CreateNewBlock(CReserveKey& reservekey)
3316 CBlockIndex* pindexPrev = pindexBest;
3319 auto_ptr<CBlock> pblock(new CBlock());
3323 // Create coinbase tx
3325 txNew.vin.resize(1);
3326 txNew.vin[0].prevout.SetNull();
3327 txNew.vout.resize(1);
3328 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3330 // Add our coinbase tx as first transaction
3331 pblock->vtx.push_back(txNew);
3333 // Collect memory pool transactions into the block
3335 CRITICAL_BLOCK(cs_main)
3336 CRITICAL_BLOCK(cs_mapTransactions)
3340 // Priority order to process transactions
3341 list<COrphan> vOrphan; // list memory doesn't move
3342 map<uint256, vector<COrphan*> > mapDependers;
3343 multimap<double, CTransaction*> mapPriority;
3344 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3346 CTransaction& tx = (*mi).second;
3347 if (tx.IsCoinBase() || !tx.IsFinal())
3350 COrphan* porphan = NULL;
3351 double dPriority = 0;
3352 foreach(const CTxIn& txin, tx.vin)
3354 // Read prev transaction
3355 CTransaction txPrev;
3357 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3359 // Has to wait for dependencies
3362 // Use list for automatic deletion
3363 vOrphan.push_back(COrphan(&tx));
3364 porphan = &vOrphan.back();
3366 mapDependers[txin.prevout.hash].push_back(porphan);
3367 porphan->setDependsOn.insert(txin.prevout.hash);
3370 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3372 // Read block header
3373 int nConf = txindex.GetDepthInMainChain();
3375 dPriority += (double)nValueIn * nConf;
3377 if (fDebug && GetBoolArg("-printpriority"))
3378 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3381 // Priority is sum(valuein * age) / txsize
3382 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3385 porphan->dPriority = dPriority;
3387 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3389 if (fDebug && GetBoolArg("-printpriority"))
3391 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3398 // Collect transactions into block
3399 map<uint256, CTxIndex> mapTestPool;
3400 uint64 nBlockSize = 1000;
3401 int nBlockSigOps = 100;
3402 while (!mapPriority.empty())
3404 // Take highest priority transaction off priority queue
3405 double dPriority = -(*mapPriority.begin()).first;
3406 CTransaction& tx = *(*mapPriority.begin()).second;
3407 mapPriority.erase(mapPriority.begin());
3410 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3411 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3413 int nTxSigOps = tx.GetSigOpCount();
3414 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3417 // Transaction fee required depends on block size
3418 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3419 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3421 // Connecting shouldn't fail due to dependency on other memory pool transactions
3422 // because we're already processing them in order of dependency
3423 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3424 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3426 swap(mapTestPool, mapTestPoolTmp);
3429 pblock->vtx.push_back(tx);
3430 nBlockSize += nTxSize;
3431 nBlockSigOps += nTxSigOps;
3433 // Add transactions that depend on this one to the priority queue
3434 uint256 hash = tx.GetHash();
3435 if (mapDependers.count(hash))
3437 foreach(COrphan* porphan, mapDependers[hash])
3439 if (!porphan->setDependsOn.empty())
3441 porphan->setDependsOn.erase(hash);
3442 if (porphan->setDependsOn.empty())
3443 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3449 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3452 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3453 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3454 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3455 pblock->nBits = GetNextWorkRequired(pindexPrev);
3458 return pblock.release();
3462 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3464 // Update nExtraNonce
3465 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3466 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3471 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3472 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3476 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3479 // Prebuild hash buffers
3486 uint256 hashPrevBlock;
3487 uint256 hashMerkleRoot;
3490 unsigned int nNonce;
3493 unsigned char pchPadding0[64];
3495 unsigned char pchPadding1[64];
3498 memset(&tmp, 0, sizeof(tmp));
3500 tmp.block.nVersion = pblock->nVersion;
3501 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3502 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3503 tmp.block.nTime = pblock->nTime;
3504 tmp.block.nBits = pblock->nBits;
3505 tmp.block.nNonce = pblock->nNonce;
3507 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3508 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3510 // Byte swap all the input buffer
3511 for (int i = 0; i < sizeof(tmp)/4; i++)
3512 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3514 // Precalc the first half of the first hash, which stays constant
3515 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3517 memcpy(pdata, &tmp.block, 128);
3518 memcpy(phash1, &tmp.hash1, 64);
3522 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3524 uint256 hash = pblock->GetHash();
3525 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3527 if (hash > hashTarget)
3531 printf("BitcoinMiner:\n");
3532 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3534 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3535 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3538 CRITICAL_BLOCK(cs_main)
3540 if (pblock->hashPrevBlock != hashBestChain)
3541 return error("BitcoinMiner : generated block is stale");
3543 // Remove key from key pool
3544 reservekey.KeepKey();
3546 // Track how many getdata requests this block gets
3547 CRITICAL_BLOCK(cs_mapRequestCount)
3548 mapRequestCount[pblock->GetHash()] = 0;
3550 // Process this block the same as if we had received it from another node
3551 if (!ProcessBlock(NULL, pblock))
3552 return error("BitcoinMiner : ProcessBlock, block not accepted");
3562 printf("BitcoinMiner started\n");
3563 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3564 bool f4WaySSE2 = Detect128BitSSE2();
3565 if (mapArgs.count("-4way"))
3566 f4WaySSE2 = GetBoolArg("-4way");
3568 // Each thread has its own key and counter
3569 CReserveKey reservekey;
3570 unsigned int nExtraNonce = 0;
3571 int64 nPrevTime = 0;
3573 while (fGenerateBitcoins)
3575 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3579 while (vNodes.empty() || IsInitialBlockDownload())
3584 if (!fGenerateBitcoins)
3592 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3593 CBlockIndex* pindexPrev = pindexBest;
3595 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3598 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3600 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3604 // Prebuild hash buffers
3606 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3607 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3608 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3610 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3612 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3613 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3619 int64 nStart = GetTime();
3620 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3622 uint256& hash = *alignup<16>(hashbuf);
3625 unsigned int nHashesDone = 0;
3626 unsigned int nNonceFound;
3630 // tcatm's 4-way 128-bit SSE2 SHA-256
3631 nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3635 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3637 // Check if something found
3638 if (nNonceFound != -1)
3640 for (int i = 0; i < sizeof(hash)/4; i++)
3641 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3643 if (hash <= hashTarget)
3646 pblock->nNonce = ByteReverse(nNonceFound);
3647 assert(hash == pblock->GetHash());
3649 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3650 CheckWork(pblock.get(), reservekey);
3651 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3657 static int64 nHashCounter;
3658 if (nHPSTimerStart == 0)
3660 nHPSTimerStart = GetTimeMillis();
3664 nHashCounter += nHashesDone;
3665 if (GetTimeMillis() - nHPSTimerStart > 4000)
3667 static CCriticalSection cs;
3670 if (GetTimeMillis() - nHPSTimerStart > 4000)
3672 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3673 nHPSTimerStart = GetTimeMillis();
3675 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3676 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3677 static int64 nLogTime;
3678 if (GetTime() - nLogTime > 30 * 60)
3680 nLogTime = GetTime();
3681 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3682 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3688 // Check for stop or if block needs to be rebuilt
3691 if (!fGenerateBitcoins)
3693 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3697 if (nBlockNonce >= 0xffff0000)
3699 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3701 if (pindexPrev != pindexBest)
3704 // Update nTime every few seconds
3705 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3706 nBlockTime = ByteReverse(pblock->nTime);
3728 //////////////////////////////////////////////////////////////////////////////
3736 int64 nStart = GetTimeMillis();
3739 CRITICAL_BLOCK(cs_mapWallet)
3741 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3743 CWalletTx* pcoin = &(*it).second;
3744 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3746 nTotal += pcoin->GetAvailableCredit();
3750 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3755 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3757 setCoinsRet.clear();
3760 // List of values less than target
3761 pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;
3762 coinLowestLarger.first = INT64_MAX;
3763 coinLowestLarger.second.first = NULL;
3764 vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;
3765 int64 nTotalLower = 0;
3767 CRITICAL_BLOCK(cs_mapWallet)
3769 vector<CWalletTx*> vCoins;
3770 vCoins.reserve(mapWallet.size());
3771 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3772 vCoins.push_back(&(*it).second);
3773 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3775 foreach(CWalletTx* pcoin, vCoins)
3777 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3780 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3783 int nDepth = pcoin->GetDepthInMainChain();
3784 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3787 for (int i = 0; i < pcoin->vout.size(); i++)
3789 if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())
3792 int64 n = pcoin->vout[i].nValue;
3797 pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
3799 if (n == nTargetValue)
3801 setCoinsRet.insert(coin.second);
3802 nValueRet += coin.first;
3805 else if (n < nTargetValue + CENT)
3807 vValue.push_back(coin);
3810 else if (n < coinLowestLarger.first)
3812 coinLowestLarger = coin;
3818 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
3820 for (int i = 0; i < vValue.size(); ++i)
3822 setCoinsRet.insert(vValue[i].second);
3823 nValueRet += vValue[i].first;
3828 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
3830 if (coinLowestLarger.second.first == NULL)
3832 setCoinsRet.insert(coinLowestLarger.second);
3833 nValueRet += coinLowestLarger.first;
3837 if (nTotalLower >= nTargetValue + CENT)
3838 nTargetValue += CENT;
3840 // Solve subset sum by stochastic approximation
3841 sort(vValue.rbegin(), vValue.rend());
3842 vector<char> vfIncluded;
3843 vector<char> vfBest(vValue.size(), true);
3844 int64 nBest = nTotalLower;
3846 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3848 vfIncluded.assign(vValue.size(), false);
3850 bool fReachedTarget = false;
3851 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3853 for (int i = 0; i < vValue.size(); i++)
3855 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3857 nTotal += vValue[i].first;
3858 vfIncluded[i] = true;
3859 if (nTotal >= nTargetValue)
3861 fReachedTarget = true;
3865 vfBest = vfIncluded;
3867 nTotal -= vValue[i].first;
3868 vfIncluded[i] = false;
3875 // If the next larger is still closer, return it
3876 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
3878 setCoinsRet.insert(coinLowestLarger.second);
3879 nValueRet += coinLowestLarger.first;
3882 for (int i = 0; i < vValue.size(); i++)
3885 setCoinsRet.insert(vValue[i].second);
3886 nValueRet += vValue[i].first;
3890 printf("SelectCoins() best subset: ");
3891 for (int i = 0; i < vValue.size(); i++)
3893 printf("%s ", FormatMoney(vValue[i].first).c_str());
3894 printf("total %s\n", FormatMoney(nBest).c_str());
3900 bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3902 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
3903 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
3904 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
3910 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3913 foreach (const PAIRTYPE(CScript, int64)& s, vecSend)
3919 if (vecSend.empty() || nValue < 0)
3922 CRITICAL_BLOCK(cs_main)
3924 // txdb must be opened before the mapWallet lock
3926 CRITICAL_BLOCK(cs_mapWallet)
3928 nFeeRet = nTransactionFee;
3932 wtxNew.vout.clear();
3933 wtxNew.fFromMe = true;
3935 int64 nTotalValue = nValue + nFeeRet;
3936 double dPriority = 0;
3937 // vouts to the payees
3938 foreach (const PAIRTYPE(CScript, int64)& s, vecSend)
3939 wtxNew.vout.push_back(CTxOut(s.second, s.first));
3941 // Choose coins to use
3942 set<pair<CWalletTx*,unsigned int> > setCoins;
3944 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
3946 foreach(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)
3948 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
3949 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
3952 // Fill a vout back to self with any change
3953 int64 nChange = nValueIn - nTotalValue;
3954 if (nChange >= CENT)
3956 // Note: We use a new key here to keep it from being obvious which side is the change.
3957 // The drawback is that by not reusing a previous key, the change may be lost if a
3958 // backup is restored, if the backup doesn't have the new private key for the change.
3959 // If we reused the old key, it would be possible to add code to look for and
3960 // rediscover unknown transactions that were written with keys of ours to recover
3961 // post-backup change.
3963 // Reserve a new key pair from key pool
3964 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3965 assert(mapKeys.count(vchPubKey));
3967 // Fill a vout to ourself, using same address type as the payment
3968 CScript scriptChange;
3969 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
3970 scriptChange.SetBitcoinAddress(vchPubKey);
3972 scriptChange << vchPubKey << OP_CHECKSIG;
3974 // Insert change txn at random position:
3975 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
3976 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
3979 reservekey.ReturnKey();
3982 foreach(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3983 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
3987 foreach(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3988 if (!SignSignature(*coin.first, wtxNew, nIn++))
3992 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3993 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3995 dPriority /= nBytes;
3997 // Check that enough fee is included
3998 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3999 bool fAllowFree = CTransaction::AllowFree(dPriority);
4000 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
4001 if (nFeeRet < max(nPayFee, nMinFee))
4003 nFeeRet = max(nPayFee, nMinFee);
4007 // Fill vtxPrev by copying from previous transactions vtxPrev
4008 wtxNew.AddSupportingTransactions(txdb);
4009 wtxNew.fTimeReceivedIsTxTime = true;
4018 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
4020 vector< pair<CScript, int64> > vecSend;
4021 vecSend.push_back(make_pair(scriptPubKey, nValue));
4022 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
4025 // Call after CreateTransaction unless you want to abort
4026 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
4028 CRITICAL_BLOCK(cs_main)
4030 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
4031 CRITICAL_BLOCK(cs_mapWallet)
4033 // This is only to keep the database open to defeat the auto-flush for the
4034 // duration of this scope. This is the only place where this optimization
4035 // maybe makes sense; please don't do it anywhere else.
4036 CWalletDB walletdb("r");
4038 // Take key pair from key pool so it won't be used again
4039 reservekey.KeepKey();
4041 // Add tx to wallet, because if it has change it's also ours,
4042 // otherwise just for transaction history.
4043 AddToWallet(wtxNew);
4045 // Mark old coins as spent
4046 set<CWalletTx*> setCoins;
4047 foreach(const CTxIn& txin, wtxNew.vin)
4049 CWalletTx &pcoin = mapWallet[txin.prevout.hash];
4050 pcoin.MarkSpent(txin.prevout.n);
4051 pcoin.WriteToDisk();
4052 vWalletUpdated.push_back(pcoin.GetHash());
4056 // Track how many getdata requests our transaction gets
4057 CRITICAL_BLOCK(cs_mapRequestCount)
4058 mapRequestCount[wtxNew.GetHash()] = 0;
4061 if (!wtxNew.AcceptToMemoryPool())
4063 // This must not fail. The transaction has already been signed and recorded.
4064 printf("CommitTransaction() : Error: Transaction not valid");
4067 wtxNew.RelayWalletTransaction();
4076 // requires cs_main lock
4077 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4079 CReserveKey reservekey;
4081 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
4084 if (nValue + nFeeRequired > GetBalance())
4085 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
4087 strError = _("Error: Transaction creation failed ");
4088 printf("SendMoney() : %s", strError.c_str());
4092 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4095 if (!CommitTransaction(wtxNew, reservekey))
4096 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.");
4104 // requires cs_main lock
4105 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4109 return _("Invalid amount");
4110 if (nValue + nTransactionFee > GetBalance())
4111 return _("Insufficient funds");
4113 // Parse bitcoin address
4114 CScript scriptPubKey;
4115 if (!scriptPubKey.SetBitcoinAddress(strAddress))
4116 return _("Invalid bitcoin address");
4118 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);