Gavin: BIO_FLAGS_BASE64_NO_NL
[bitcoinplatinum.git] / main.cpp
blob45ad06f9367b2962952eab4f08a95ff7df863dbc
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.
5 #include "headers.h"
6 #include "sha.h"
13 // Global state
16 CCriticalSection cs_main;
18 map<uint256, CTransaction> mapTransactions;
19 CCriticalSection cs_mapTransactions;
20 unsigned int nTransactionsUpdated = 0;
21 map<COutPoint, CInPoint> mapNextTx;
23 map<uint256, CBlockIndex*> mapBlockIndex;
24 const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
25 CBlockIndex* pindexGenesisBlock = NULL;
26 int nBestHeight = -1;
27 CBigNum bnBestChainWork = 0;
28 uint256 hashBestChain = 0;
29 CBlockIndex* pindexBest = NULL;
30 int64 nTimeBestReceived = 0;
32 map<uint256, CBlock*> mapOrphanBlocks;
33 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
35 map<uint256, CDataStream*> mapOrphanTransactions;
36 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
38 map<uint256, CWalletTx> mapWallet;
39 vector<uint256> vWalletUpdated;
40 CCriticalSection cs_mapWallet;
42 map<vector<unsigned char>, CPrivKey> mapKeys;
43 map<uint160, vector<unsigned char> > mapPubKeys;
44 CCriticalSection cs_mapKeys;
45 CKey keyUser;
47 map<uint256, int> mapRequestCount;
48 CCriticalSection cs_mapRequestCount;
50 map<string, string> mapAddressBook;
51 CCriticalSection cs_mapAddressBook;
53 vector<unsigned char> vchDefaultKey;
55 // Settings
56 int fGenerateBitcoins = false;
57 int64 nTransactionFee = 0;
58 CAddress addrIncoming;
59 int fLimitProcessors = false;
60 int nLimitProcessors = 1;
61 int fMinimizeToTray = true;
62 int fMinimizeOnClose = true;
69 //////////////////////////////////////////////////////////////////////////////
71 // mapKeys
74 bool AddKey(const CKey& key)
76 CRITICAL_BLOCK(cs_mapKeys)
78 mapKeys[key.GetPubKey()] = key.GetPrivKey();
79 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
81 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
84 vector<unsigned char> GenerateNewKey()
86 CKey key;
87 key.MakeNewKey();
88 if (!AddKey(key))
89 throw runtime_error("GenerateNewKey() : AddKey failed\n");
90 return key.GetPubKey();
96 //////////////////////////////////////////////////////////////////////////////
98 // mapWallet
101 bool AddToWallet(const CWalletTx& wtxIn)
103 uint256 hash = wtxIn.GetHash();
104 CRITICAL_BLOCK(cs_mapWallet)
106 // Inserts only if not already there, returns tx inserted or tx found
107 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
108 CWalletTx& wtx = (*ret.first).second;
109 bool fInsertedNew = ret.second;
110 if (fInsertedNew)
111 wtx.nTimeReceived = GetAdjustedTime();
113 bool fUpdated = false;
114 if (!fInsertedNew)
116 // Merge
117 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
119 wtx.hashBlock = wtxIn.hashBlock;
120 fUpdated = true;
122 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
124 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
125 wtx.nIndex = wtxIn.nIndex;
126 fUpdated = true;
128 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
130 wtx.fFromMe = wtxIn.fFromMe;
131 fUpdated = true;
133 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
135 wtx.fSpent = wtxIn.fSpent;
136 fUpdated = true;
140 //// debug print
141 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
143 // Write to disk
144 if (fInsertedNew || fUpdated)
145 if (!wtx.WriteToDisk())
146 return false;
148 // If default receiving address gets used, replace it with a new one
149 CScript scriptDefaultKey;
150 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
151 foreach(const CTxOut& txout, wtx.vout)
153 if (txout.scriptPubKey == scriptDefaultKey)
155 CWalletDB walletdb;
156 walletdb.WriteDefaultKey(GenerateNewKey());
157 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
161 // Notify UI
162 vWalletUpdated.push_back(hash);
165 // Refresh UI
166 MainFrameRepaint();
167 return true;
170 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
172 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
174 CWalletTx wtx(tx);
175 // Get merkle branch if transaction was found in a block
176 if (pblock)
177 wtx.SetMerkleBranch(pblock);
178 return AddToWallet(wtx);
180 return true;
183 bool EraseFromWallet(uint256 hash)
185 CRITICAL_BLOCK(cs_mapWallet)
187 if (mapWallet.erase(hash))
188 CWalletDB().EraseTx(hash);
190 return true;
193 void WalletUpdateSpent(const COutPoint& prevout)
195 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
196 // Update the wallet spent flag if it doesn't know due to wallet.dat being
197 // restored from backup or the user making copies of wallet.dat.
198 CRITICAL_BLOCK(cs_mapWallet)
200 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
201 if (mi != mapWallet.end())
203 CWalletTx& wtx = (*mi).second;
204 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
206 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
207 wtx.fSpent = true;
208 wtx.WriteToDisk();
209 vWalletUpdated.push_back(prevout.hash);
222 //////////////////////////////////////////////////////////////////////////////
224 // mapOrphanTransactions
227 void AddOrphanTx(const CDataStream& vMsg)
229 CTransaction tx;
230 CDataStream(vMsg) >> tx;
231 uint256 hash = tx.GetHash();
232 if (mapOrphanTransactions.count(hash))
233 return;
234 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
235 foreach(const CTxIn& txin, tx.vin)
236 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
239 void EraseOrphanTx(uint256 hash)
241 if (!mapOrphanTransactions.count(hash))
242 return;
243 const CDataStream* pvMsg = mapOrphanTransactions[hash];
244 CTransaction tx;
245 CDataStream(*pvMsg) >> tx;
246 foreach(const CTxIn& txin, tx.vin)
248 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
249 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
251 if ((*mi).second == pvMsg)
252 mapOrphanTransactionsByPrev.erase(mi++);
253 else
254 mi++;
257 delete pvMsg;
258 mapOrphanTransactions.erase(hash);
268 //////////////////////////////////////////////////////////////////////////////
270 // CTransaction
273 bool CTxIn::IsMine() const
275 CRITICAL_BLOCK(cs_mapWallet)
277 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
278 if (mi != mapWallet.end())
280 const CWalletTx& prev = (*mi).second;
281 if (prevout.n < prev.vout.size())
282 if (prev.vout[prevout.n].IsMine())
283 return true;
286 return false;
289 int64 CTxIn::GetDebit() const
291 CRITICAL_BLOCK(cs_mapWallet)
293 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
294 if (mi != mapWallet.end())
296 const CWalletTx& prev = (*mi).second;
297 if (prevout.n < prev.vout.size())
298 if (prev.vout[prevout.n].IsMine())
299 return prev.vout[prevout.n].nValue;
302 return 0;
305 int64 CWalletTx::GetTxTime() const
307 if (!fTimeReceivedIsTxTime && hashBlock != 0)
309 // If we did not receive the transaction directly, we rely on the block's
310 // time to figure out when it happened. We use the median over a range
311 // of blocks to try to filter out inaccurate block times.
312 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
313 if (mi != mapBlockIndex.end())
315 CBlockIndex* pindex = (*mi).second;
316 if (pindex)
317 return pindex->GetMedianTime();
320 return nTimeReceived;
323 int CWalletTx::GetRequestCount() const
325 // Returns -1 if it wasn't being tracked
326 int nRequests = -1;
327 CRITICAL_BLOCK(cs_mapRequestCount)
329 if (IsCoinBase())
331 // Generated block
332 if (hashBlock != 0)
334 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
335 if (mi != mapRequestCount.end())
336 nRequests = (*mi).second;
339 else
341 // Did anyone request this transaction?
342 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
343 if (mi != mapRequestCount.end())
345 nRequests = (*mi).second;
347 // How about the block it's in?
348 if (nRequests == 0 && hashBlock != 0)
350 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
351 if (mi != mapRequestCount.end())
352 nRequests = (*mi).second;
353 else
354 nRequests = 1; // If it's in someone else's block it must have got out
359 return nRequests;
365 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
367 if (fClient)
369 if (hashBlock == 0)
370 return 0;
372 else
374 CBlock blockTmp;
375 if (pblock == NULL)
377 // Load the block this tx is in
378 CTxIndex txindex;
379 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
380 return 0;
381 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
382 return 0;
383 pblock = &blockTmp;
386 // Update the tx's hashBlock
387 hashBlock = pblock->GetHash();
389 // Locate the transaction
390 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
391 if (pblock->vtx[nIndex] == *(CTransaction*)this)
392 break;
393 if (nIndex == pblock->vtx.size())
395 vMerkleBranch.clear();
396 nIndex = -1;
397 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
398 return 0;
401 // Fill in merkle branch
402 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
405 // Is the tx in a block that's in the main chain
406 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
407 if (mi == mapBlockIndex.end())
408 return 0;
409 CBlockIndex* pindex = (*mi).second;
410 if (!pindex || !pindex->IsInMainChain())
411 return 0;
413 return pindexBest->nHeight - pindex->nHeight + 1;
418 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
420 vtxPrev.clear();
422 const int COPY_DEPTH = 3;
423 if (SetMerkleBranch() < COPY_DEPTH)
425 vector<uint256> vWorkQueue;
426 foreach(const CTxIn& txin, vin)
427 vWorkQueue.push_back(txin.prevout.hash);
429 // This critsect is OK because txdb is already open
430 CRITICAL_BLOCK(cs_mapWallet)
432 map<uint256, const CMerkleTx*> mapWalletPrev;
433 set<uint256> setAlreadyDone;
434 for (int i = 0; i < vWorkQueue.size(); i++)
436 uint256 hash = vWorkQueue[i];
437 if (setAlreadyDone.count(hash))
438 continue;
439 setAlreadyDone.insert(hash);
441 CMerkleTx tx;
442 if (mapWallet.count(hash))
444 tx = mapWallet[hash];
445 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
446 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
448 else if (mapWalletPrev.count(hash))
450 tx = *mapWalletPrev[hash];
452 else if (!fClient && txdb.ReadDiskTx(hash, tx))
456 else
458 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
459 continue;
462 int nDepth = tx.SetMerkleBranch();
463 vtxPrev.push_back(tx);
465 if (nDepth < COPY_DEPTH)
466 foreach(const CTxIn& txin, tx.vin)
467 vWorkQueue.push_back(txin.prevout.hash);
472 reverse(vtxPrev.begin(), vtxPrev.end());
485 bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
487 if (pfMissingInputs)
488 *pfMissingInputs = false;
490 // Coinbase is only valid in a block, not as a loose transaction
491 if (IsCoinBase())
492 return error("AcceptTransaction() : coinbase as individual tx");
494 if (!CheckTransaction())
495 return error("AcceptTransaction() : CheckTransaction failed");
497 // To help v0.1.5 clients who would see it as a negative number
498 if (nLockTime > INT_MAX)
499 return error("AcceptTransaction() : not accepting nLockTime beyond 2038");
501 // Do we already have it?
502 uint256 hash = GetHash();
503 CRITICAL_BLOCK(cs_mapTransactions)
504 if (mapTransactions.count(hash))
505 return false;
506 if (fCheckInputs)
507 if (txdb.ContainsTx(hash))
508 return false;
510 // Check for conflicts with in-memory transactions
511 CTransaction* ptxOld = NULL;
512 for (int i = 0; i < vin.size(); i++)
514 COutPoint outpoint = vin[i].prevout;
515 if (mapNextTx.count(outpoint))
517 // Allow replacing with a newer version of the same transaction
518 if (i != 0)
519 return false;
520 ptxOld = mapNextTx[outpoint].ptx;
521 if (!IsNewerThan(*ptxOld))
522 return false;
523 for (int i = 0; i < vin.size(); i++)
525 COutPoint outpoint = vin[i].prevout;
526 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
527 return false;
529 break;
533 // Check against previous transactions
534 map<uint256, CTxIndex> mapUnused;
535 int64 nFees = 0;
536 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))
538 if (pfMissingInputs)
539 *pfMissingInputs = true;
540 return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());
543 // Store transaction in memory
544 CRITICAL_BLOCK(cs_mapTransactions)
546 if (ptxOld)
548 printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());
549 mapTransactions.erase(ptxOld->GetHash());
551 AddToMemoryPool();
554 ///// are we sure this is ok when loading transactions or restoring block txes
555 // If updated, erase old tx from wallet
556 if (ptxOld)
557 EraseFromWallet(ptxOld->GetHash());
559 printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());
560 return true;
564 bool CTransaction::AddToMemoryPool()
566 // Add to memory pool without checking anything. Don't call this directly,
567 // call AcceptTransaction to properly check the transaction first.
568 CRITICAL_BLOCK(cs_mapTransactions)
570 uint256 hash = GetHash();
571 mapTransactions[hash] = *this;
572 for (int i = 0; i < vin.size(); i++)
573 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
574 nTransactionsUpdated++;
576 return true;
580 bool CTransaction::RemoveFromMemoryPool()
582 // Remove transaction from memory pool
583 CRITICAL_BLOCK(cs_mapTransactions)
585 foreach(const CTxIn& txin, vin)
586 mapNextTx.erase(txin.prevout);
587 mapTransactions.erase(GetHash());
588 nTransactionsUpdated++;
590 return true;
598 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
600 if (hashBlock == 0 || nIndex == -1)
601 return 0;
603 // Find the block it claims to be in
604 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
605 if (mi == mapBlockIndex.end())
606 return 0;
607 CBlockIndex* pindex = (*mi).second;
608 if (!pindex || !pindex->IsInMainChain())
609 return 0;
611 // Make sure the merkle branch connects to this block
612 if (!fMerkleVerified)
614 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
615 return 0;
616 fMerkleVerified = true;
619 nHeightRet = pindex->nHeight;
620 return pindexBest->nHeight - pindex->nHeight + 1;
624 int CMerkleTx::GetBlocksToMaturity() const
626 if (!IsCoinBase())
627 return 0;
628 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
632 bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
634 if (fClient)
636 if (!IsInMainChain() && !ClientConnectInputs())
637 return false;
638 return CTransaction::AcceptTransaction(txdb, false);
640 else
642 return CTransaction::AcceptTransaction(txdb, fCheckInputs);
648 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
650 CRITICAL_BLOCK(cs_mapTransactions)
652 foreach(CMerkleTx& tx, vtxPrev)
654 if (!tx.IsCoinBase())
656 uint256 hash = tx.GetHash();
657 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
658 tx.AcceptTransaction(txdb, fCheckInputs);
661 if (!IsCoinBase())
662 return AcceptTransaction(txdb, fCheckInputs);
664 return true;
667 void ReacceptWalletTransactions()
669 CTxDB txdb("r");
670 CRITICAL_BLOCK(cs_mapWallet)
672 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
674 CWalletTx& wtx = item.second;
675 if (wtx.fSpent && wtx.IsCoinBase())
676 continue;
678 CTxIndex txindex;
679 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
681 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
682 if (!wtx.fSpent)
684 if (txindex.vSpent.size() != wtx.vout.size())
686 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
687 continue;
689 for (int i = 0; i < txindex.vSpent.size(); i++)
691 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
693 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
694 wtx.fSpent = true;
695 wtx.WriteToDisk();
696 break;
701 else
703 // Reaccept any txes of ours that aren't already in a block
704 if (!wtx.IsCoinBase())
705 wtx.AcceptWalletTransaction(txdb, false);
712 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
714 foreach(const CMerkleTx& tx, vtxPrev)
716 if (!tx.IsCoinBase())
718 uint256 hash = tx.GetHash();
719 if (!txdb.ContainsTx(hash))
720 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
723 if (!IsCoinBase())
725 uint256 hash = GetHash();
726 if (!txdb.ContainsTx(hash))
728 printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());
729 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
734 void ResendWalletTransactions()
736 // Do this infrequently and randomly to avoid giving away
737 // that these are our transactions.
738 static int64 nNextTime;
739 if (GetTime() < nNextTime)
740 return;
741 bool fFirst = (nNextTime == 0);
742 nNextTime = GetTime() + GetRand(120 * 60);
743 if (fFirst)
744 return;
746 // Rebroadcast any of our txes that aren't in a block yet
747 printf("ResendWalletTransactions()\n");
748 CTxDB txdb("r");
749 CRITICAL_BLOCK(cs_mapWallet)
751 // Sort them in chronological order
752 multimap<unsigned int, CWalletTx*> mapSorted;
753 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
755 CWalletTx& wtx = item.second;
756 // Don't rebroadcast until it's had plenty of time that
757 // it should have gotten in already by now.
758 if (nTimeBestReceived - wtx.nTimeReceived > 60 * 60)
759 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
761 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
763 CWalletTx& wtx = *item.second;
764 wtx.RelayWalletTransaction(txdb);
778 //////////////////////////////////////////////////////////////////////////////
780 // CBlock and CBlockIndex
783 bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)
785 return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);
788 uint256 GetOrphanRoot(const CBlock* pblock)
790 // Work back to the first block in the orphan chain
791 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
792 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
793 return pblock->GetHash();
796 int64 CBlock::GetBlockValue(int64 nFees) const
798 int64 nSubsidy = 50 * COIN;
800 // Subsidy is cut in half every 4 years
801 nSubsidy >>= (nBestHeight / 210000);
803 return nSubsidy + nFees;
806 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
808 const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
809 const unsigned int nTargetSpacing = 10 * 60;
810 const unsigned int nInterval = nTargetTimespan / nTargetSpacing;
812 // Genesis block
813 if (pindexLast == NULL)
814 return bnProofOfWorkLimit.GetCompact();
816 // Only change once per interval
817 if ((pindexLast->nHeight+1) % nInterval != 0)
818 return pindexLast->nBits;
820 // Go back by what we want to be 14 days worth of blocks
821 const CBlockIndex* pindexFirst = pindexLast;
822 for (int i = 0; pindexFirst && i < nInterval-1; i++)
823 pindexFirst = pindexFirst->pprev;
824 assert(pindexFirst);
826 // Limit adjustment step
827 unsigned int nActualTimespan = pindexLast->nTime - pindexFirst->nTime;
828 printf(" nActualTimespan = %d before bounds\n", nActualTimespan);
829 if (nActualTimespan < nTargetTimespan/4)
830 nActualTimespan = nTargetTimespan/4;
831 if (nActualTimespan > nTargetTimespan*4)
832 nActualTimespan = nTargetTimespan*4;
834 // Retarget
835 CBigNum bnNew;
836 bnNew.SetCompact(pindexLast->nBits);
837 bnNew *= nActualTimespan;
838 bnNew /= nTargetTimespan;
840 if (bnNew > bnProofOfWorkLimit)
841 bnNew = bnProofOfWorkLimit;
843 /// debug print
844 printf("GetNextWorkRequired RETARGET\n");
845 printf("nTargetTimespan = %d nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);
846 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
847 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
849 return bnNew.GetCompact();
852 vector<int> vStartingHeight;
853 void AddStartingHeight(int nStartingHeight)
855 if (nStartingHeight != -1)
857 vStartingHeight.push_back(nStartingHeight);
858 sort(vStartingHeight.begin(), vStartingHeight.end());
862 bool IsInitialBlockDownload()
864 int nMedian = 69000;
865 if (vStartingHeight.size() >= 5)
866 nMedian = vStartingHeight[vStartingHeight.size()/2];
867 return nBestHeight < nMedian-1000;
877 bool CTransaction::DisconnectInputs(CTxDB& txdb)
879 // Relinquish previous transactions' spent pointers
880 if (!IsCoinBase())
882 foreach(const CTxIn& txin, vin)
884 COutPoint prevout = txin.prevout;
886 // Get prev txindex from disk
887 CTxIndex txindex;
888 if (!txdb.ReadTxIndex(prevout.hash, txindex))
889 return error("DisconnectInputs() : ReadTxIndex failed");
891 if (prevout.n >= txindex.vSpent.size())
892 return error("DisconnectInputs() : prevout.n out of range");
894 // Mark outpoint as not spent
895 txindex.vSpent[prevout.n].SetNull();
897 // Write back
898 txdb.UpdateTxIndex(prevout.hash, txindex);
902 // Remove transaction from index
903 if (!txdb.EraseTxIndex(*this))
904 return error("DisconnectInputs() : EraseTxPos failed");
906 return true;
910 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
912 // Take over previous transactions' spent pointers
913 if (!IsCoinBase())
915 int64 nValueIn = 0;
916 for (int i = 0; i < vin.size(); i++)
918 COutPoint prevout = vin[i].prevout;
920 // Read txindex
921 CTxIndex txindex;
922 bool fFound = true;
923 if (fMiner && mapTestPool.count(prevout.hash))
925 // Get txindex from current proposed changes
926 txindex = mapTestPool[prevout.hash];
928 else
930 // Read txindex from txdb
931 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
933 if (!fFound && (fBlock || fMiner))
934 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
936 // Read txPrev
937 CTransaction txPrev;
938 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
940 // Get prev tx from single transactions in memory
941 CRITICAL_BLOCK(cs_mapTransactions)
943 if (!mapTransactions.count(prevout.hash))
944 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
945 txPrev = mapTransactions[prevout.hash];
947 if (!fFound)
948 txindex.vSpent.resize(txPrev.vout.size());
950 else
952 // Get prev tx from disk
953 if (!txPrev.ReadFromDisk(txindex.pos))
954 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
957 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
958 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,6).c_str(), txPrev.ToString().c_str());
960 // If prev is coinbase, check that it's matured
961 if (txPrev.IsCoinBase())
962 for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)
963 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
964 return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);
966 // Verify signature
967 if (!VerifySignature(txPrev, *this, i))
968 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
970 // Check for conflicts
971 if (!txindex.vSpent[prevout.n].IsNull())
972 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,6).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
974 // Mark outpoints as spent
975 txindex.vSpent[prevout.n] = posThisTx;
977 // Write back
978 if (fBlock)
979 txdb.UpdateTxIndex(prevout.hash, txindex);
980 else if (fMiner)
981 mapTestPool[prevout.hash] = txindex;
983 nValueIn += txPrev.vout[prevout.n].nValue;
986 // Tally transaction fees
987 int64 nTxFee = nValueIn - GetValueOut();
988 if (nTxFee < 0)
989 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
990 if (nTxFee < nMinFee)
991 return false;
992 nFees += nTxFee;
995 if (fBlock)
997 // Add transaction to disk index
998 if (!txdb.AddTxIndex(*this, posThisTx, nHeight))
999 return error("ConnectInputs() : AddTxPos failed");
1001 else if (fMiner)
1003 // Add transaction to test pool
1004 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1007 return true;
1011 bool CTransaction::ClientConnectInputs()
1013 if (IsCoinBase())
1014 return false;
1016 // Take over previous transactions' spent pointers
1017 CRITICAL_BLOCK(cs_mapTransactions)
1019 int64 nValueIn = 0;
1020 for (int i = 0; i < vin.size(); i++)
1022 // Get prev tx from single transactions in memory
1023 COutPoint prevout = vin[i].prevout;
1024 if (!mapTransactions.count(prevout.hash))
1025 return false;
1026 CTransaction& txPrev = mapTransactions[prevout.hash];
1028 if (prevout.n >= txPrev.vout.size())
1029 return false;
1031 // Verify signature
1032 if (!VerifySignature(txPrev, *this, i))
1033 return error("ConnectInputs() : VerifySignature failed");
1035 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1036 ///// this has to go away now that posNext is gone
1037 // // Check for conflicts
1038 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1039 // return error("ConnectInputs() : prev tx already used");
1041 // // Flag outpoints as used
1042 // txPrev.vout[prevout.n].posNext = posThisTx;
1044 nValueIn += txPrev.vout[prevout.n].nValue;
1046 if (GetValueOut() > nValueIn)
1047 return false;
1050 return true;
1056 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1058 // Disconnect in reverse order
1059 for (int i = vtx.size()-1; i >= 0; i--)
1060 if (!vtx[i].DisconnectInputs(txdb))
1061 return false;
1063 // Update block index on disk without changing it in memory.
1064 // The memory index structure will be changed after the db commits.
1065 if (pindex->pprev)
1067 CDiskBlockIndex blockindexPrev(pindex->pprev);
1068 blockindexPrev.hashNext = 0;
1069 txdb.WriteBlockIndex(blockindexPrev);
1072 return true;
1075 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1077 //// issue here: it doesn't know the version
1078 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1080 map<uint256, CTxIndex> mapUnused;
1081 int64 nFees = 0;
1082 foreach(CTransaction& tx, vtx)
1084 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1085 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1087 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))
1088 return false;
1091 if (vtx[0].GetValueOut() > GetBlockValue(nFees))
1092 return false;
1094 // Update block index on disk without changing it in memory.
1095 // The memory index structure will be changed after the db commits.
1096 if (pindex->pprev)
1098 CDiskBlockIndex blockindexPrev(pindex->pprev);
1099 blockindexPrev.hashNext = pindex->GetBlockHash();
1100 txdb.WriteBlockIndex(blockindexPrev);
1103 // Watch for transactions paying to me
1104 foreach(CTransaction& tx, vtx)
1105 AddToWalletIfMine(tx, this);
1107 return true;
1112 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1114 printf("REORGANIZE\n");
1116 // Find the fork
1117 CBlockIndex* pfork = pindexBest;
1118 CBlockIndex* plonger = pindexNew;
1119 while (pfork != plonger)
1121 if (!(pfork = pfork->pprev))
1122 return error("Reorganize() : pfork->pprev is null");
1123 while (plonger->nHeight > pfork->nHeight)
1124 if (!(plonger = plonger->pprev))
1125 return error("Reorganize() : plonger->pprev is null");
1128 // List of what to disconnect
1129 vector<CBlockIndex*> vDisconnect;
1130 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1131 vDisconnect.push_back(pindex);
1133 // List of what to connect
1134 vector<CBlockIndex*> vConnect;
1135 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1136 vConnect.push_back(pindex);
1137 reverse(vConnect.begin(), vConnect.end());
1139 // Disconnect shorter branch
1140 vector<CTransaction> vResurrect;
1141 foreach(CBlockIndex* pindex, vDisconnect)
1143 CBlock block;
1144 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1145 return error("Reorganize() : ReadFromDisk for disconnect failed");
1146 if (!block.DisconnectBlock(txdb, pindex))
1147 return error("Reorganize() : DisconnectBlock failed");
1149 // Queue memory transactions to resurrect
1150 foreach(const CTransaction& tx, block.vtx)
1151 if (!tx.IsCoinBase())
1152 vResurrect.push_back(tx);
1155 // Connect longer branch
1156 vector<CTransaction> vDelete;
1157 for (int i = 0; i < vConnect.size(); i++)
1159 CBlockIndex* pindex = vConnect[i];
1160 CBlock block;
1161 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
1162 return error("Reorganize() : ReadFromDisk for connect failed");
1163 if (!block.ConnectBlock(txdb, pindex))
1165 // Invalid block, delete the rest of this branch
1166 txdb.TxnAbort();
1167 for (int j = i; j < vConnect.size(); j++)
1169 CBlockIndex* pindex = vConnect[j];
1170 pindex->EraseBlockFromDisk();
1171 txdb.EraseBlockIndex(pindex->GetBlockHash());
1172 mapBlockIndex.erase(pindex->GetBlockHash());
1173 delete pindex;
1175 return error("Reorganize() : ConnectBlock failed");
1178 // Queue memory transactions to delete
1179 foreach(const CTransaction& tx, block.vtx)
1180 vDelete.push_back(tx);
1182 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1183 return error("Reorganize() : WriteHashBestChain failed");
1185 // Commit now because resurrecting could take some time
1186 txdb.TxnCommit();
1188 // Disconnect shorter branch
1189 foreach(CBlockIndex* pindex, vDisconnect)
1190 if (pindex->pprev)
1191 pindex->pprev->pnext = NULL;
1193 // Connect longer branch
1194 foreach(CBlockIndex* pindex, vConnect)
1195 if (pindex->pprev)
1196 pindex->pprev->pnext = pindex;
1198 // Resurrect memory transactions that were in the disconnected branch
1199 foreach(CTransaction& tx, vResurrect)
1200 tx.AcceptTransaction(txdb, false);
1202 // Delete redundant memory transactions that are in the connected branch
1203 foreach(CTransaction& tx, vDelete)
1204 tx.RemoveFromMemoryPool();
1206 return true;
1210 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1212 // Check for duplicate
1213 uint256 hash = GetHash();
1214 if (mapBlockIndex.count(hash))
1215 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());
1217 // Construct new block index object
1218 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1219 if (!pindexNew)
1220 return error("AddToBlockIndex() : new CBlockIndex failed");
1221 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1222 pindexNew->phashBlock = &((*mi).first);
1223 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1224 if (miPrev != mapBlockIndex.end())
1226 pindexNew->pprev = (*miPrev).second;
1227 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1229 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1231 CTxDB txdb;
1232 txdb.TxnBegin();
1233 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1235 // New best
1236 if (pindexNew->bnChainWork > bnBestChainWork)
1238 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1240 pindexGenesisBlock = pindexNew;
1241 txdb.WriteHashBestChain(hash);
1243 else if (hashPrevBlock == hashBestChain)
1245 // Adding to current best branch
1246 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1248 txdb.TxnAbort();
1249 pindexNew->EraseBlockFromDisk();
1250 mapBlockIndex.erase(pindexNew->GetBlockHash());
1251 delete pindexNew;
1252 return error("AddToBlockIndex() : ConnectBlock failed");
1254 txdb.TxnCommit();
1255 pindexNew->pprev->pnext = pindexNew;
1257 // Delete redundant memory transactions
1258 foreach(CTransaction& tx, vtx)
1259 tx.RemoveFromMemoryPool();
1261 else
1263 // New best branch
1264 if (!Reorganize(txdb, pindexNew))
1266 txdb.TxnAbort();
1267 return error("AddToBlockIndex() : Reorganize failed");
1271 // New best block
1272 hashBestChain = hash;
1273 pindexBest = pindexNew;
1274 nBestHeight = pindexBest->nHeight;
1275 bnBestChainWork = pindexNew->bnChainWork;
1276 nTimeBestReceived = GetTime();
1277 nTransactionsUpdated++;
1278 printf("AddToBlockIndex: new best=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);
1281 txdb.TxnCommit();
1282 txdb.Close();
1284 if (pindexNew == pindexBest)
1286 // Notify UI to display prev block's coinbase if it was ours
1287 static uint256 hashPrevBestCoinBase;
1288 CRITICAL_BLOCK(cs_mapWallet)
1289 vWalletUpdated.push_back(hashPrevBestCoinBase);
1290 hashPrevBestCoinBase = vtx[0].GetHash();
1293 MainFrameRepaint();
1294 return true;
1300 bool CBlock::CheckBlock() const
1302 // These are checks that are independent of context
1303 // that can be verified before saving an orphan block.
1305 // Size limits
1306 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
1307 return error("CheckBlock() : size limits failed");
1309 // Check timestamp
1310 if (nTime > GetAdjustedTime() + 2 * 60 * 60)
1311 return error("CheckBlock() : block timestamp too far in the future");
1313 // First transaction must be coinbase, the rest must not be
1314 if (vtx.empty() || !vtx[0].IsCoinBase())
1315 return error("CheckBlock() : first tx is not coinbase");
1316 for (int i = 1; i < vtx.size(); i++)
1317 if (vtx[i].IsCoinBase())
1318 return error("CheckBlock() : more than one coinbase");
1320 // Check transactions
1321 foreach(const CTransaction& tx, vtx)
1322 if (!tx.CheckTransaction())
1323 return error("CheckBlock() : CheckTransaction failed");
1325 // Check proof of work matches claimed amount
1326 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
1327 return error("CheckBlock() : nBits below minimum work");
1328 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
1329 return error("CheckBlock() : hash doesn't match nBits");
1331 // Check merkleroot
1332 if (hashMerkleRoot != BuildMerkleTree())
1333 return error("CheckBlock() : hashMerkleRoot mismatch");
1335 return true;
1338 bool CBlock::AcceptBlock()
1340 // Check for duplicate
1341 uint256 hash = GetHash();
1342 if (mapBlockIndex.count(hash))
1343 return error("AcceptBlock() : block already in mapBlockIndex");
1345 // Get prev block index
1346 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1347 if (mi == mapBlockIndex.end())
1348 return error("AcceptBlock() : prev block not found");
1349 CBlockIndex* pindexPrev = (*mi).second;
1351 // Check timestamp against prev
1352 if (nTime <= pindexPrev->GetMedianTimePast())
1353 return error("AcceptBlock() : block's timestamp is too early");
1355 // Check that all transactions are finalized
1356 foreach(const CTransaction& tx, vtx)
1357 if (!tx.IsFinal(nTime))
1358 return error("AcceptBlock() : contains a non-final transaction");
1360 // Check proof of work
1361 if (nBits != GetNextWorkRequired(pindexPrev))
1362 return error("AcceptBlock() : incorrect proof of work");
1364 // Check that the block chain matches the known block chain up to a checkpoint
1365 if (pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
1366 return error("AcceptBlock() : rejected by checkpoint lockin at 11111");
1367 if (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
1368 return error("AcceptBlock() : rejected by checkpoint lockin at 33333");
1369 if (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a"))
1370 return error("AcceptBlock() : rejected by checkpoint lockin at 68555");
1372 // Write block to history file
1373 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1374 return error("AcceptBlock() : out of disk space");
1375 unsigned int nFile;
1376 unsigned int nBlockPos;
1377 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1378 return error("AcceptBlock() : WriteToDisk failed");
1379 if (!AddToBlockIndex(nFile, nBlockPos))
1380 return error("AcceptBlock() : AddToBlockIndex failed");
1382 // Relay inventory, but don't relay old inventory during initial block download
1383 if (hashBestChain == hash)
1384 CRITICAL_BLOCK(cs_vNodes)
1385 foreach(CNode* pnode, vNodes)
1386 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1387 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1389 return true;
1392 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1394 // Check for duplicate
1395 uint256 hash = pblock->GetHash();
1396 if (mapBlockIndex.count(hash))
1397 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());
1398 if (mapOrphanBlocks.count(hash))
1399 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());
1401 // Preliminary checks
1402 if (!pblock->CheckBlock())
1404 delete pblock;
1405 return error("ProcessBlock() : CheckBlock FAILED");
1408 // If don't already have its previous block, shunt it off to holding area until we get it
1409 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1411 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());
1412 mapOrphanBlocks.insert(make_pair(hash, pblock));
1413 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1415 // Ask this guy to fill in what we're missing
1416 if (pfrom)
1417 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1418 return true;
1421 // Store to disk
1422 if (!pblock->AcceptBlock())
1424 delete pblock;
1425 return error("ProcessBlock() : AcceptBlock FAILED");
1427 delete pblock;
1429 // Recursively process any orphan blocks that depended on this one
1430 vector<uint256> vWorkQueue;
1431 vWorkQueue.push_back(hash);
1432 for (int i = 0; i < vWorkQueue.size(); i++)
1434 uint256 hashPrev = vWorkQueue[i];
1435 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1436 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1437 ++mi)
1439 CBlock* pblockOrphan = (*mi).second;
1440 if (pblockOrphan->AcceptBlock())
1441 vWorkQueue.push_back(pblockOrphan->GetHash());
1442 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1443 delete pblockOrphan;
1445 mapOrphanBlocksByPrev.erase(hashPrev);
1448 printf("ProcessBlock: ACCEPTED\n");
1449 return true;
1459 template<typename Stream>
1460 bool ScanMessageStart(Stream& s)
1462 // Scan ahead to the next pchMessageStart, which should normally be immediately
1463 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1464 s.clear(0);
1465 short prevmask = s.exceptions(0);
1466 const char* p = BEGIN(pchMessageStart);
1469 loop
1471 char c;
1472 s.read(&c, 1);
1473 if (s.fail())
1475 s.clear(0);
1476 s.exceptions(prevmask);
1477 return false;
1479 if (*p != c)
1480 p = BEGIN(pchMessageStart);
1481 if (*p == c)
1483 if (++p == END(pchMessageStart))
1485 s.clear(0);
1486 s.exceptions(prevmask);
1487 return true;
1492 catch (...)
1494 s.clear(0);
1495 s.exceptions(prevmask);
1496 return false;
1500 bool CheckDiskSpace(int64 nAdditionalBytes)
1502 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1504 // Check for 15MB because database could create another 10MB log file at any time
1505 if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)
1507 fShutdown = true;
1508 printf("*** %s***\n", _("Warning: Disk space is low "));
1509 #if wxUSE_GUI
1510 ThreadSafeMessageBox(_("Warning: Disk space is low "), "Bitcoin", wxOK | wxICON_EXCLAMATION);
1511 #endif
1512 CreateThread(Shutdown, NULL);
1513 return false;
1515 return true;
1518 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1520 if (nFile == -1)
1521 return NULL;
1522 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1523 if (!file)
1524 return NULL;
1525 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1527 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1529 fclose(file);
1530 return NULL;
1533 return file;
1536 static unsigned int nCurrentBlockFile = 1;
1538 FILE* AppendBlockFile(unsigned int& nFileRet)
1540 nFileRet = 0;
1541 loop
1543 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1544 if (!file)
1545 return NULL;
1546 if (fseek(file, 0, SEEK_END) != 0)
1547 return NULL;
1548 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1549 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1551 nFileRet = nCurrentBlockFile;
1552 return file;
1554 fclose(file);
1555 nCurrentBlockFile++;
1559 bool LoadBlockIndex(bool fAllowNew)
1562 // Load block index
1564 CTxDB txdb("cr");
1565 if (!txdb.LoadBlockIndex())
1566 return false;
1567 txdb.Close();
1570 // Init with genesis block
1572 if (mapBlockIndex.empty())
1574 if (!fAllowNew)
1575 return false;
1578 // Genesis Block:
1579 // GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
1580 // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
1581 // txNew.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
1582 // txNew.vout[0].nValue = 5000000000
1583 // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG
1584 // block.nVersion = 1
1585 // block.nTime = 1231006505
1586 // block.nBits = 0x1d00ffff
1587 // block.nNonce = 2083236893
1588 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1589 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1590 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1591 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1592 // vMerkleTree: 4a5e1e
1594 // Genesis block
1595 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1596 CTransaction txNew;
1597 txNew.vin.resize(1);
1598 txNew.vout.resize(1);
1599 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1600 txNew.vout[0].nValue = 50 * COIN;
1601 CBigNum bnPubKey;
1602 bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");
1603 txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;
1604 CBlock block;
1605 block.vtx.push_back(txNew);
1606 block.hashPrevBlock = 0;
1607 block.hashMerkleRoot = block.BuildMerkleTree();
1608 block.nVersion = 1;
1609 block.nTime = 1231006505;
1610 block.nBits = 0x1d00ffff;
1611 block.nNonce = 2083236893;
1613 //// debug print
1614 printf("%s\n", block.GetHash().ToString().c_str());
1615 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1616 printf("%s\n", hashGenesisBlock.ToString().c_str());
1617 txNew.vout[0].scriptPubKey.print();
1618 block.print();
1619 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1621 assert(block.GetHash() == hashGenesisBlock);
1623 // Start new block file
1624 unsigned int nFile;
1625 unsigned int nBlockPos;
1626 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1627 return error("LoadBlockIndex() : writing genesis block to disk failed");
1628 if (!block.AddToBlockIndex(nFile, nBlockPos))
1629 return error("LoadBlockIndex() : genesis block not accepted");
1632 return true;
1637 void PrintBlockTree()
1639 // precompute tree structure
1640 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1641 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1643 CBlockIndex* pindex = (*mi).second;
1644 mapNext[pindex->pprev].push_back(pindex);
1645 // test
1646 //while (rand() % 3 == 0)
1647 // mapNext[pindex->pprev].push_back(pindex);
1650 vector<pair<int, CBlockIndex*> > vStack;
1651 vStack.push_back(make_pair(0, pindexGenesisBlock));
1653 int nPrevCol = 0;
1654 while (!vStack.empty())
1656 int nCol = vStack.back().first;
1657 CBlockIndex* pindex = vStack.back().second;
1658 vStack.pop_back();
1660 // print split or gap
1661 if (nCol > nPrevCol)
1663 for (int i = 0; i < nCol-1; i++)
1664 printf("| ");
1665 printf("|\\\n");
1667 else if (nCol < nPrevCol)
1669 for (int i = 0; i < nCol; i++)
1670 printf("| ");
1671 printf("|\n");
1673 nPrevCol = nCol;
1675 // print columns
1676 for (int i = 0; i < nCol; i++)
1677 printf("| ");
1679 // print item
1680 CBlock block;
1681 block.ReadFromDisk(pindex);
1682 printf("%d (%u,%u) %s %s tx %d",
1683 pindex->nHeight,
1684 pindex->nFile,
1685 pindex->nBlockPos,
1686 block.GetHash().ToString().substr(0,16).c_str(),
1687 DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),
1688 block.vtx.size());
1690 CRITICAL_BLOCK(cs_mapWallet)
1692 if (mapWallet.count(block.vtx[0].GetHash()))
1694 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1695 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1698 printf("\n");
1701 // put the main timechain first
1702 vector<CBlockIndex*>& vNext = mapNext[pindex];
1703 for (int i = 0; i < vNext.size(); i++)
1705 if (vNext[i]->pnext)
1707 swap(vNext[0], vNext[i]);
1708 break;
1712 // iterate children
1713 for (int i = 0; i < vNext.size(); i++)
1714 vStack.push_back(make_pair(nCol+i, vNext[i]));
1727 //////////////////////////////////////////////////////////////////////////////
1729 // Messages
1733 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1735 switch (inv.type)
1737 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1738 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1740 // Don't know what it is, just say we already got one
1741 return true;
1750 bool ProcessMessages(CNode* pfrom)
1752 CDataStream& vRecv = pfrom->vRecv;
1753 if (vRecv.empty())
1754 return true;
1755 //if (fDebug)
1756 // printf("ProcessMessages(%d bytes)\n", vRecv.size());
1759 // Message format
1760 // (4) message start
1761 // (12) command
1762 // (4) size
1763 // (4) checksum
1764 // (x) data
1767 loop
1769 // Scan for message start
1770 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
1771 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
1772 if (vRecv.end() - pstart < nHeaderSize)
1774 if (vRecv.size() > nHeaderSize)
1776 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
1777 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
1779 break;
1781 if (pstart - vRecv.begin() > 0)
1782 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
1783 vRecv.erase(vRecv.begin(), pstart);
1785 // Read header
1786 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
1787 CMessageHeader hdr;
1788 vRecv >> hdr;
1789 if (!hdr.IsValid())
1791 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
1792 continue;
1794 string strCommand = hdr.GetCommand();
1796 // Message size
1797 unsigned int nMessageSize = hdr.nMessageSize;
1798 if (nMessageSize > vRecv.size())
1800 // Rewind and wait for rest of message
1801 ///// need a mechanism to give up waiting for overlong message size error
1802 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
1803 break;
1806 // Copy message to its own buffer
1807 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
1808 vRecv.ignore(nMessageSize);
1810 // Checksum
1811 if (vRecv.GetVersion() >= 209)
1813 uint256 hash = Hash(vMsg.begin(), vMsg.end());
1814 unsigned int nChecksum = 0;
1815 memcpy(&nChecksum, &hash, sizeof(nChecksum));
1816 if (nChecksum != hdr.nChecksum)
1818 printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
1819 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
1820 continue;
1824 // Process message
1825 bool fRet = false;
1828 CRITICAL_BLOCK(cs_main)
1829 fRet = ProcessMessage(pfrom, strCommand, vMsg);
1830 if (fShutdown)
1831 return true;
1833 catch (std::ios_base::failure& e)
1835 if (strstr(e.what(), "CDataStream::read() : end of data"))
1837 // Allow exceptions from underlength message on vRecv
1838 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
1840 else if (strstr(e.what(), ": size too large"))
1842 // Allow exceptions from overlong size
1843 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
1845 else
1847 PrintException(&e, "ProcessMessage()");
1850 catch (std::exception& e) {
1851 PrintException(&e, "ProcessMessage()");
1852 } catch (...) {
1853 PrintException(NULL, "ProcessMessage()");
1856 if (!fRet)
1857 printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);
1860 vRecv.Compact();
1861 return true;
1867 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1869 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1870 RandAddSeedPerfmon();
1871 if (fDebug)
1872 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1873 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1874 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1876 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1877 return true;
1884 if (strCommand == "version")
1886 // Each connection can only send one version message
1887 if (pfrom->nVersion != 0)
1888 return false;
1890 int64 nTime;
1891 CAddress addrMe;
1892 CAddress addrFrom;
1893 uint64 nNonce = 1;
1894 string strSubVer;
1895 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1896 if (pfrom->nVersion == 10300)
1897 pfrom->nVersion = 300;
1898 if (pfrom->nVersion >= 106 && !vRecv.empty())
1899 vRecv >> addrFrom >> nNonce;
1900 if (pfrom->nVersion >= 106 && !vRecv.empty())
1901 vRecv >> strSubVer;
1902 if (pfrom->nVersion >= 209 && !vRecv.empty())
1903 vRecv >> pfrom->nStartingHeight;
1905 if (pfrom->nVersion == 0)
1906 return false;
1908 // Disconnect if we connected to ourself
1909 if (nNonce == nLocalHostNonce && nNonce > 1)
1911 pfrom->fDisconnect = true;
1912 return true;
1915 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1916 if (pfrom->fClient)
1918 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
1919 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
1922 AddTimeData(pfrom->addr.ip, nTime);
1923 AddStartingHeight(pfrom->nStartingHeight);
1925 // Change version
1926 if (pfrom->nVersion >= 209)
1927 pfrom->PushMessage("verack");
1928 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1929 if (pfrom->nVersion < 209)
1930 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1932 // Ask the first connected node for block updates
1933 static int nAskedForBlocks;
1934 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1936 nAskedForBlocks++;
1937 pfrom->PushGetBlocks(pindexBest, uint256(0));
1940 pfrom->fSuccessfullyConnected = true;
1942 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1946 else if (pfrom->nVersion == 0)
1948 // Must have a version message before anything else
1949 return false;
1953 else if (strCommand == "verack")
1955 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1959 else if (strCommand == "addr")
1961 vector<CAddress> vAddr;
1962 vRecv >> vAddr;
1963 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
1964 return true;
1965 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
1966 return true;
1967 if (vAddr.size() > 1000)
1968 return error("message addr size() = %d", vAddr.size());
1970 // Store the new addresses
1971 foreach(CAddress& addr, vAddr)
1973 if (fShutdown)
1974 return true;
1975 // ignore IPv6 for now, since it isn't implemented anyway
1976 if (!addr.IsIPv4())
1977 continue;
1978 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
1979 if (pfrom->fGetAddr || vAddr.size() > 10)
1980 addr.nTime -= 5 * 24 * 60 * 60;
1981 AddAddress(addr);
1982 pfrom->AddAddressKnown(addr);
1983 if (!pfrom->fGetAddr && addr.IsRoutable())
1985 // Relay to a limited number of other nodes
1986 CRITICAL_BLOCK(cs_vNodes)
1988 // Use deterministic randomness to send to
1989 // the same places for 12 hours at a time
1990 static uint256 hashSalt;
1991 if (hashSalt == 0)
1992 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1993 uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
1994 multimap<uint256, CNode*> mapMix;
1995 foreach(CNode* pnode, vNodes)
1996 mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
1997 int nRelayNodes = 4;
1998 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1999 ((*mi).second)->PushAddress(addr);
2003 if (vAddr.size() < 1000)
2004 pfrom->fGetAddr = false;
2008 else if (strCommand == "inv")
2010 vector<CInv> vInv;
2011 vRecv >> vInv;
2012 if (vInv.size() > 50000)
2013 return error("message inv size() = %d", vInv.size());
2015 CTxDB txdb("r");
2016 foreach(const CInv& inv, vInv)
2018 if (fShutdown)
2019 return true;
2020 pfrom->AddInventoryKnown(inv);
2022 bool fAlreadyHave = AlreadyHave(txdb, inv);
2023 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2025 if (!fAlreadyHave)
2026 pfrom->AskFor(inv);
2027 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2028 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2030 // Track requests for our stuff
2031 CRITICAL_BLOCK(cs_mapRequestCount)
2033 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2034 if (mi != mapRequestCount.end())
2035 (*mi).second++;
2041 else if (strCommand == "getdata")
2043 vector<CInv> vInv;
2044 vRecv >> vInv;
2045 if (vInv.size() > 50000)
2046 return error("message getdata size() = %d", vInv.size());
2048 foreach(const CInv& inv, vInv)
2050 if (fShutdown)
2051 return true;
2052 printf("received getdata for: %s\n", inv.ToString().c_str());
2054 if (inv.type == MSG_BLOCK)
2056 // Send block from disk
2057 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2058 if (mi != mapBlockIndex.end())
2060 //// could optimize this to send header straight from blockindex for client
2061 CBlock block;
2062 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2063 pfrom->PushMessage("block", block);
2065 // Trigger them to send a getblocks request for the next batch of inventory
2066 if (inv.hash == pfrom->hashContinue)
2068 // Bypass PushInventory, this must send even if redundant,
2069 // and we want it right after the last block so they don't
2070 // wait for other stuff first.
2071 vector<CInv> vInv;
2072 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2073 pfrom->PushMessage("inv", vInv);
2074 pfrom->hashContinue = 0;
2078 else if (inv.IsKnownType())
2080 // Send stream from relay memory
2081 CRITICAL_BLOCK(cs_mapRelay)
2083 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2084 if (mi != mapRelay.end())
2085 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2089 // Track requests for our stuff
2090 CRITICAL_BLOCK(cs_mapRequestCount)
2092 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2093 if (mi != mapRequestCount.end())
2094 (*mi).second++;
2100 else if (strCommand == "getblocks")
2102 CBlockLocator locator;
2103 uint256 hashStop;
2104 vRecv >> locator >> hashStop;
2106 // Find the first block the caller has in the main chain
2107 CBlockIndex* pindex = locator.GetBlockIndex();
2109 // Send the rest of the chain
2110 if (pindex)
2111 pindex = pindex->pnext;
2112 int nLimit = 500 + locator.GetDistanceBack();
2113 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);
2114 for (; pindex; pindex = pindex->pnext)
2116 if (pindex->GetBlockHash() == hashStop)
2118 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2119 break;
2121 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2122 if (--nLimit <= 0)
2124 // When this block is requested, we'll send an inv that'll make them
2125 // getblocks the next batch of inventory.
2126 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
2127 pfrom->hashContinue = pindex->GetBlockHash();
2128 break;
2134 else if (strCommand == "tx")
2136 vector<uint256> vWorkQueue;
2137 CDataStream vMsg(vRecv);
2138 CTransaction tx;
2139 vRecv >> tx;
2141 CInv inv(MSG_TX, tx.GetHash());
2142 pfrom->AddInventoryKnown(inv);
2144 bool fMissingInputs = false;
2145 if (tx.AcceptTransaction(true, &fMissingInputs))
2147 AddToWalletIfMine(tx, NULL);
2148 RelayMessage(inv, vMsg);
2149 mapAlreadyAskedFor.erase(inv);
2150 vWorkQueue.push_back(inv.hash);
2152 // Recursively process any orphan transactions that depended on this one
2153 for (int i = 0; i < vWorkQueue.size(); i++)
2155 uint256 hashPrev = vWorkQueue[i];
2156 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2157 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2158 ++mi)
2160 const CDataStream& vMsg = *((*mi).second);
2161 CTransaction tx;
2162 CDataStream(vMsg) >> tx;
2163 CInv inv(MSG_TX, tx.GetHash());
2165 if (tx.AcceptTransaction(true))
2167 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2168 AddToWalletIfMine(tx, NULL);
2169 RelayMessage(inv, vMsg);
2170 mapAlreadyAskedFor.erase(inv);
2171 vWorkQueue.push_back(inv.hash);
2176 foreach(uint256 hash, vWorkQueue)
2177 EraseOrphanTx(hash);
2179 else if (fMissingInputs)
2181 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
2182 AddOrphanTx(vMsg);
2187 else if (strCommand == "block")
2189 auto_ptr<CBlock> pblock(new CBlock);
2190 vRecv >> *pblock;
2192 //// debug print
2193 printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());
2194 // pblock->print();
2196 CInv inv(MSG_BLOCK, pblock->GetHash());
2197 pfrom->AddInventoryKnown(inv);
2199 if (ProcessBlock(pfrom, pblock.release()))
2200 mapAlreadyAskedFor.erase(inv);
2204 else if (strCommand == "getaddr")
2206 // This includes all nodes that are currently online,
2207 // since they rebroadcast an addr every 24 hours
2208 pfrom->vAddrToSend.clear();
2209 int64 nSince = GetAdjustedTime() - 24 * 60 * 60; // in the last 24 hours
2210 CRITICAL_BLOCK(cs_mapAddresses)
2212 unsigned int nSize = mapAddresses.size();
2213 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2215 if (fShutdown)
2216 return true;
2217 const CAddress& addr = item.second;
2218 if (addr.nTime > nSince)
2219 pfrom->PushAddress(addr);
2225 else if (strCommand == "checkorder")
2227 uint256 hashReply;
2228 CWalletTx order;
2229 vRecv >> hashReply >> order;
2231 /// we have a chance to check the order here
2233 // Keep giving the same key to the same ip until they use it
2234 if (!mapReuseKey.count(pfrom->addr.ip))
2235 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
2237 // Send back approval of order and pubkey to use
2238 CScript scriptPubKey;
2239 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2240 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2244 else if (strCommand == "submitorder")
2246 uint256 hashReply;
2247 CWalletTx wtxNew;
2248 vRecv >> hashReply >> wtxNew;
2249 wtxNew.fFromMe = false;
2251 // Broadcast
2252 if (!wtxNew.AcceptWalletTransaction())
2254 pfrom->PushMessage("reply", hashReply, (int)1);
2255 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2257 wtxNew.fTimeReceivedIsTxTime = true;
2258 AddToWallet(wtxNew);
2259 wtxNew.RelayWalletTransaction();
2260 mapReuseKey.erase(pfrom->addr.ip);
2262 // Send back confirmation
2263 pfrom->PushMessage("reply", hashReply, (int)0);
2267 else if (strCommand == "reply")
2269 uint256 hashReply;
2270 vRecv >> hashReply;
2272 CRequestTracker tracker;
2273 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2275 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2276 if (mi != pfrom->mapRequests.end())
2278 tracker = (*mi).second;
2279 pfrom->mapRequests.erase(mi);
2282 if (!tracker.IsNull())
2283 tracker.fn(tracker.param1, vRecv);
2287 else if (strCommand == "ping")
2292 else
2294 // Ignore unknown commands for extensibility
2298 // Update the last seen time for this node's address
2299 if (pfrom->fNetworkNode)
2300 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2301 AddressCurrentlyConnected(pfrom->addr);
2304 return true;
2315 bool SendMessages(CNode* pto, bool fSendTrickle)
2317 CRITICAL_BLOCK(cs_main)
2319 // Don't send anything until we get their version message
2320 if (pto->nVersion == 0)
2321 return true;
2323 // Keep-alive ping
2324 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2325 pto->PushMessage("ping");
2327 // Address refresh broadcast
2328 static int64 nLastRebroadcast;
2329 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2331 nLastRebroadcast = GetTime();
2332 CRITICAL_BLOCK(cs_vNodes)
2334 foreach(CNode* pnode, vNodes)
2336 // Periodically clear setAddrKnown to allow refresh broadcasts
2337 pnode->setAddrKnown.clear();
2339 // Rebroadcast our address
2340 if (addrLocalHost.IsRoutable() && !fUseProxy)
2341 pnode->PushAddress(addrLocalHost);
2346 // Resend wallet transactions that haven't gotten in a block yet
2347 ResendWalletTransactions();
2351 // Message: addr
2353 if (fSendTrickle)
2355 vector<CAddress> vAddr;
2356 vAddr.reserve(pto->vAddrToSend.size());
2357 foreach(const CAddress& addr, pto->vAddrToSend)
2359 // returns true if wasn't already contained in the set
2360 if (pto->setAddrKnown.insert(addr).second)
2362 vAddr.push_back(addr);
2363 // receiver rejects addr messages larger than 1000
2364 if (vAddr.size() >= 1000)
2366 pto->PushMessage("addr", vAddr);
2367 vAddr.clear();
2371 pto->vAddrToSend.clear();
2372 if (!vAddr.empty())
2373 pto->PushMessage("addr", vAddr);
2378 // Message: inventory
2380 vector<CInv> vInv;
2381 vector<CInv> vInvWait;
2382 CRITICAL_BLOCK(pto->cs_inventory)
2384 vInv.reserve(pto->vInventoryToSend.size());
2385 vInvWait.reserve(pto->vInventoryToSend.size());
2386 foreach(const CInv& inv, pto->vInventoryToSend)
2388 if (pto->setInventoryKnown.count(inv))
2389 continue;
2391 // trickle out tx inv to protect privacy
2392 if (inv.type == MSG_TX && !fSendTrickle)
2394 // 1/4 of tx invs blast to all immediately
2395 static uint256 hashSalt;
2396 if (hashSalt == 0)
2397 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2398 uint256 hashRand = inv.hash ^ hashSalt;
2399 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2400 bool fTrickleWait = ((hashRand & 3) != 0);
2402 // always trickle our own transactions
2403 if (!fTrickleWait)
2405 TRY_CRITICAL_BLOCK(cs_mapWallet)
2407 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2408 if (mi != mapWallet.end())
2410 CWalletTx& wtx = (*mi).second;
2411 if (wtx.fFromMe)
2412 fTrickleWait = true;
2417 if (fTrickleWait)
2419 vInvWait.push_back(inv);
2420 continue;
2424 // returns true if wasn't already contained in the set
2425 if (pto->setInventoryKnown.insert(inv).second)
2427 vInv.push_back(inv);
2428 if (vInv.size() >= 1000)
2430 pto->PushMessage("inv", vInv);
2431 vInv.clear();
2435 pto->vInventoryToSend = vInvWait;
2437 if (!vInv.empty())
2438 pto->PushMessage("inv", vInv);
2442 // Message: getdata
2444 vector<CInv> vGetData;
2445 int64 nNow = GetTime() * 1000000;
2446 CTxDB txdb("r");
2447 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2449 const CInv& inv = (*pto->mapAskFor.begin()).second;
2450 if (!AlreadyHave(txdb, inv))
2452 printf("sending getdata: %s\n", inv.ToString().c_str());
2453 vGetData.push_back(inv);
2454 if (vGetData.size() >= 1000)
2456 pto->PushMessage("getdata", vGetData);
2457 vGetData.clear();
2460 pto->mapAskFor.erase(pto->mapAskFor.begin());
2462 if (!vGetData.empty())
2463 pto->PushMessage("getdata", vGetData);
2466 return true;
2482 //////////////////////////////////////////////////////////////////////////////
2484 // BitcoinMiner
2487 void GenerateBitcoins(bool fGenerate)
2489 if (fGenerateBitcoins != fGenerate)
2491 fGenerateBitcoins = fGenerate;
2492 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2493 MainFrameRepaint();
2495 if (fGenerateBitcoins)
2497 int nProcessors = wxThread::GetCPUCount();
2498 printf("%d processors\n", nProcessors);
2499 if (nProcessors < 1)
2500 nProcessors = 1;
2501 if (fLimitProcessors && nProcessors > nLimitProcessors)
2502 nProcessors = nLimitProcessors;
2503 int nAddThreads = nProcessors - vnThreadsRunning[3];
2504 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2505 for (int i = 0; i < nAddThreads; i++)
2507 if (!CreateThread(ThreadBitcoinMiner, NULL))
2508 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2509 Sleep(10);
2514 void ThreadBitcoinMiner(void* parg)
2518 vnThreadsRunning[3]++;
2519 BitcoinMiner();
2520 vnThreadsRunning[3]--;
2522 catch (std::exception& e) {
2523 vnThreadsRunning[3]--;
2524 PrintException(&e, "ThreadBitcoinMiner()");
2525 } catch (...) {
2526 vnThreadsRunning[3]--;
2527 PrintException(NULL, "ThreadBitcoinMiner()");
2529 UIThreadCall(bind(CalledSetStatusBar, "", 0));
2530 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2533 int FormatHashBlocks(void* pbuffer, unsigned int len)
2535 unsigned char* pdata = (unsigned char*)pbuffer;
2536 unsigned int blocks = 1 + ((len + 8) / 64);
2537 unsigned char* pend = pdata + 64 * blocks;
2538 memset(pdata + len, 0, 64 * blocks - len);
2539 pdata[len] = 0x80;
2540 unsigned int bits = len * 8;
2541 pend[-1] = (bits >> 0) & 0xff;
2542 pend[-2] = (bits >> 8) & 0xff;
2543 pend[-3] = (bits >> 16) & 0xff;
2544 pend[-4] = (bits >> 24) & 0xff;
2545 return blocks;
2548 using CryptoPP::ByteReverse;
2549 static int detectlittleendian = 1;
2551 void BlockSHA256(const void* pin, unsigned int nBlocks, void* pout)
2553 unsigned int* pinput = (unsigned int*)pin;
2554 unsigned int* pstate = (unsigned int*)pout;
2556 CryptoPP::SHA256::InitState(pstate);
2558 if (*(char*)&detectlittleendian != 0)
2560 for (int n = 0; n < nBlocks; n++)
2562 unsigned int pbuf[16];
2563 for (int i = 0; i < 16; i++)
2564 pbuf[i] = ByteReverse(pinput[n * 16 + i]);
2565 CryptoPP::SHA256::Transform(pstate, pbuf);
2567 for (int i = 0; i < 8; i++)
2568 pstate[i] = ByteReverse(pstate[i]);
2570 else
2572 for (int n = 0; n < nBlocks; n++)
2573 CryptoPP::SHA256::Transform(pstate, pinput + n * 16);
2578 void BitcoinMiner()
2580 printf("BitcoinMiner started\n");
2581 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2583 CKey key;
2584 key.MakeNewKey();
2585 CBigNum bnExtraNonce = 0;
2586 while (fGenerateBitcoins)
2588 Sleep(50);
2589 if (fShutdown)
2590 return;
2591 while (vNodes.empty())
2593 Sleep(1000);
2594 if (fShutdown)
2595 return;
2596 if (!fGenerateBitcoins)
2597 return;
2600 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2601 CBlockIndex* pindexPrev = pindexBest;
2602 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2606 // Create coinbase tx
2608 CTransaction txNew;
2609 txNew.vin.resize(1);
2610 txNew.vin[0].prevout.SetNull();
2611 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
2612 txNew.vout.resize(1);
2613 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
2617 // Create new block
2619 auto_ptr<CBlock> pblock(new CBlock());
2620 if (!pblock.get())
2621 return;
2623 // Add our coinbase tx as first transaction
2624 pblock->vtx.push_back(txNew);
2626 // Collect the latest transactions into the block
2627 int64 nFees = 0;
2628 CRITICAL_BLOCK(cs_main)
2629 CRITICAL_BLOCK(cs_mapTransactions)
2631 CTxDB txdb("r");
2632 map<uint256, CTxIndex> mapTestPool;
2633 vector<char> vfAlreadyAdded(mapTransactions.size());
2634 bool fFoundSomething = true;
2635 unsigned int nBlockSize = 0;
2636 while (fFoundSomething && nBlockSize < MAX_SIZE/2)
2638 fFoundSomething = false;
2639 unsigned int n = 0;
2640 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
2642 if (vfAlreadyAdded[n])
2643 continue;
2644 CTransaction& tx = (*mi).second;
2645 if (tx.IsCoinBase() || !tx.IsFinal())
2646 continue;
2647 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2648 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)
2649 continue;
2651 // Transaction fee based on block size
2652 int64 nMinFee = tx.GetMinFee(nBlockSize);
2654 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2655 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))
2656 continue;
2657 swap(mapTestPool, mapTestPoolTmp);
2659 pblock->vtx.push_back(tx);
2660 nBlockSize += nTxSize;
2661 vfAlreadyAdded[n] = true;
2662 fFoundSomething = true;
2666 pblock->nBits = nBits;
2667 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);
2668 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2672 // Prebuild hash buffer
2674 struct unnamed1
2676 struct unnamed2
2678 int nVersion;
2679 uint256 hashPrevBlock;
2680 uint256 hashMerkleRoot;
2681 unsigned int nTime;
2682 unsigned int nBits;
2683 unsigned int nNonce;
2685 block;
2686 unsigned char pchPadding0[64];
2687 uint256 hash1;
2688 unsigned char pchPadding1[64];
2690 tmp;
2692 tmp.block.nVersion = pblock->nVersion;
2693 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
2694 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2695 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
2696 tmp.block.nBits = pblock->nBits = nBits;
2697 tmp.block.nNonce = pblock->nNonce = 1;
2699 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2700 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2704 // Search
2706 int64 nStart = GetTime();
2707 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2708 uint256 hash;
2709 loop
2711 BlockSHA256(&tmp.block, nBlocks0, &tmp.hash1);
2712 BlockSHA256(&tmp.hash1, nBlocks1, &hash);
2714 if (hash <= hashTarget)
2716 pblock->nNonce = tmp.block.nNonce;
2717 assert(hash == pblock->GetHash());
2719 //// debug print
2720 printf("BitcoinMiner:\n");
2721 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2722 pblock->print();
2723 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2724 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2726 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2727 CRITICAL_BLOCK(cs_main)
2729 if (pindexPrev == pindexBest)
2731 // Save key
2732 if (!AddKey(key))
2733 return;
2734 key.MakeNewKey();
2736 // Track how many getdata requests this block gets
2737 CRITICAL_BLOCK(cs_mapRequestCount)
2738 mapRequestCount[pblock->GetHash()] = 0;
2740 // Process this block the same as if we had received it from another node
2741 if (!ProcessBlock(NULL, pblock.release()))
2742 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
2745 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2747 Sleep(500);
2748 break;
2751 // Update nTime every few seconds
2752 const unsigned int nMask = 0xffff;
2753 if ((++tmp.block.nNonce & nMask) == 0)
2755 // Meter hashes/sec
2756 static int64 nTimerStart;
2757 static int nHashCounter;
2758 if (nTimerStart == 0)
2759 nTimerStart = GetTimeMillis();
2760 else
2761 nHashCounter++;
2762 if (GetTimeMillis() - nTimerStart > 4000)
2764 static CCriticalSection cs;
2765 CRITICAL_BLOCK(cs)
2767 if (GetTimeMillis() - nTimerStart > 4000)
2769 double dHashesPerSec = 1000.0 * (nMask+1) * nHashCounter / (GetTimeMillis() - nTimerStart);
2770 nTimerStart = GetTimeMillis();
2771 nHashCounter = 0;
2772 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
2773 UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));
2774 static int64 nLogTime;
2775 if (GetTime() - nLogTime > 30 * 60)
2777 nLogTime = GetTime();
2778 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2779 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
2785 // Check for stop or if block needs to be rebuilt
2786 if (fShutdown)
2787 return;
2788 if (!fGenerateBitcoins)
2789 return;
2790 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
2791 return;
2792 if (vNodes.empty())
2793 break;
2794 if (tmp.block.nNonce == 0)
2795 break;
2796 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2797 break;
2798 if (pindexPrev != pindexBest)
2800 // Pause generating during initial download
2801 if (GetTime() - nStart < 20)
2803 CBlockIndex* pindexTmp;
2806 pindexTmp = pindexBest;
2807 for (int i = 0; i < 10; i++)
2809 Sleep(1000);
2810 if (fShutdown)
2811 return;
2814 while (pindexTmp != pindexBest);
2816 break;
2819 tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2842 //////////////////////////////////////////////////////////////////////////////
2844 // Actions
2848 int64 GetBalance()
2850 int64 nStart = GetTimeMillis();
2852 int64 nTotal = 0;
2853 CRITICAL_BLOCK(cs_mapWallet)
2855 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2857 CWalletTx* pcoin = &(*it).second;
2858 if (!pcoin->IsFinal() || pcoin->fSpent)
2859 continue;
2860 nTotal += pcoin->GetCredit(true);
2864 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
2865 return nTotal;
2869 int GetRandInt(int nMax)
2871 return GetRand(nMax);
2874 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
2876 setCoinsRet.clear();
2878 // List of values less than target
2879 int64 nLowestLarger = INT64_MAX;
2880 CWalletTx* pcoinLowestLarger = NULL;
2881 vector<pair<int64, CWalletTx*> > vValue;
2882 int64 nTotalLower = 0;
2884 CRITICAL_BLOCK(cs_mapWallet)
2886 vector<CWalletTx*> vCoins;
2887 vCoins.reserve(mapWallet.size());
2888 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2889 vCoins.push_back(&(*it).second);
2890 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2892 foreach(CWalletTx* pcoin, vCoins)
2894 if (!pcoin->IsFinal() || pcoin->fSpent)
2895 continue;
2896 int64 n = pcoin->GetCredit();
2897 if (n <= 0)
2898 continue;
2899 if (n < nTargetValue)
2901 vValue.push_back(make_pair(n, pcoin));
2902 nTotalLower += n;
2904 else if (n == nTargetValue)
2906 setCoinsRet.insert(pcoin);
2907 return true;
2909 else if (n < nLowestLarger)
2911 nLowestLarger = n;
2912 pcoinLowestLarger = pcoin;
2917 if (nTotalLower < nTargetValue)
2919 if (pcoinLowestLarger == NULL)
2920 return false;
2921 setCoinsRet.insert(pcoinLowestLarger);
2922 return true;
2925 // Solve subset sum by stochastic approximation
2926 sort(vValue.rbegin(), vValue.rend());
2927 vector<char> vfIncluded;
2928 vector<char> vfBest(vValue.size(), true);
2929 int64 nBest = nTotalLower;
2931 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
2933 vfIncluded.assign(vValue.size(), false);
2934 int64 nTotal = 0;
2935 bool fReachedTarget = false;
2936 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2938 for (int i = 0; i < vValue.size(); i++)
2940 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
2942 nTotal += vValue[i].first;
2943 vfIncluded[i] = true;
2944 if (nTotal >= nTargetValue)
2946 fReachedTarget = true;
2947 if (nTotal < nBest)
2949 nBest = nTotal;
2950 vfBest = vfIncluded;
2952 nTotal -= vValue[i].first;
2953 vfIncluded[i] = false;
2960 // If the next larger is still closer, return it
2961 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
2962 setCoinsRet.insert(pcoinLowestLarger);
2963 else
2965 for (int i = 0; i < vValue.size(); i++)
2966 if (vfBest[i])
2967 setCoinsRet.insert(vValue[i].second);
2969 //// debug print
2970 printf("SelectCoins() best subset: ");
2971 for (int i = 0; i < vValue.size(); i++)
2972 if (vfBest[i])
2973 printf("%s ", FormatMoney(vValue[i].first).c_str());
2974 printf("total %s\n", FormatMoney(nBest).c_str());
2977 return true;
2983 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
2985 nFeeRequiredRet = 0;
2986 CRITICAL_BLOCK(cs_main)
2988 // txdb must be opened before the mapWallet lock
2989 CTxDB txdb("r");
2990 CRITICAL_BLOCK(cs_mapWallet)
2992 int64 nFee = nTransactionFee;
2993 loop
2995 wtxNew.vin.clear();
2996 wtxNew.vout.clear();
2997 wtxNew.fFromMe = true;
2998 if (nValue < 0)
2999 return false;
3000 int64 nValueOut = nValue;
3001 int64 nTotalValue = nValue + nFee;
3003 // Choose coins to use
3004 set<CWalletTx*> setCoins;
3005 if (!SelectCoins(nTotalValue, setCoins))
3006 return false;
3007 int64 nValueIn = 0;
3008 foreach(CWalletTx* pcoin, setCoins)
3009 nValueIn += pcoin->GetCredit();
3011 // Fill a vout to the payee
3012 bool fChangeFirst = GetRand(2);
3013 if (!fChangeFirst)
3014 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3016 // Fill a vout back to self with any change
3017 if (nValueIn > nTotalValue)
3019 // Note: We use a new key here to keep it from being obvious which side is the change.
3020 // The drawback is that by not reusing a previous key, the change may be lost if a
3021 // backup is restored, if the backup doesn't have the new private key for the change.
3022 // If we reused the old key, it would be possible to add code to look for and
3023 // rediscover unknown transactions that were written with keys of ours to recover
3024 // post-backup change.
3026 // New private key
3027 if (keyRet.IsNull())
3028 keyRet.MakeNewKey();
3030 // Fill a vout to ourself, using same address type as the payment
3031 CScript scriptChange;
3032 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3033 scriptChange.SetBitcoinAddress(keyRet.GetPubKey());
3034 else
3035 scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;
3036 wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));
3039 // Fill a vout to the payee
3040 if (fChangeFirst)
3041 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3043 // Fill vin
3044 foreach(CWalletTx* pcoin, setCoins)
3045 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3046 if (pcoin->vout[nOut].IsMine())
3047 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3049 // Sign
3050 int nIn = 0;
3051 foreach(CWalletTx* pcoin, setCoins)
3052 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3053 if (pcoin->vout[nOut].IsMine())
3054 SignSignature(*pcoin, wtxNew, nIn++);
3056 // Check that enough fee is included
3057 if (nFee < wtxNew.GetMinFee())
3059 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3060 continue;
3063 // Fill vtxPrev by copying from previous transactions vtxPrev
3064 wtxNew.AddSupportingTransactions(txdb);
3065 wtxNew.fTimeReceivedIsTxTime = true;
3067 break;
3071 return true;
3074 // Call after CreateTransaction unless you want to abort
3075 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)
3077 CRITICAL_BLOCK(cs_main)
3079 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3080 CRITICAL_BLOCK(cs_mapWallet)
3082 // This is only to keep the database open to defeat the auto-flush for the
3083 // duration of this scope. This is the only place where this optimization
3084 // maybe makes sense; please don't do it anywhere else.
3085 CWalletDB walletdb("r");
3087 // Add the change's private key to wallet
3088 if (!key.IsNull() && !AddKey(key))
3089 throw runtime_error("CommitTransaction() : AddKey failed\n");
3091 // Add tx to wallet, because if it has change it's also ours,
3092 // otherwise just for transaction history.
3093 AddToWallet(wtxNew);
3095 // Mark old coins as spent
3096 set<CWalletTx*> setCoins;
3097 foreach(const CTxIn& txin, wtxNew.vin)
3098 setCoins.insert(&mapWallet[txin.prevout.hash]);
3099 foreach(CWalletTx* pcoin, setCoins)
3101 pcoin->fSpent = true;
3102 pcoin->WriteToDisk();
3103 vWalletUpdated.push_back(pcoin->GetHash());
3107 // Track how many getdata requests our transaction gets
3108 CRITICAL_BLOCK(cs_mapRequestCount)
3109 mapRequestCount[wtxNew.GetHash()] = 0;
3111 // Broadcast
3112 if (!wtxNew.AcceptTransaction())
3114 // This must not fail. The transaction has already been signed and recorded.
3115 printf("CommitTransaction() : Error: Transaction not valid");
3116 return false;
3118 wtxNew.RelayWalletTransaction();
3120 MainFrameRepaint();
3121 return true;
3127 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3129 CRITICAL_BLOCK(cs_main)
3131 CKey key;
3132 int64 nFeeRequired;
3133 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
3135 string strError;
3136 if (nValue + nFeeRequired > GetBalance())
3137 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3138 else
3139 strError = _("Error: Transaction creation failed ");
3140 printf("SendMoney() : %s", strError.c_str());
3141 return strError;
3144 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3145 return "ABORTED";
3147 if (!CommitTransaction(wtxNew, key))
3148 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.");
3150 MainFrameRepaint();
3151 return "";
3156 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3158 // Check amount
3159 if (nValue <= 0)
3160 return _("Invalid amount");
3161 if (nValue + nTransactionFee > GetBalance())
3162 return _("Insufficient funds");
3164 // Parse bitcoin address
3165 CScript scriptPubKey;
3166 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3167 return _("Invalid bitcoin address");
3169 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);