add GetTotalBlocksEstimate() function, move magic number to constant
[novacoin.git] / src / main.cpp
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.
4 #include "headers.h"
5 #include "db.h"
6 #include "net.h"
7 #include "init.h"
8 #include "cryptopp/sha.h"
9 #include <boost/filesystem/fstream.hpp>
10
11 using namespace std;
12 using namespace boost;
13
14 //
15 // Global state
16 //
17
18 CCriticalSection cs_main;
19
20 map<uint256, CTransaction> mapTransactions;
21 CCriticalSection cs_mapTransactions;
22 unsigned int nTransactionsUpdated = 0;
23 map<COutPoint, CInPoint> mapNextTx;
24
25 map<uint256, CBlockIndex*> mapBlockIndex;
26 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
27 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
28 const int nTotalBlocksEstimate = 131000; // Conservative estimate of total nr of blocks on main chain
29 const int nInitialBlockThreshold = 10000; // Regard blocks up until N-threshold as "initial download"
30 CBlockIndex* pindexGenesisBlock = NULL;
31 int nBestHeight = -1;
32 CBigNum bnBestChainWork = 0;
33 CBigNum bnBestInvalidWork = 0;
34 uint256 hashBestChain = 0;
35 CBlockIndex* pindexBest = NULL;
36 int64 nTimeBestReceived = 0;
37
38 map<uint256, CBlock*> mapOrphanBlocks;
39 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
40
41 map<uint256, CDataStream*> mapOrphanTransactions;
42 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
43
44 map<uint256, CWalletTx> mapWallet;
45 vector<uint256> vWalletUpdated;
46 CCriticalSection cs_mapWallet;
47
48 map<vector<unsigned char>, CPrivKey> mapKeys;
49 map<uint160, vector<unsigned char> > mapPubKeys;
50 CCriticalSection cs_mapKeys;
51 CKey keyUser;
52
53 map<uint256, int> mapRequestCount;
54 CCriticalSection cs_mapRequestCount;
55
56 map<string, string> mapAddressBook;
57 CCriticalSection cs_mapAddressBook;
58
59 vector<unsigned char> vchDefaultKey;
60
61 double dHashesPerSec;
62 int64 nHPSTimerStart;
63
64 // Settings
65 int fGenerateBitcoins = false;
66 int64 nTransactionFee = 0;
67 CAddress addrIncoming;
68 int fLimitProcessors = false;
69 int nLimitProcessors = 1;
70 int fMinimizeToTray = true;
71 int fMinimizeOnClose = true;
72 #if USE_UPNP
73 int fUseUPnP = true;
74 #else
75 int fUseUPnP = false;
76 #endif
77
78
79
80
81
82
83
84 //////////////////////////////////////////////////////////////////////////////
85 //
86 // mapKeys
87 //
88
89 bool AddKey(const CKey& key)
90 {
91     CRITICAL_BLOCK(cs_mapKeys)
92     {
93         mapKeys[key.GetPubKey()] = key.GetPrivKey();
94         mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
95     }
96     return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
97 }
98
99 vector<unsigned char> GenerateNewKey()
100 {
101     RandAddSeedPerfmon();
102     CKey key;
103     key.MakeNewKey();
104     if (!AddKey(key))
105         throw runtime_error("GenerateNewKey() : AddKey failed");
106     return key.GetPubKey();
107 }
108
109
110
111
112 //////////////////////////////////////////////////////////////////////////////
113 //
114 // mapWallet
115 //
116
117 bool AddToWallet(const CWalletTx& wtxIn)
118 {
119     uint256 hash = wtxIn.GetHash();
120     CRITICAL_BLOCK(cs_mapWallet)
121     {
122         // Inserts only if not already there, returns tx inserted or tx found
123         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
124         CWalletTx& wtx = (*ret.first).second;
125         bool fInsertedNew = ret.second;
126         if (fInsertedNew)
127             wtx.nTimeReceived = GetAdjustedTime();
128
129         bool fUpdated = false;
130         if (!fInsertedNew)
131         {
132             // Merge
133             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
134             {
135                 wtx.hashBlock = wtxIn.hashBlock;
136                 fUpdated = true;
137             }
138             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
139             {
140                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
141                 wtx.nIndex = wtxIn.nIndex;
142                 fUpdated = true;
143             }
144             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
145             {
146                 wtx.fFromMe = wtxIn.fFromMe;
147                 fUpdated = true;
148             }
149             fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
150         }
151
152         //// debug print
153         printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
154
155         // Write to disk
156         if (fInsertedNew || fUpdated)
157             if (!wtx.WriteToDisk())
158                 return false;
159
160         // If default receiving address gets used, replace it with a new one
161         CScript scriptDefaultKey;
162         scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
163         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
164         {
165             if (txout.scriptPubKey == scriptDefaultKey)
166             {
167                 CWalletDB walletdb;
168                 vchDefaultKey = GetKeyFromKeyPool();
169                 walletdb.WriteDefaultKey(vchDefaultKey);
170                 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
171             }
172         }
173
174         // Notify UI
175         vWalletUpdated.push_back(hash);
176     }
177
178     // Refresh UI
179     MainFrameRepaint();
180     return true;
181 }
182
183 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false)
184 {
185     uint256 hash = tx.GetHash();
186     bool fExisted = mapWallet.count(hash);
187     if (fExisted && !fUpdate) return false;
188     if (fExisted || tx.IsMine() || tx.IsFromMe())
189     {
190         CWalletTx wtx(tx);
191         // Get merkle branch if transaction was found in a block
192         if (pblock)
193             wtx.SetMerkleBranch(pblock);
194         return AddToWallet(wtx);
195     }
196     return false;
197 }
198
199 bool EraseFromWallet(uint256 hash)
200 {
201     CRITICAL_BLOCK(cs_mapWallet)
202     {
203         if (mapWallet.erase(hash))
204             CWalletDB().EraseTx(hash);
205     }
206     return true;
207 }
208
209 void WalletUpdateSpent(const COutPoint& prevout)
210 {
211     // Anytime a signature is successfully verified, it's proof the outpoint is spent.
212     // Update the wallet spent flag if it doesn't know due to wallet.dat being
213     // restored from backup or the user making copies of wallet.dat.
214     CRITICAL_BLOCK(cs_mapWallet)
215     {
216         map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
217         if (mi != mapWallet.end())
218         {
219             CWalletTx& wtx = (*mi).second;
220             if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())
221             {
222                 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
223                 wtx.MarkSpent(prevout.n);
224                 wtx.WriteToDisk();
225                 vWalletUpdated.push_back(prevout.hash);
226             }
227         }
228     }
229 }
230
231
232
233
234
235
236
237
238 //////////////////////////////////////////////////////////////////////////////
239 //
240 // mapOrphanTransactions
241 //
242
243 void AddOrphanTx(const CDataStream& vMsg)
244 {
245     CTransaction tx;
246     CDataStream(vMsg) >> tx;
247     uint256 hash = tx.GetHash();
248     if (mapOrphanTransactions.count(hash))
249         return;
250     CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
251     BOOST_FOREACH(const CTxIn& txin, tx.vin)
252         mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
253 }
254
255 void EraseOrphanTx(uint256 hash)
256 {
257     if (!mapOrphanTransactions.count(hash))
258         return;
259     const CDataStream* pvMsg = mapOrphanTransactions[hash];
260     CTransaction tx;
261     CDataStream(*pvMsg) >> tx;
262     BOOST_FOREACH(const CTxIn& txin, tx.vin)
263     {
264         for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
265              mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
266         {
267             if ((*mi).second == pvMsg)
268                 mapOrphanTransactionsByPrev.erase(mi++);
269             else
270                 mi++;
271         }
272     }
273     delete pvMsg;
274     mapOrphanTransactions.erase(hash);
275 }
276
277
278
279
280
281
282
283
284 //////////////////////////////////////////////////////////////////////////////
285 //
286 // CTransaction and CTxIndex
287 //
288
289 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
290 {
291     SetNull();
292     if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
293         return false;
294     if (!ReadFromDisk(txindexRet.pos))
295         return false;
296     if (prevout.n >= vout.size())
297     {
298         SetNull();
299         return false;
300     }
301     return true;
302 }
303
304 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
305 {
306     CTxIndex txindex;
307     return ReadFromDisk(txdb, prevout, txindex);
308 }
309
310 bool CTransaction::ReadFromDisk(COutPoint prevout)
311 {
312     CTxDB txdb("r");
313     CTxIndex txindex;
314     return ReadFromDisk(txdb, prevout, txindex);
315 }
316
317 bool CTxIn::IsMine() const
318 {
319     CRITICAL_BLOCK(cs_mapWallet)
320     {
321         map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
322         if (mi != mapWallet.end())
323         {
324             const CWalletTx& prev = (*mi).second;
325             if (prevout.n < prev.vout.size())
326                 if (prev.vout[prevout.n].IsMine())
327                     return true;
328         }
329     }
330     return false;
331 }
332
333 int64 CTxIn::GetDebit() const
334 {
335     CRITICAL_BLOCK(cs_mapWallet)
336     {
337         map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
338         if (mi != mapWallet.end())
339         {
340             const CWalletTx& prev = (*mi).second;
341             if (prevout.n < prev.vout.size())
342                 if (prev.vout[prevout.n].IsMine())
343                     return prev.vout[prevout.n].nValue;
344         }
345     }
346     return 0;
347 }
348
349 int64 CWalletTx::GetTxTime() const
350 {
351     if (!fTimeReceivedIsTxTime && hashBlock != 0)
352     {
353         // If we did not receive the transaction directly, we rely on the block's
354         // time to figure out when it happened.  We use the median over a range
355         // of blocks to try to filter out inaccurate block times.
356         map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
357         if (mi != mapBlockIndex.end())
358         {
359             CBlockIndex* pindex = (*mi).second;
360             if (pindex)
361                 return pindex->GetMedianTime();
362         }
363     }
364     return nTimeReceived;
365 }
366
367 int CWalletTx::GetRequestCount() const
368 {
369     // Returns -1 if it wasn't being tracked
370     int nRequests = -1;
371     CRITICAL_BLOCK(cs_mapRequestCount)
372     {
373         if (IsCoinBase())
374         {
375             // Generated block
376             if (hashBlock != 0)
377             {
378                 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
379                 if (mi != mapRequestCount.end())
380                     nRequests = (*mi).second;
381             }
382         }
383         else
384         {
385             // Did anyone request this transaction?
386             map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
387             if (mi != mapRequestCount.end())
388             {
389                 nRequests = (*mi).second;
390
391                 // How about the block it's in?
392                 if (nRequests == 0 && hashBlock != 0)
393                 {
394                     map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
395                     if (mi != mapRequestCount.end())
396                         nRequests = (*mi).second;
397                     else
398                         nRequests = 1; // If it's in someone else's block it must have got out
399                 }
400             }
401         }
402     }
403     return nRequests;
404 }
405
406 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
407                            list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
408 {
409     nGeneratedImmature = nGeneratedMature = nFee = 0;
410     listReceived.clear();
411     listSent.clear();
412     strSentAccount = strFromAccount;
413
414     if (IsCoinBase())
415     {
416         if (GetBlocksToMaturity() > 0)
417             nGeneratedImmature = CTransaction::GetCredit();
418         else
419             nGeneratedMature = GetCredit();
420         return;
421     }
422
423     // Compute fee:
424     int64 nDebit = GetDebit();
425     if (nDebit > 0) // debit>0 means we signed/sent this transaction
426     {
427         int64 nValueOut = GetValueOut();
428         nFee = nDebit - nValueOut;
429     }
430
431     // Sent/received.  Standard client will never generate a send-to-multiple-recipients,
432     // but non-standard clients might (so return a list of address/amount pairs)
433     BOOST_FOREACH(const CTxOut& txout, vout)
434     {
435         string address;
436         uint160 hash160;
437         vector<unsigned char> vchPubKey;
438         if (ExtractHash160(txout.scriptPubKey, hash160))
439             address = Hash160ToAddress(hash160);
440         else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))
441             address = PubKeyToAddress(vchPubKey);
442         else
443         {
444             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
445                    this->GetHash().ToString().c_str());
446             address = " unknown ";
447         }
448
449         // Don't report 'change' txouts
450         if (nDebit > 0 && txout.IsChange())
451             continue;
452
453         if (nDebit > 0)
454             listSent.push_back(make_pair(address, txout.nValue));
455
456         if (txout.IsMine())
457             listReceived.push_back(make_pair(address, txout.nValue));
458     }
459
460 }
461
462 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 
463                                   int64& nSent, int64& nFee) const
464 {
465     nGenerated = nReceived = nSent = nFee = 0;
466
467     int64 allGeneratedImmature, allGeneratedMature, allFee;
468     allGeneratedImmature = allGeneratedMature = allFee = 0;
469     string strSentAccount;
470     list<pair<string, int64> > listReceived;
471     list<pair<string, int64> > listSent;
472     GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
473
474     if (strAccount == "")
475         nGenerated = allGeneratedMature;
476     if (strAccount == strSentAccount)
477     {
478         BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
479             nSent += s.second;
480         nFee = allFee;
481     }
482     CRITICAL_BLOCK(cs_mapAddressBook)
483     {
484         BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
485         {
486             if (mapAddressBook.count(r.first))
487             {
488                 if (mapAddressBook[r.first] == strAccount)
489                 {
490                     nReceived += r.second;
491                 }
492             }
493             else if (strAccount.empty())
494             {
495                 nReceived += r.second;
496             }
497         }
498     }
499 }
500
501
502
503 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
504 {
505     if (fClient)
506     {
507         if (hashBlock == 0)
508             return 0;
509     }
510     else
511     {
512         CBlock blockTmp;
513         if (pblock == NULL)
514         {
515             // Load the block this tx is in
516             CTxIndex txindex;
517             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
518                 return 0;
519             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
520                 return 0;
521             pblock = &blockTmp;
522         }
523
524         // Update the tx's hashBlock
525         hashBlock = pblock->GetHash();
526
527         // Locate the transaction
528         for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
529             if (pblock->vtx[nIndex] == *(CTransaction*)this)
530                 break;
531         if (nIndex == pblock->vtx.size())
532         {
533             vMerkleBranch.clear();
534             nIndex = -1;
535             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
536             return 0;
537         }
538
539         // Fill in merkle branch
540         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
541     }
542
543     // Is the tx in a block that's in the main chain
544     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
545     if (mi == mapBlockIndex.end())
546         return 0;
547     CBlockIndex* pindex = (*mi).second;
548     if (!pindex || !pindex->IsInMainChain())
549         return 0;
550
551     return pindexBest->nHeight - pindex->nHeight + 1;
552 }
553
554
555
556 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
557 {
558     vtxPrev.clear();
559
560     const int COPY_DEPTH = 3;
561     if (SetMerkleBranch() < COPY_DEPTH)
562     {
563         vector<uint256> vWorkQueue;
564         BOOST_FOREACH(const CTxIn& txin, vin)
565             vWorkQueue.push_back(txin.prevout.hash);
566
567         // This critsect is OK because txdb is already open
568         CRITICAL_BLOCK(cs_mapWallet)
569         {
570             map<uint256, const CMerkleTx*> mapWalletPrev;
571             set<uint256> setAlreadyDone;
572             for (int i = 0; i < vWorkQueue.size(); i++)
573             {
574                 uint256 hash = vWorkQueue[i];
575                 if (setAlreadyDone.count(hash))
576                     continue;
577                 setAlreadyDone.insert(hash);
578
579                 CMerkleTx tx;
580                 if (mapWallet.count(hash))
581                 {
582                     tx = mapWallet[hash];
583                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
584                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
585                 }
586                 else if (mapWalletPrev.count(hash))
587                 {
588                     tx = *mapWalletPrev[hash];
589                 }
590                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
591                 {
592                     ;
593                 }
594                 else
595                 {
596                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
597                     continue;
598                 }
599
600                 int nDepth = tx.SetMerkleBranch();
601                 vtxPrev.push_back(tx);
602
603                 if (nDepth < COPY_DEPTH)
604                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
605                         vWorkQueue.push_back(txin.prevout.hash);
606             }
607         }
608     }
609
610     reverse(vtxPrev.begin(), vtxPrev.end());
611 }
612
613
614
615
616
617
618
619
620
621
622
623 bool CTransaction::CheckTransaction() const
624 {
625     // Basic checks that don't depend on any context
626     if (vin.empty() || vout.empty())
627         return error("CTransaction::CheckTransaction() : vin or vout empty");
628
629     // Size limits
630     if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
631         return error("CTransaction::CheckTransaction() : size limits failed");
632
633     // Check for negative or overflow output values
634     int64 nValueOut = 0;
635     BOOST_FOREACH(const CTxOut& txout, vout)
636     {
637         if (txout.nValue < 0)
638             return error("CTransaction::CheckTransaction() : txout.nValue negative");
639         if (txout.nValue > MAX_MONEY)
640             return error("CTransaction::CheckTransaction() : txout.nValue too high");
641         nValueOut += txout.nValue;
642         if (!MoneyRange(nValueOut))
643             return error("CTransaction::CheckTransaction() : txout total out of range");
644     }
645
646     if (IsCoinBase())
647     {
648         if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
649             return error("CTransaction::CheckTransaction() : coinbase script size");
650     }
651     else
652     {
653         BOOST_FOREACH(const CTxIn& txin, vin)
654             if (txin.prevout.IsNull())
655                 return error("CTransaction::CheckTransaction() : prevout is null");
656     }
657
658     return true;
659 }
660
661 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
662 {
663     if (pfMissingInputs)
664         *pfMissingInputs = false;
665
666     if (!CheckTransaction())
667         return error("AcceptToMemoryPool() : CheckTransaction failed");
668
669     // Coinbase is only valid in a block, not as a loose transaction
670     if (IsCoinBase())
671         return error("AcceptToMemoryPool() : coinbase as individual tx");
672
673     // To help v0.1.5 clients who would see it as a negative number
674     if ((int64)nLockTime > INT_MAX)
675         return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
676
677     // Safety limits
678     unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
679     // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
680     // attacks disallow transactions with more than one SigOp per 34 bytes.
681     // 34 bytes because a TxOut is:
682     //   20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
683     if (GetSigOpCount() > nSize / 34 || nSize < 100)
684         return error("AcceptToMemoryPool() : nonstandard transaction");
685
686     // Rather not work on nonstandard transactions (unless -testnet)
687     if (!fTestNet && !IsStandard())
688         return error("AcceptToMemoryPool() : nonstandard transaction type");
689
690     // Do we already have it?
691     uint256 hash = GetHash();
692     CRITICAL_BLOCK(cs_mapTransactions)
693         if (mapTransactions.count(hash))
694             return false;
695     if (fCheckInputs)
696         if (txdb.ContainsTx(hash))
697             return false;
698
699     // Check for conflicts with in-memory transactions
700     CTransaction* ptxOld = NULL;
701     for (int i = 0; i < vin.size(); i++)
702     {
703         COutPoint outpoint = vin[i].prevout;
704         if (mapNextTx.count(outpoint))
705         {
706             // Disable replacement feature for now
707             return false;
708
709             // Allow replacing with a newer version of the same transaction
710             if (i != 0)
711                 return false;
712             ptxOld = mapNextTx[outpoint].ptx;
713             if (ptxOld->IsFinal())
714                 return false;
715             if (!IsNewerThan(*ptxOld))
716                 return false;
717             for (int i = 0; i < vin.size(); i++)
718             {
719                 COutPoint outpoint = vin[i].prevout;
720                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
721                     return false;
722             }
723             break;
724         }
725     }
726
727     if (fCheckInputs)
728     {
729         // Check against previous transactions
730         map<uint256, CTxIndex> mapUnused;
731         int64 nFees = 0;
732         if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
733         {
734             if (pfMissingInputs)
735                 *pfMissingInputs = true;
736             return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
737         }
738
739         // Don't accept it if it can't get into a block
740         if (nFees < GetMinFee(1000, true, true))
741             return error("AcceptToMemoryPool() : not enough fees");
742
743         // Continuously rate-limit free transactions
744         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
745         // be annoying or make other's transactions take longer to confirm.
746         if (nFees < MIN_RELAY_TX_FEE)
747         {
748             static CCriticalSection cs;
749             static double dFreeCount;
750             static int64 nLastTime;
751             int64 nNow = GetTime();
752
753             CRITICAL_BLOCK(cs)
754             {
755                 // Use an exponentially decaying ~10-minute window:
756                 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
757                 nLastTime = nNow;
758                 // -limitfreerelay unit is thousand-bytes-per-minute
759                 // At default rate it would take over a month to fill 1GB
760                 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())
761                     return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
762                 if (fDebug)
763                     printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
764                 dFreeCount += nSize;
765             }
766         }
767     }
768
769     // Store transaction in memory
770     CRITICAL_BLOCK(cs_mapTransactions)
771     {
772         if (ptxOld)
773         {
774             printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
775             ptxOld->RemoveFromMemoryPool();
776         }
777         AddToMemoryPoolUnchecked();
778     }
779
780     ///// are we sure this is ok when loading transactions or restoring block txes
781     // If updated, erase old tx from wallet
782     if (ptxOld)
783         EraseFromWallet(ptxOld->GetHash());
784
785     printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
786     return true;
787 }
788
789
790 bool CTransaction::AddToMemoryPoolUnchecked()
791 {
792     // Add to memory pool without checking anything.  Don't call this directly,
793     // call AcceptToMemoryPool to properly check the transaction first.
794     CRITICAL_BLOCK(cs_mapTransactions)
795     {
796         uint256 hash = GetHash();
797         mapTransactions[hash] = *this;
798         for (int i = 0; i < vin.size(); i++)
799             mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
800         nTransactionsUpdated++;
801     }
802     return true;
803 }
804
805
806 bool CTransaction::RemoveFromMemoryPool()
807 {
808     // Remove transaction from memory pool
809     CRITICAL_BLOCK(cs_mapTransactions)
810     {
811         BOOST_FOREACH(const CTxIn& txin, vin)
812             mapNextTx.erase(txin.prevout);
813         mapTransactions.erase(GetHash());
814         nTransactionsUpdated++;
815     }
816     return true;
817 }
818
819
820
821
822
823
824 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
825 {
826     if (hashBlock == 0 || nIndex == -1)
827         return 0;
828
829     // Find the block it claims to be in
830     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
831     if (mi == mapBlockIndex.end())
832         return 0;
833     CBlockIndex* pindex = (*mi).second;
834     if (!pindex || !pindex->IsInMainChain())
835         return 0;
836
837     // Make sure the merkle branch connects to this block
838     if (!fMerkleVerified)
839     {
840         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
841             return 0;
842         fMerkleVerified = true;
843     }
844
845     nHeightRet = pindex->nHeight;
846     return pindexBest->nHeight - pindex->nHeight + 1;
847 }
848
849
850 int CMerkleTx::GetBlocksToMaturity() const
851 {
852     if (!IsCoinBase())
853         return 0;
854     return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
855 }
856
857
858 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
859 {
860     if (fClient)
861     {
862         if (!IsInMainChain() && !ClientConnectInputs())
863             return false;
864         return CTransaction::AcceptToMemoryPool(txdb, false);
865     }
866     else
867     {
868         return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
869     }
870 }
871
872
873
874 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
875 {
876     CRITICAL_BLOCK(cs_mapTransactions)
877     {
878         // Add previous supporting transactions first
879         BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
880         {
881             if (!tx.IsCoinBase())
882             {
883                 uint256 hash = tx.GetHash();
884                 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
885                     tx.AcceptToMemoryPool(txdb, fCheckInputs);
886             }
887         }
888         return AcceptToMemoryPool(txdb, fCheckInputs);
889     }
890     return false;
891 }
892
893 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
894 {
895     int ret = 0;
896
897     CBlockIndex* pindex = pindexStart;
898     CRITICAL_BLOCK(cs_mapWallet)
899     {
900         while (pindex)
901         {
902             CBlock block;
903             block.ReadFromDisk(pindex, true);
904             BOOST_FOREACH(CTransaction& tx, block.vtx)
905             {
906                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
907                     ret++;
908             }
909             pindex = pindex->pnext;
910         }
911     }
912     return ret;
913 }
914
915 void ReacceptWalletTransactions()
916 {
917     CTxDB txdb("r");
918     bool fRepeat = true;
919     while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
920     {
921         fRepeat = false;
922         vector<CDiskTxPos> vMissingTx;
923         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
924         {
925             CWalletTx& wtx = item.second;
926             if (wtx.IsCoinBase() && wtx.IsSpent(0))
927                 continue;
928
929             CTxIndex txindex;
930             bool fUpdated = false;
931             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
932             {
933                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
934                 if (txindex.vSpent.size() != wtx.vout.size())
935                 {
936                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
937                     continue;
938                 }
939                 for (int i = 0; i < txindex.vSpent.size(); i++)
940                 {
941                     if (wtx.IsSpent(i))
942                         continue;
943                     if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
944                     {
945                         wtx.MarkSpent(i);
946                         fUpdated = true;
947                         vMissingTx.push_back(txindex.vSpent[i]);
948                     }
949                 }
950                 if (fUpdated)
951                 {
952                     printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
953                     wtx.MarkDirty();
954                     wtx.WriteToDisk();
955                 }
956             }
957             else
958             {
959                 // Reaccept any txes of ours that aren't already in a block
960                 if (!wtx.IsCoinBase())
961                     wtx.AcceptWalletTransaction(txdb, false);
962             }
963         }
964         if (!vMissingTx.empty())
965         {
966             // TODO: optimize this to scan just part of the block chain?
967             if (ScanForWalletTransactions(pindexGenesisBlock))
968                 fRepeat = true;  // Found missing transactions: re-do Reaccept.
969         }
970     }
971 }
972
973
974 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
975 {
976     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
977     {
978         if (!tx.IsCoinBase())
979         {
980             uint256 hash = tx.GetHash();
981             if (!txdb.ContainsTx(hash))
982                 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
983         }
984     }
985     if (!IsCoinBase())
986     {
987         uint256 hash = GetHash();
988         if (!txdb.ContainsTx(hash))
989         {
990             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
991             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
992         }
993     }
994 }
995
996 void ResendWalletTransactions()
997 {
998     // Do this infrequently and randomly to avoid giving away
999     // that these are our transactions.
1000     static int64 nNextTime;
1001     if (GetTime() < nNextTime)
1002         return;
1003     bool fFirst = (nNextTime == 0);
1004     nNextTime = GetTime() + GetRand(30 * 60);
1005     if (fFirst)
1006         return;
1007
1008     // Only do it if there's been a new block since last time
1009     static int64 nLastTime;
1010     if (nTimeBestReceived < nLastTime)
1011         return;
1012     nLastTime = GetTime();
1013
1014     // Rebroadcast any of our txes that aren't in a block yet
1015     printf("ResendWalletTransactions()\n");
1016     CTxDB txdb("r");
1017     CRITICAL_BLOCK(cs_mapWallet)
1018     {
1019         // Sort them in chronological order
1020         multimap<unsigned int, CWalletTx*> mapSorted;
1021         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1022         {
1023             CWalletTx& wtx = item.second;
1024             // Don't rebroadcast until it's had plenty of time that
1025             // it should have gotten in already by now.
1026             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1027                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1028         }
1029         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1030         {
1031             CWalletTx& wtx = *item.second;
1032             wtx.RelayWalletTransaction(txdb);
1033         }
1034     }
1035 }
1036
1037 int CTxIndex::GetDepthInMainChain() const
1038 {
1039     // Read block header
1040     CBlock block;
1041     if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
1042         return 0;
1043     // Find the block in the index
1044     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
1045     if (mi == mapBlockIndex.end())
1046         return 0;
1047     CBlockIndex* pindex = (*mi).second;
1048     if (!pindex || !pindex->IsInMainChain())
1049         return 0;
1050     return 1 + nBestHeight - pindex->nHeight;
1051 }
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062 //////////////////////////////////////////////////////////////////////////////
1063 //
1064 // CBlock and CBlockIndex
1065 //
1066
1067 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1068 {
1069     if (!fReadTransactions)
1070     {
1071         *this = pindex->GetBlockHeader();
1072         return true;
1073     }
1074     if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1075         return false;
1076     if (GetHash() != pindex->GetBlockHash())
1077         return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1078     return true;
1079 }
1080
1081 uint256 GetOrphanRoot(const CBlock* pblock)
1082 {
1083     // Work back to the first block in the orphan chain
1084     while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1085         pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1086     return pblock->GetHash();
1087 }
1088
1089 int64 GetBlockValue(int nHeight, int64 nFees)
1090 {
1091     int64 nSubsidy = 50 * COIN;
1092
1093     // Subsidy is cut in half every 4 years
1094     nSubsidy >>= (nHeight / 210000);
1095
1096     return nSubsidy + nFees;
1097 }
1098
1099 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1100 {
1101     const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1102     const int64 nTargetSpacing = 10 * 60;
1103     const int64 nInterval = nTargetTimespan / nTargetSpacing;
1104
1105     // Genesis block
1106     if (pindexLast == NULL)
1107         return bnProofOfWorkLimit.GetCompact();
1108
1109     // Only change once per interval
1110     if ((pindexLast->nHeight+1) % nInterval != 0)
1111         return pindexLast->nBits;
1112
1113     // Go back by what we want to be 14 days worth of blocks
1114     const CBlockIndex* pindexFirst = pindexLast;
1115     for (int i = 0; pindexFirst && i < nInterval-1; i++)
1116         pindexFirst = pindexFirst->pprev;
1117     assert(pindexFirst);
1118
1119     // Limit adjustment step
1120     int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1121     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
1122     if (nActualTimespan < nTargetTimespan/4)
1123         nActualTimespan = nTargetTimespan/4;
1124     if (nActualTimespan > nTargetTimespan*4)
1125         nActualTimespan = nTargetTimespan*4;
1126
1127     // Retarget
1128     CBigNum bnNew;
1129     bnNew.SetCompact(pindexLast->nBits);
1130     bnNew *= nActualTimespan;
1131     bnNew /= nTargetTimespan;
1132
1133     if (bnNew > bnProofOfWorkLimit)
1134         bnNew = bnProofOfWorkLimit;
1135
1136     /// debug print
1137     printf("GetNextWorkRequired RETARGET\n");
1138     printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1139     printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1140     printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1141
1142     return bnNew.GetCompact();
1143 }
1144
1145 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1146 {
1147     CBigNum bnTarget;
1148     bnTarget.SetCompact(nBits);
1149
1150     // Check range
1151     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1152         return error("CheckProofOfWork() : nBits below minimum work");
1153
1154     // Check proof of work matches claimed amount
1155     if (hash > bnTarget.getuint256())
1156         return error("CheckProofOfWork() : hash doesn't match nBits");
1157
1158     return true;
1159 }
1160
1161 // Return conservative estimate of total number of blocks, 0 if unknown
1162 int GetTotalBlocksEstimate()
1163 {
1164     if(fTestNet)
1165     {
1166         return 0;
1167     }
1168     else
1169     {
1170         return nTotalBlocksEstimate;
1171     }
1172 }
1173
1174 bool IsInitialBlockDownload()
1175 {
1176     if (pindexBest == NULL || nBestHeight < (GetTotalBlocksEstimate()-nInitialBlockThreshold))
1177         return true;
1178     static int64 nLastUpdate;
1179     static CBlockIndex* pindexLastBest;
1180     if (pindexBest != pindexLastBest)
1181     {
1182         pindexLastBest = pindexBest;
1183         nLastUpdate = GetTime();
1184     }
1185     return (GetTime() - nLastUpdate < 10 &&
1186             pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1187 }
1188
1189 void InvalidChainFound(CBlockIndex* pindexNew)
1190 {
1191     if (pindexNew->bnChainWork > bnBestInvalidWork)
1192     {
1193         bnBestInvalidWork = pindexNew->bnChainWork;
1194         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1195         MainFrameRepaint();
1196     }
1197     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());
1198     printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1199     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1200         printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
1201 }
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1214 {
1215     // Relinquish previous transactions' spent pointers
1216     if (!IsCoinBase())
1217     {
1218         BOOST_FOREACH(const CTxIn& txin, vin)
1219         {
1220             COutPoint prevout = txin.prevout;
1221
1222             // Get prev txindex from disk
1223             CTxIndex txindex;
1224             if (!txdb.ReadTxIndex(prevout.hash, txindex))
1225                 return error("DisconnectInputs() : ReadTxIndex failed");
1226
1227             if (prevout.n >= txindex.vSpent.size())
1228                 return error("DisconnectInputs() : prevout.n out of range");
1229
1230             // Mark outpoint as not spent
1231             txindex.vSpent[prevout.n].SetNull();
1232
1233             // Write back
1234             if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1235                 return error("DisconnectInputs() : UpdateTxIndex failed");
1236         }
1237     }
1238
1239     // Remove transaction from index
1240     if (!txdb.EraseTxIndex(*this))
1241         return error("DisconnectInputs() : EraseTxPos failed");
1242
1243     return true;
1244 }
1245
1246
1247 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1248                                  CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1249 {
1250     // Take over previous transactions' spent pointers
1251     if (!IsCoinBase())
1252     {
1253         int64 nValueIn = 0;
1254         for (int i = 0; i < vin.size(); i++)
1255         {
1256             COutPoint prevout = vin[i].prevout;
1257
1258             // Read txindex
1259             CTxIndex txindex;
1260             bool fFound = true;
1261             if (fMiner && mapTestPool.count(prevout.hash))
1262             {
1263                 // Get txindex from current proposed changes
1264                 txindex = mapTestPool[prevout.hash];
1265             }
1266             else
1267             {
1268                 // Read txindex from txdb
1269                 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1270             }
1271             if (!fFound && (fBlock || fMiner))
1272                 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());
1273
1274             // Read txPrev
1275             CTransaction txPrev;
1276             if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1277             {
1278                 // Get prev tx from single transactions in memory
1279                 CRITICAL_BLOCK(cs_mapTransactions)
1280                 {
1281                     if (!mapTransactions.count(prevout.hash))
1282                         return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
1283                     txPrev = mapTransactions[prevout.hash];
1284                 }
1285                 if (!fFound)
1286                     txindex.vSpent.resize(txPrev.vout.size());
1287             }
1288             else
1289             {
1290                 // Get prev tx from disk
1291                 if (!txPrev.ReadFromDisk(txindex.pos))
1292                     return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
1293             }
1294
1295             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1296                 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());
1297
1298             // If prev is coinbase, check that it's matured
1299             if (txPrev.IsCoinBase())
1300                 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1301                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1302                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1303
1304             // Verify signature
1305             if (!VerifySignature(txPrev, *this, i))
1306                 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1307
1308             // Check for conflicts
1309             if (!txindex.vSpent[prevout.n].IsNull())
1310                 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());
1311
1312             // Check for negative or overflow input values
1313             nValueIn += txPrev.vout[prevout.n].nValue;
1314             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1315                 return error("ConnectInputs() : txin values out of range");
1316
1317             // Mark outpoints as spent
1318             txindex.vSpent[prevout.n] = posThisTx;
1319
1320             // Write back
1321             if (fBlock)
1322             {
1323                 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1324                     return error("ConnectInputs() : UpdateTxIndex failed");
1325             }
1326             else if (fMiner)
1327             {
1328                 mapTestPool[prevout.hash] = txindex;
1329             }
1330         }
1331
1332         if (nValueIn < GetValueOut())
1333             return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1334
1335         // Tally transaction fees
1336         int64 nTxFee = nValueIn - GetValueOut();
1337         if (nTxFee < 0)
1338             return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1339         if (nTxFee < nMinFee)
1340             return false;
1341         nFees += nTxFee;
1342         if (!MoneyRange(nFees))
1343             return error("ConnectInputs() : nFees out of range");
1344     }
1345
1346     if (fBlock)
1347     {
1348         // Add transaction to disk index
1349         if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1350             return error("ConnectInputs() : AddTxPos failed");
1351     }
1352     else if (fMiner)
1353     {
1354         // Add transaction to test pool
1355         mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1356     }
1357
1358     return true;
1359 }
1360
1361
1362 bool CTransaction::ClientConnectInputs()
1363 {
1364     if (IsCoinBase())
1365         return false;
1366
1367     // Take over previous transactions' spent pointers
1368     CRITICAL_BLOCK(cs_mapTransactions)
1369     {
1370         int64 nValueIn = 0;
1371         for (int i = 0; i < vin.size(); i++)
1372         {
1373             // Get prev tx from single transactions in memory
1374             COutPoint prevout = vin[i].prevout;
1375             if (!mapTransactions.count(prevout.hash))
1376                 return false;
1377             CTransaction& txPrev = mapTransactions[prevout.hash];
1378
1379             if (prevout.n >= txPrev.vout.size())
1380                 return false;
1381
1382             // Verify signature
1383             if (!VerifySignature(txPrev, *this, i))
1384                 return error("ConnectInputs() : VerifySignature failed");
1385
1386             ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1387             ///// this has to go away now that posNext is gone
1388             // // Check for conflicts
1389             // if (!txPrev.vout[prevout.n].posNext.IsNull())
1390             //     return error("ConnectInputs() : prev tx already used");
1391             //
1392             // // Flag outpoints as used
1393             // txPrev.vout[prevout.n].posNext = posThisTx;
1394
1395             nValueIn += txPrev.vout[prevout.n].nValue;
1396
1397             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1398                 return error("ClientConnectInputs() : txin values out of range");
1399         }
1400         if (GetValueOut() > nValueIn)
1401             return false;
1402     }
1403
1404     return true;
1405 }
1406
1407
1408
1409
1410 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1411 {
1412     // Disconnect in reverse order
1413     for (int i = vtx.size()-1; i >= 0; i--)
1414         if (!vtx[i].DisconnectInputs(txdb))
1415             return false;
1416
1417     // Update block index on disk without changing it in memory.
1418     // The memory index structure will be changed after the db commits.
1419     if (pindex->pprev)
1420     {
1421         CDiskBlockIndex blockindexPrev(pindex->pprev);
1422         blockindexPrev.hashNext = 0;
1423         if (!txdb.WriteBlockIndex(blockindexPrev))
1424             return error("DisconnectBlock() : WriteBlockIndex failed");
1425     }
1426
1427     return true;
1428 }
1429
1430 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1431 {
1432     // Check it again in case a previous version let a bad block in
1433     if (!CheckBlock())
1434         return false;
1435
1436     //// issue here: it doesn't know the version
1437     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1438
1439     map<uint256, CTxIndex> mapUnused;
1440     int64 nFees = 0;
1441     BOOST_FOREACH(CTransaction& tx, vtx)
1442     {
1443         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1444         nTxPos += ::GetSerializeSize(tx, SER_DISK);
1445
1446         if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1447             return false;
1448     }
1449
1450     if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1451         return false;
1452
1453     // Update block index on disk without changing it in memory.
1454     // The memory index structure will be changed after the db commits.
1455     if (pindex->pprev)
1456     {
1457         CDiskBlockIndex blockindexPrev(pindex->pprev);
1458         blockindexPrev.hashNext = pindex->GetBlockHash();
1459         if (!txdb.WriteBlockIndex(blockindexPrev))
1460             return error("ConnectBlock() : WriteBlockIndex failed");
1461     }
1462
1463     // Watch for transactions paying to me
1464     BOOST_FOREACH(CTransaction& tx, vtx)
1465         AddToWalletIfInvolvingMe(tx, this, true);
1466
1467     return true;
1468 }
1469
1470 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1471 {
1472     printf("REORGANIZE\n");
1473
1474     // Find the fork
1475     CBlockIndex* pfork = pindexBest;
1476     CBlockIndex* plonger = pindexNew;
1477     while (pfork != plonger)
1478     {
1479         while (plonger->nHeight > pfork->nHeight)
1480             if (!(plonger = plonger->pprev))
1481                 return error("Reorganize() : plonger->pprev is null");
1482         if (pfork == plonger)
1483             break;
1484         if (!(pfork = pfork->pprev))
1485             return error("Reorganize() : pfork->pprev is null");
1486     }
1487
1488     // List of what to disconnect
1489     vector<CBlockIndex*> vDisconnect;
1490     for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1491         vDisconnect.push_back(pindex);
1492
1493     // List of what to connect
1494     vector<CBlockIndex*> vConnect;
1495     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1496         vConnect.push_back(pindex);
1497     reverse(vConnect.begin(), vConnect.end());
1498
1499     // Disconnect shorter branch
1500     vector<CTransaction> vResurrect;
1501     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1502     {
1503         CBlock block;
1504         if (!block.ReadFromDisk(pindex))
1505             return error("Reorganize() : ReadFromDisk for disconnect failed");
1506         if (!block.DisconnectBlock(txdb, pindex))
1507             return error("Reorganize() : DisconnectBlock failed");
1508
1509         // Queue memory transactions to resurrect
1510         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1511             if (!tx.IsCoinBase())
1512                 vResurrect.push_back(tx);
1513     }
1514
1515     // Connect longer branch
1516     vector<CTransaction> vDelete;
1517     for (int i = 0; i < vConnect.size(); i++)
1518     {
1519         CBlockIndex* pindex = vConnect[i];
1520         CBlock block;
1521         if (!block.ReadFromDisk(pindex))
1522             return error("Reorganize() : ReadFromDisk for connect failed");
1523         if (!block.ConnectBlock(txdb, pindex))
1524         {
1525             // Invalid block
1526             txdb.TxnAbort();
1527             return error("Reorganize() : ConnectBlock failed");
1528         }
1529
1530         // Queue memory transactions to delete
1531         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1532             vDelete.push_back(tx);
1533     }
1534     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1535         return error("Reorganize() : WriteHashBestChain failed");
1536
1537     // Make sure it's successfully written to disk before changing memory structure
1538     if (!txdb.TxnCommit())
1539         return error("Reorganize() : TxnCommit failed");
1540
1541     // Disconnect shorter branch
1542     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1543         if (pindex->pprev)
1544             pindex->pprev->pnext = NULL;
1545
1546     // Connect longer branch
1547     BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1548         if (pindex->pprev)
1549             pindex->pprev->pnext = pindex;
1550
1551     // Resurrect memory transactions that were in the disconnected branch
1552     BOOST_FOREACH(CTransaction& tx, vResurrect)
1553         tx.AcceptToMemoryPool(txdb, false);
1554
1555     // Delete redundant memory transactions that are in the connected branch
1556     BOOST_FOREACH(CTransaction& tx, vDelete)
1557         tx.RemoveFromMemoryPool();
1558
1559     return true;
1560 }
1561
1562
1563 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1564 {
1565     uint256 hash = GetHash();
1566
1567     txdb.TxnBegin();
1568     if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1569     {
1570         txdb.WriteHashBestChain(hash);
1571         if (!txdb.TxnCommit())
1572             return error("SetBestChain() : TxnCommit failed");
1573         pindexGenesisBlock = pindexNew;
1574     }
1575     else if (hashPrevBlock == hashBestChain)
1576     {
1577         // Adding to current best branch
1578         if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1579         {
1580             txdb.TxnAbort();
1581             InvalidChainFound(pindexNew);
1582             return error("SetBestChain() : ConnectBlock failed");
1583         }
1584         if (!txdb.TxnCommit())
1585             return error("SetBestChain() : TxnCommit failed");
1586
1587         // Add to current best branch
1588         pindexNew->pprev->pnext = pindexNew;
1589
1590         // Delete redundant memory transactions
1591         BOOST_FOREACH(CTransaction& tx, vtx)
1592             tx.RemoveFromMemoryPool();
1593     }
1594     else
1595     {
1596         // New best branch
1597         if (!Reorganize(txdb, pindexNew))
1598         {
1599             txdb.TxnAbort();
1600             InvalidChainFound(pindexNew);
1601             return error("SetBestChain() : Reorganize failed");
1602         }
1603     }
1604
1605     // Update best block in wallet (so we can detect restored wallets)
1606     if (!IsInitialBlockDownload())
1607     {
1608         CWalletDB walletdb;
1609         const CBlockLocator locator(pindexNew);
1610         if (!walletdb.WriteBestBlock(locator))
1611             return error("SetBestChain() : WriteWalletBest failed");
1612     }
1613
1614     // New best block
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());
1622
1623     return true;
1624 }
1625
1626
1627 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1628 {
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());
1633
1634     // Construct new block index object
1635     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1636     if (!pindexNew)
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())
1642     {
1643         pindexNew->pprev = (*miPrev).second;
1644         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1645     }
1646     pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1647
1648     CTxDB txdb;
1649     txdb.TxnBegin();
1650     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1651     if (!txdb.TxnCommit())
1652         return false;
1653
1654     // New best
1655     if (pindexNew->bnChainWork > bnBestChainWork)
1656         if (!SetBestChain(txdb, pindexNew))
1657             return false;
1658
1659     txdb.Close();
1660
1661     if (pindexNew == pindexBest)
1662     {
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();
1668     }
1669
1670     MainFrameRepaint();
1671     return true;
1672 }
1673
1674
1675
1676
1677 bool CBlock::CheckBlock() const
1678 {
1679     // These are checks that are independent of context
1680     // that can be verified before saving an orphan block.
1681
1682     // Size limits
1683     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1684         return error("CheckBlock() : size limits failed");
1685
1686     // Check proof of work matches claimed amount
1687     if (!CheckProofOfWork(GetHash(), nBits))
1688         return error("CheckBlock() : proof of work failed");
1689
1690     // Check timestamp
1691     if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1692         return error("CheckBlock() : block timestamp too far in the future");
1693
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");
1700
1701     // Check transactions
1702     BOOST_FOREACH(const CTransaction& tx, vtx)
1703         if (!tx.CheckTransaction())
1704             return error("CheckBlock() : CheckTransaction failed");
1705
1706     // Check that it's not full of nonstandard transactions
1707     if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1708         return error("CheckBlock() : too many nonstandard transactions");
1709
1710     // Check merkleroot
1711     if (hashMerkleRoot != BuildMerkleTree())
1712         return error("CheckBlock() : hashMerkleRoot mismatch");
1713
1714     return true;
1715 }
1716
1717 bool CBlock::AcceptBlock()
1718 {
1719     // Check for duplicate
1720     uint256 hash = GetHash();
1721     if (mapBlockIndex.count(hash))
1722         return error("AcceptBlock() : block already in mapBlockIndex");
1723
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;
1730
1731     // Check proof of work
1732     if (nBits != GetNextWorkRequired(pindexPrev))
1733         return error("AcceptBlock() : incorrect proof of work");
1734
1735     // Check timestamp against prev
1736     if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1737         return error("AcceptBlock() : block's timestamp is too early");
1738
1739     // Check that all transactions are finalized
1740     BOOST_FOREACH(const CTransaction& tx, vtx)
1741         if (!tx.IsFinal(nHeight, GetBlockTime()))
1742             return error("AcceptBlock() : contains a non-final transaction");
1743
1744     // Check that the block chain matches the known block chain up to a checkpoint
1745     if (!fTestNet)
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);
1754
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");
1764
1765     // Relay inventory, but don't relay old inventory during initial block download
1766     if (hashBestChain == hash)
1767         CRITICAL_BLOCK(cs_vNodes)
1768             BOOST_FOREACH(CNode* pnode, vNodes)
1769                 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
1770                     pnode->PushInventory(CInv(MSG_BLOCK, hash));
1771
1772     return true;
1773 }
1774
1775 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1776 {
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());
1783
1784     // Preliminary checks
1785     if (!pblock->CheckBlock())
1786         return error("ProcessBlock() : CheckBlock FAILED");
1787
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))
1790     {
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));
1795
1796         // Ask this guy to fill in what we're missing
1797         if (pfrom)
1798             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1799         return true;
1800     }
1801
1802     // Store to disk
1803     if (!pblock->AcceptBlock())
1804         return error("ProcessBlock() : AcceptBlock FAILED");
1805
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++)
1810     {
1811         uint256 hashPrev = vWorkQueue[i];
1812         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1813              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1814              ++mi)
1815         {
1816             CBlock* pblockOrphan = (*mi).second;
1817             if (pblockOrphan->AcceptBlock())
1818                 vWorkQueue.push_back(pblockOrphan->GetHash());
1819             mapOrphanBlocks.erase(pblockOrphan->GetHash());
1820             delete pblockOrphan;
1821         }
1822         mapOrphanBlocksByPrev.erase(hashPrev);
1823     }
1824
1825     printf("ProcessBlock: ACCEPTED\n");
1826     return true;
1827 }
1828
1829
1830
1831
1832
1833
1834
1835
1836 template<typename Stream>
1837 bool ScanMessageStart(Stream& s)
1838 {
1839     // Scan ahead to the next pchMessageStart, which should normally be immediately
1840     // at the file pointer.  Leaves file pointer at end of pchMessageStart.
1841     s.clear(0);
1842     short prevmask = s.exceptions(0);
1843     const char* p = BEGIN(pchMessageStart);
1844     try
1845     {
1846         loop
1847         {
1848             char c;
1849             s.read(&c, 1);
1850             if (s.fail())
1851             {
1852                 s.clear(0);
1853                 s.exceptions(prevmask);
1854                 return false;
1855             }
1856             if (*p != c)
1857                 p = BEGIN(pchMessageStart);
1858             if (*p == c)
1859             {
1860                 if (++p == END(pchMessageStart))
1861                 {
1862                     s.clear(0);
1863                     s.exceptions(prevmask);
1864                     return true;
1865                 }
1866             }
1867         }
1868     }
1869     catch (...)
1870     {
1871         s.clear(0);
1872         s.exceptions(prevmask);
1873         return false;
1874     }
1875 }
1876
1877 bool CheckDiskSpace(uint64 nAdditionalBytes)
1878 {
1879     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1880
1881     // Check for 15MB because database could create another 10MB log file at any time
1882     if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1883     {
1884         fShutdown = true;
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);
1890         return false;
1891     }
1892     return true;
1893 }
1894
1895 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1896 {
1897     if (nFile == -1)
1898         return NULL;
1899     FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1900     if (!file)
1901         return NULL;
1902     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1903     {
1904         if (fseek(file, nBlockPos, SEEK_SET) != 0)
1905         {
1906             fclose(file);
1907             return NULL;
1908         }
1909     }
1910     return file;
1911 }
1912
1913 static unsigned int nCurrentBlockFile = 1;
1914
1915 FILE* AppendBlockFile(unsigned int& nFileRet)
1916 {
1917     nFileRet = 0;
1918     loop
1919     {
1920         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1921         if (!file)
1922             return NULL;
1923         if (fseek(file, 0, SEEK_END) != 0)
1924             return NULL;
1925         // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1926         if (ftell(file) < 0x7F000000 - MAX_SIZE)
1927         {
1928             nFileRet = nCurrentBlockFile;
1929             return file;
1930         }
1931         fclose(file);
1932         nCurrentBlockFile++;
1933     }
1934 }
1935
1936 bool LoadBlockIndex(bool fAllowNew)
1937 {
1938     if (fTestNet)
1939     {
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;
1946     }
1947
1948     //
1949     // Load block index
1950     //
1951     CTxDB txdb("cr");
1952     if (!txdb.LoadBlockIndex())
1953         return false;
1954     txdb.Close();
1955
1956     //
1957     // Init with genesis block
1958     //
1959     if (mapBlockIndex.empty())
1960     {
1961         if (!fAllowNew)
1962             return false;
1963
1964         // Genesis Block:
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
1970
1971         // Genesis block
1972         const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1973         CTransaction txNew;
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;
1979         CBlock block;
1980         block.vtx.push_back(txNew);
1981         block.hashPrevBlock = 0;
1982         block.hashMerkleRoot = block.BuildMerkleTree();
1983         block.nVersion = 1;
1984         block.nTime    = 1231006505;
1985         block.nBits    = 0x1d00ffff;
1986         block.nNonce   = 2083236893;
1987
1988         if (fTestNet)
1989         {
1990             block.nTime    = 1296688602;
1991             block.nBits    = 0x1d07fff8;
1992             block.nNonce   = 384568319;
1993         }
1994
1995         //// debug print
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"));
2000         block.print();
2001         assert(block.GetHash() == hashGenesisBlock);
2002
2003         // Start new block file
2004         unsigned int nFile;
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");
2010     }
2011
2012     return true;
2013 }
2014
2015
2016
2017 void PrintBlockTree()
2018 {
2019     // precompute tree structure
2020     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2021     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2022     {
2023         CBlockIndex* pindex = (*mi).second;
2024         mapNext[pindex->pprev].push_back(pindex);
2025         // test
2026         //while (rand() % 3 == 0)
2027         //    mapNext[pindex->pprev].push_back(pindex);
2028     }
2029
2030     vector<pair<int, CBlockIndex*> > vStack;
2031     vStack.push_back(make_pair(0, pindexGenesisBlock));
2032
2033     int nPrevCol = 0;
2034     while (!vStack.empty())
2035     {
2036         int nCol = vStack.back().first;
2037         CBlockIndex* pindex = vStack.back().second;
2038         vStack.pop_back();
2039
2040         // print split or gap
2041         if (nCol > nPrevCol)
2042         {
2043             for (int i = 0; i < nCol-1; i++)
2044                 printf("| ");
2045             printf("|\\\n");
2046         }
2047         else if (nCol < nPrevCol)
2048         {
2049             for (int i = 0; i < nCol; i++)
2050                 printf("| ");
2051             printf("|\n");
2052         }
2053         nPrevCol = nCol;
2054
2055         // print columns
2056         for (int i = 0; i < nCol; i++)
2057             printf("| ");
2058
2059         // print item
2060         CBlock block;
2061         block.ReadFromDisk(pindex);
2062         printf("%d (%u,%u) %s  %s  tx %d",
2063             pindex->nHeight,
2064             pindex->nFile,
2065             pindex->nBlockPos,
2066             block.GetHash().ToString().substr(0,20).c_str(),
2067             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2068             block.vtx.size());
2069
2070         CRITICAL_BLOCK(cs_mapWallet)
2071         {
2072             if (mapWallet.count(block.vtx[0].GetHash()))
2073             {
2074                 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2075                 printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2076             }
2077         }
2078         printf("\n");
2079
2080
2081         // put the main timechain first
2082         vector<CBlockIndex*>& vNext = mapNext[pindex];
2083         for (int i = 0; i < vNext.size(); i++)
2084         {
2085             if (vNext[i]->pnext)
2086             {
2087                 swap(vNext[0], vNext[i]);
2088                 break;
2089             }
2090         }
2091
2092         // iterate children
2093         for (int i = 0; i < vNext.size(); i++)
2094             vStack.push_back(make_pair(nCol+i, vNext[i]));
2095     }
2096 }
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107 //////////////////////////////////////////////////////////////////////////////
2108 //
2109 // CAlert
2110 //
2111
2112 map<uint256, CAlert> mapAlerts;
2113 CCriticalSection cs_mapAlerts;
2114
2115 string GetWarnings(string strFor)
2116 {
2117     int nPriority = 0;
2118     string strStatusBar;
2119     string strRPC;
2120     if (GetBoolArg("-testsafemode"))
2121         strRPC = "test";
2122
2123     // Misc warnings like out of disk space and clock is wrong
2124     if (strMiscWarning != "")
2125     {
2126         nPriority = 1000;
2127         strStatusBar = strMiscWarning;
2128     }
2129
2130     // Longer invalid proof-of-work chain
2131     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2132     {
2133         nPriority = 2000;
2134         strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";
2135     }
2136
2137     // Alerts
2138     CRITICAL_BLOCK(cs_mapAlerts)
2139     {
2140         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2141         {
2142             const CAlert& alert = item.second;
2143             if (alert.AppliesToMe() && alert.nPriority > nPriority)
2144             {
2145                 nPriority = alert.nPriority;
2146                 strStatusBar = alert.strStatusBar;
2147             }
2148         }
2149     }
2150
2151     if (strFor == "statusbar")
2152         return strStatusBar;
2153     else if (strFor == "rpc")
2154         return strRPC;
2155     assert(("GetWarnings() : invalid parameter", false));
2156     return "error";
2157 }
2158
2159 bool CAlert::ProcessAlert()
2160 {
2161     if (!CheckSignature())
2162         return false;
2163     if (!IsInEffect())
2164         return false;
2165
2166     CRITICAL_BLOCK(cs_mapAlerts)
2167     {
2168         // Cancel previous alerts
2169         for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2170         {
2171             const CAlert& alert = (*mi).second;
2172             if (Cancels(alert))
2173             {
2174                 printf("cancelling alert %d\n", alert.nID);
2175                 mapAlerts.erase(mi++);
2176             }
2177             else if (!alert.IsInEffect())
2178             {
2179                 printf("expiring alert %d\n", alert.nID);
2180                 mapAlerts.erase(mi++);
2181             }
2182             else
2183                 mi++;
2184         }
2185
2186         // Check if this alert has been cancelled
2187         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2188         {
2189             const CAlert& alert = item.second;
2190             if (alert.Cancels(*this))
2191             {
2192                 printf("alert already cancelled by %d\n", alert.nID);
2193                 return false;
2194             }
2195         }
2196
2197         // Add to mapAlerts
2198         mapAlerts.insert(make_pair(GetHash(), *this));
2199     }
2200
2201     printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2202     MainFrameRepaint();
2203     return true;
2204 }
2205
2206
2207
2208
2209
2210
2211
2212
2213 //////////////////////////////////////////////////////////////////////////////
2214 //
2215 // Messages
2216 //
2217
2218
2219 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2220 {
2221     switch (inv.type)
2222     {
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);
2225     }
2226     // Don't know what it is, just say we already got one
2227     return true;
2228 }
2229
2230
2231
2232
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 };
2237
2238
2239 bool ProcessMessages(CNode* pfrom)
2240 {
2241     CDataStream& vRecv = pfrom->vRecv;
2242     if (vRecv.empty())
2243         return true;
2244     //if (fDebug)
2245     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
2246
2247     //
2248     // Message format
2249     //  (4) message start
2250     //  (12) command
2251     //  (4) size
2252     //  (4) checksum
2253     //  (x) data
2254     //
2255
2256     loop
2257     {
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)
2262         {
2263             if (vRecv.size() > nHeaderSize)
2264             {
2265                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2266                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2267             }
2268             break;
2269         }
2270         if (pstart - vRecv.begin() > 0)
2271             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2272         vRecv.erase(vRecv.begin(), pstart);
2273
2274         // Read header
2275         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2276         CMessageHeader hdr;
2277         vRecv >> hdr;
2278         if (!hdr.IsValid())
2279         {
2280             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2281             continue;
2282         }
2283         string strCommand = hdr.GetCommand();
2284
2285         // Message size
2286         unsigned int nMessageSize = hdr.nMessageSize;
2287         if (nMessageSize > MAX_SIZE)
2288         {
2289             printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2290             continue;
2291         }
2292         if (nMessageSize > vRecv.size())
2293         {
2294             // Rewind and wait for rest of message
2295             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2296             break;
2297         }
2298
2299         // Checksum
2300         if (vRecv.GetVersion() >= 209)
2301         {
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)
2306             {
2307                 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2308                        strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2309                 continue;
2310             }
2311         }
2312
2313         // Copy message to its own buffer
2314         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2315         vRecv.ignore(nMessageSize);
2316
2317         // Process message
2318         bool fRet = false;
2319         try
2320         {
2321             CRITICAL_BLOCK(cs_main)
2322                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2323             if (fShutdown)
2324                 return true;
2325         }
2326         catch (std::ios_base::failure& e)
2327         {
2328             if (strstr(e.what(), "end of data"))
2329             {
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());
2332             }
2333             else if (strstr(e.what(), "size too large"))
2334             {
2335                 // Allow exceptions from overlong size
2336                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2337             }
2338             else
2339             {
2340                 PrintExceptionContinue(&e, "ProcessMessage()");
2341             }
2342         }
2343         catch (std::exception& e) {
2344             PrintExceptionContinue(&e, "ProcessMessage()");
2345         } catch (...) {
2346             PrintExceptionContinue(NULL, "ProcessMessage()");
2347         }
2348
2349         if (!fRet)
2350             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2351     }
2352
2353     vRecv.Compact();
2354     return true;
2355 }
2356
2357
2358
2359
2360 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2361 {
2362     static map<unsigned int, vector<unsigned char> > mapReuseKey;
2363     RandAddSeedPerfmon();
2364     if (fDebug)
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)
2368     {
2369         printf("dropmessagestest DROPPING RECV MESSAGE\n");
2370         return true;
2371     }
2372
2373
2374
2375
2376
2377     if (strCommand == "version")
2378     {
2379         // Each connection can only send one version message
2380         if (pfrom->nVersion != 0)
2381             return false;
2382
2383         int64 nTime;
2384         CAddress addrMe;
2385         CAddress addrFrom;
2386         uint64 nNonce = 1;
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;
2396
2397         if (pfrom->nVersion == 0)
2398             return false;
2399
2400         // Disconnect if we connected to ourself
2401         if (nNonce == nLocalHostNonce && nNonce > 1)
2402         {
2403             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2404             pfrom->fDisconnect = true;
2405             return true;
2406         }
2407
2408         // Be shy and don't send version until we hear
2409         if (pfrom->fInbound)
2410             pfrom->PushVersion();
2411
2412         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2413
2414         AddTimeData(pfrom->addr.ip, nTime);
2415
2416         // Change version
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));
2422
2423         if (!pfrom->fInbound)
2424         {
2425             // Advertise our address
2426             if (addrLocalHost.IsRoutable() && !fUseProxy)
2427             {
2428                 CAddress addr(addrLocalHost);
2429                 addr.nTime = GetAdjustedTime();
2430                 pfrom->PushAddress(addr);
2431             }
2432
2433             // Get recent addresses
2434             if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2435             {
2436                 pfrom->PushMessage("getaddr");
2437                 pfrom->fGetAddr = true;
2438             }
2439         }
2440
2441         // Ask the first connected node for block updates
2442         static int nAskedForBlocks;
2443         if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2444         {
2445             nAskedForBlocks++;
2446             pfrom->PushGetBlocks(pindexBest, uint256(0));
2447         }
2448
2449         // Relay alerts
2450         CRITICAL_BLOCK(cs_mapAlerts)
2451             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2452                 item.second.RelayTo(pfrom);
2453
2454         pfrom->fSuccessfullyConnected = true;
2455
2456         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2457     }
2458
2459
2460     else if (pfrom->nVersion == 0)
2461     {
2462         // Must have a version message before anything else
2463         return false;
2464     }
2465
2466
2467     else if (strCommand == "verack")
2468     {
2469         pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2470     }
2471
2472
2473     else if (strCommand == "addr")
2474     {
2475         vector<CAddress> vAddr;
2476         vRecv >> vAddr;
2477
2478         // Don't want addr from older versions unless seeding
2479         if (pfrom->nVersion < 209)
2480             return true;
2481         if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2482             return true;
2483         if (vAddr.size() > 1000)
2484             return error("message addr size() = %d", vAddr.size());
2485
2486         // Store the new addresses
2487         int64 nNow = GetAdjustedTime();
2488         int64 nSince = nNow - 10 * 60;
2489         BOOST_FOREACH(CAddress& addr, vAddr)
2490         {
2491             if (fShutdown)
2492                 return true;
2493             // ignore IPv6 for now, since it isn't implemented anyway
2494             if (!addr.IsIPv4())
2495                 continue;
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())
2501             {
2502                 // Relay to a limited number of other nodes
2503                 CRITICAL_BLOCK(cs_vNodes)
2504                 {
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;
2508                     if (hashSalt == 0)
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                     BOOST_FOREACH(CNode* pnode, vNodes)
2514                     {
2515                         if (pnode->nVersion < 31402)
2516                             continue;
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));
2522                     }
2523                     int nRelayNodes = 2;
2524                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2525                         ((*mi).second)->PushAddress(addr);
2526                 }
2527             }
2528         }
2529         if (vAddr.size() < 1000)
2530             pfrom->fGetAddr = false;
2531     }
2532
2533
2534     else if (strCommand == "inv")
2535     {
2536         vector<CInv> vInv;
2537         vRecv >> vInv;
2538         if (vInv.size() > 50000)
2539             return error("message inv size() = %d", vInv.size());
2540
2541         CTxDB txdb("r");
2542         BOOST_FOREACH(const CInv& inv, vInv)
2543         {
2544             if (fShutdown)
2545                 return true;
2546             pfrom->AddInventoryKnown(inv);
2547
2548             bool fAlreadyHave = AlreadyHave(txdb, inv);
2549             printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2550
2551             if (!fAlreadyHave)
2552                 pfrom->AskFor(inv);
2553             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2554                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2555
2556             // Track requests for our stuff
2557             CRITICAL_BLOCK(cs_mapRequestCount)
2558             {
2559                 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2560                 if (mi != mapRequestCount.end())
2561                     (*mi).second++;
2562             }
2563         }
2564     }
2565
2566
2567     else if (strCommand == "getdata")
2568     {
2569         vector<CInv> vInv;
2570         vRecv >> vInv;
2571         if (vInv.size() > 50000)
2572             return error("message getdata size() = %d", vInv.size());
2573
2574         BOOST_FOREACH(const CInv& inv, vInv)
2575         {
2576             if (fShutdown)
2577                 return true;
2578             printf("received getdata for: %s\n", inv.ToString().c_str());
2579
2580             if (inv.type == MSG_BLOCK)
2581             {
2582                 // Send block from disk
2583                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2584                 if (mi != mapBlockIndex.end())
2585                 {
2586                     CBlock block;
2587                     block.ReadFromDisk((*mi).second);
2588                     pfrom->PushMessage("block", block);
2589
2590                     // Trigger them to send a getblocks request for the next batch of inventory
2591                     if (inv.hash == pfrom->hashContinue)
2592                     {
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.
2596                         vector<CInv> vInv;
2597                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2598                         pfrom->PushMessage("inv", vInv);
2599                         pfrom->hashContinue = 0;
2600                     }
2601                 }
2602             }
2603             else if (inv.IsKnownType())
2604             {
2605                 // Send stream from relay memory
2606                 CRITICAL_BLOCK(cs_mapRelay)
2607                 {
2608                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2609                     if (mi != mapRelay.end())
2610                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2611                 }
2612             }
2613
2614             // Track requests for our stuff
2615             CRITICAL_BLOCK(cs_mapRequestCount)
2616             {
2617                 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2618                 if (mi != mapRequestCount.end())
2619                     (*mi).second++;
2620             }
2621         }
2622     }
2623
2624
2625     else if (strCommand == "getblocks")
2626     {
2627         CBlockLocator locator;
2628         uint256 hashStop;
2629         vRecv >> locator >> hashStop;
2630
2631         // Find the last block the caller has in the main chain
2632         CBlockIndex* pindex = locator.GetBlockIndex();
2633
2634         // Send the rest of the chain
2635         if (pindex)
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)
2640         {
2641             if (pindex->GetBlockHash() == hashStop)
2642             {
2643                 printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2644                 break;
2645             }
2646             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2647             if (--nLimit <= 0)
2648             {
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();
2653                 break;
2654             }
2655         }
2656     }
2657
2658
2659     else if (strCommand == "getheaders")
2660     {
2661         CBlockLocator locator;
2662         uint256 hashStop;
2663         vRecv >> locator >> hashStop;
2664
2665         CBlockIndex* pindex = NULL;
2666         if (locator.IsNull())
2667         {
2668             // If locator is null, return the hashStop block
2669             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2670             if (mi == mapBlockIndex.end())
2671                 return true;
2672             pindex = (*mi).second;
2673         }
2674         else
2675         {
2676             // Find the last block the caller has in the main chain
2677             pindex = locator.GetBlockIndex();
2678             if (pindex)
2679                 pindex = pindex->pnext;
2680         }
2681
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)
2686         {
2687             vHeaders.push_back(pindex->GetBlockHeader());
2688             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2689                 break;
2690         }
2691         pfrom->PushMessage("headers", vHeaders);
2692     }
2693
2694
2695     else if (strCommand == "tx")
2696     {
2697         vector<uint256> vWorkQueue;
2698         CDataStream vMsg(vRecv);
2699         CTransaction tx;
2700         vRecv >> tx;
2701
2702         CInv inv(MSG_TX, tx.GetHash());
2703         pfrom->AddInventoryKnown(inv);
2704
2705         bool fMissingInputs = false;
2706         if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2707         {
2708             AddToWalletIfInvolvingMe(tx, NULL, true);
2709             RelayMessage(inv, vMsg);
2710             mapAlreadyAskedFor.erase(inv);
2711             vWorkQueue.push_back(inv.hash);
2712
2713             // Recursively process any orphan transactions that depended on this one
2714             for (int i = 0; i < vWorkQueue.size(); i++)
2715             {
2716                 uint256 hashPrev = vWorkQueue[i];
2717                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2718                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2719                      ++mi)
2720                 {
2721                     const CDataStream& vMsg = *((*mi).second);
2722                     CTransaction tx;
2723                     CDataStream(vMsg) >> tx;
2724                     CInv inv(MSG_TX, tx.GetHash());
2725
2726                     if (tx.AcceptToMemoryPool(true))
2727                     {
2728                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2729                         AddToWalletIfInvolvingMe(tx, NULL, true);
2730                         RelayMessage(inv, vMsg);
2731                         mapAlreadyAskedFor.erase(inv);
2732                         vWorkQueue.push_back(inv.hash);
2733                     }
2734                 }
2735             }
2736
2737             BOOST_FOREACH(uint256 hash, vWorkQueue)
2738                 EraseOrphanTx(hash);
2739         }
2740         else if (fMissingInputs)
2741         {
2742             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2743             AddOrphanTx(vMsg);
2744         }
2745     }
2746
2747
2748     else if (strCommand == "block")
2749     {
2750         CBlock block;
2751         vRecv >> block;
2752
2753         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2754         // block.print();
2755
2756         CInv inv(MSG_BLOCK, block.GetHash());
2757         pfrom->AddInventoryKnown(inv);
2758
2759         if (ProcessBlock(pfrom, &block))
2760             mapAlreadyAskedFor.erase(inv);
2761     }
2762
2763
2764     else if (strCommand == "getaddr")
2765     {
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)
2770         {
2771             unsigned int nCount = 0;
2772             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2773             {
2774                 const CAddress& addr = item.second;
2775                 if (addr.nTime > nSince)
2776                     nCount++;
2777             }
2778             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2779             {
2780                 const CAddress& addr = item.second;
2781                 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2782                     pfrom->PushAddress(addr);
2783             }
2784         }
2785     }
2786
2787
2788     else if (strCommand == "checkorder")
2789     {
2790         uint256 hashReply;
2791         vRecv >> hashReply;
2792
2793         if (!GetBoolArg("-allowreceivebyip"))
2794         {
2795             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2796             return true;
2797         }
2798
2799         CWalletTx order;
2800         vRecv >> order;
2801
2802         /// we have a chance to check the order here
2803
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();
2807
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);
2812     }
2813
2814
2815     else if (strCommand == "submitorder")
2816     {
2817         uint256 hashReply;
2818         vRecv >> hashReply;
2819
2820         if (!GetBoolArg("-allowreceivebyip"))
2821         {
2822             pfrom->PushMessage("reply", hashReply, (int)2);
2823             return true;
2824         }
2825
2826         CWalletTx wtxNew;
2827         vRecv >> wtxNew;
2828         wtxNew.fFromMe = false;
2829
2830         // Broadcast
2831         if (!wtxNew.AcceptWalletTransaction())
2832         {
2833             pfrom->PushMessage("reply", hashReply, (int)1);
2834             return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2835         }
2836         wtxNew.fTimeReceivedIsTxTime = true;
2837         AddToWallet(wtxNew);
2838         wtxNew.RelayWalletTransaction();
2839         mapReuseKey.erase(pfrom->addr.ip);
2840
2841         // Send back confirmation
2842         pfrom->PushMessage("reply", hashReply, (int)0);
2843     }
2844
2845
2846     else if (strCommand == "reply")
2847     {
2848         uint256 hashReply;
2849         vRecv >> hashReply;
2850
2851         CRequestTracker tracker;
2852         CRITICAL_BLOCK(pfrom->cs_mapRequests)
2853         {
2854             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2855             if (mi != pfrom->mapRequests.end())
2856             {
2857                 tracker = (*mi).second;
2858                 pfrom->mapRequests.erase(mi);
2859             }
2860         }
2861         if (!tracker.IsNull())
2862             tracker.fn(tracker.param1, vRecv);
2863     }
2864
2865
2866     else if (strCommand == "ping")
2867     {
2868     }
2869
2870
2871     else if (strCommand == "alert")
2872     {
2873         CAlert alert;
2874         vRecv >> alert;
2875
2876         if (alert.ProcessAlert())
2877         {
2878             // Relay
2879             pfrom->setKnown.insert(alert.GetHash());
2880             CRITICAL_BLOCK(cs_vNodes)
2881                 BOOST_FOREACH(CNode* pnode, vNodes)
2882                     alert.RelayTo(pnode);
2883         }
2884     }
2885
2886
2887     else
2888     {
2889         // Ignore unknown commands for extensibility
2890     }
2891
2892
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);
2897
2898
2899     return true;
2900 }
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910 bool SendMessages(CNode* pto, bool fSendTrickle)
2911 {
2912     CRITICAL_BLOCK(cs_main)
2913     {
2914         // Don't send anything until we get their version message
2915         if (pto->nVersion == 0)
2916             return true;
2917
2918         // Keep-alive ping
2919         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2920             pto->PushMessage("ping");
2921
2922         // Resend wallet transactions that haven't gotten in a block yet
2923         ResendWalletTransactions();
2924
2925         // Address refresh broadcast
2926         static int64 nLastRebroadcast;
2927         if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2928         {
2929             nLastRebroadcast = GetTime();
2930             CRITICAL_BLOCK(cs_vNodes)
2931             {
2932                 BOOST_FOREACH(CNode* pnode, vNodes)
2933                 {
2934                     // Periodically clear setAddrKnown to allow refresh broadcasts
2935                     pnode->setAddrKnown.clear();
2936
2937                     // Rebroadcast our address
2938                     if (addrLocalHost.IsRoutable() && !fUseProxy)
2939                     {
2940                         CAddress addr(addrLocalHost);
2941                         addr.nTime = GetAdjustedTime();
2942                         pnode->PushAddress(addr);
2943                     }
2944                 }
2945             }
2946         }
2947
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)
2953         {
2954             nLastClear = GetTime();
2955             CRITICAL_BLOCK(cs_mapAddresses)
2956             {
2957                 CAddrDB addrdb;
2958                 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2959                 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2960                      mi != mapAddresses.end();)
2961                 {
2962                     const CAddress& addr = (*mi).second;
2963                     if (addr.nTime < nSince)
2964                     {
2965                         if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2966                             break;
2967                         addrdb.EraseAddress(addr);
2968                         mapAddresses.erase(mi++);
2969                     }
2970                     else
2971                         mi++;
2972                 }
2973             }
2974         }
2975
2976
2977         //
2978         // Message: addr
2979         //
2980         if (fSendTrickle)
2981         {
2982             vector<CAddress> vAddr;
2983             vAddr.reserve(pto->vAddrToSend.size());
2984             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2985             {
2986                 // returns true if wasn't already contained in the set
2987                 if (pto->setAddrKnown.insert(addr).second)
2988                 {
2989                     vAddr.push_back(addr);
2990                     // receiver rejects addr messages larger than 1000
2991                     if (vAddr.size() >= 1000)
2992                     {
2993                         pto->PushMessage("addr", vAddr);
2994                         vAddr.clear();
2995                     }
2996                 }
2997             }
2998             pto->vAddrToSend.clear();
2999             if (!vAddr.empty())
3000                 pto->PushMessage("addr", vAddr);
3001         }
3002
3003
3004         //
3005         // Message: inventory
3006         //
3007         vector<CInv> vInv;
3008         vector<CInv> vInvWait;
3009         CRITICAL_BLOCK(pto->cs_inventory)
3010         {
3011             vInv.reserve(pto->vInventoryToSend.size());
3012             vInvWait.reserve(pto->vInventoryToSend.size());
3013             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3014             {
3015                 if (pto->setInventoryKnown.count(inv))
3016                     continue;
3017
3018                 // trickle out tx inv to protect privacy
3019                 if (inv.type == MSG_TX && !fSendTrickle)
3020                 {
3021                     // 1/4 of tx invs blast to all immediately
3022                     static uint256 hashSalt;
3023                     if (hashSalt == 0)
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);
3028
3029                     // always trickle our own transactions
3030                     if (!fTrickleWait)
3031                     {
3032                         TRY_CRITICAL_BLOCK(cs_mapWallet)
3033                         {
3034                             map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
3035                             if (mi != mapWallet.end())
3036                             {
3037                                 CWalletTx& wtx = (*mi).second;
3038                                 if (wtx.fFromMe)
3039                                     fTrickleWait = true;
3040                             }
3041                         }
3042                     }
3043
3044                     if (fTrickleWait)
3045                     {
3046                         vInvWait.push_back(inv);
3047                         continue;
3048                     }
3049                 }
3050
3051                 // returns true if wasn't already contained in the set
3052                 if (pto->setInventoryKnown.insert(inv).second)
3053                 {
3054                     vInv.push_back(inv);
3055                     if (vInv.size() >= 1000)
3056                     {
3057                         pto->PushMessage("inv", vInv);
3058                         vInv.clear();
3059                     }
3060                 }
3061             }
3062             pto->vInventoryToSend = vInvWait;
3063         }
3064         if (!vInv.empty())
3065             pto->PushMessage("inv", vInv);
3066
3067
3068         //
3069         // Message: getdata
3070         //
3071         vector<CInv> vGetData;
3072         int64 nNow = GetTime() * 1000000;
3073         CTxDB txdb("r");
3074         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3075         {
3076             const CInv& inv = (*pto->mapAskFor.begin()).second;
3077             if (!AlreadyHave(txdb, inv))
3078             {
3079                 printf("sending getdata: %s\n", inv.ToString().c_str());
3080                 vGetData.push_back(inv);
3081                 if (vGetData.size() >= 1000)
3082                 {
3083                     pto->PushMessage("getdata", vGetData);
3084                     vGetData.clear();
3085                 }
3086             }
3087             pto->mapAskFor.erase(pto->mapAskFor.begin());
3088         }
3089         if (!vGetData.empty())
3090             pto->PushMessage("getdata", vGetData);
3091
3092     }
3093     return true;
3094 }
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109 //////////////////////////////////////////////////////////////////////////////
3110 //
3111 // BitcoinMiner
3112 //
3113
3114 void GenerateBitcoins(bool fGenerate)
3115 {
3116     if (fGenerateBitcoins != fGenerate)
3117     {
3118         fGenerateBitcoins = fGenerate;
3119         CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3120         MainFrameRepaint();
3121     }
3122     if (fGenerateBitcoins)
3123     {
3124         int nProcessors = boost::thread::hardware_concurrency();
3125         printf("%d processors\n", nProcessors);
3126         if (nProcessors < 1)
3127             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++)
3133         {
3134             if (!CreateThread(ThreadBitcoinMiner, NULL))
3135                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3136             Sleep(10);
3137         }
3138     }
3139 }
3140
3141 void ThreadBitcoinMiner(void* parg)
3142 {
3143     try
3144     {
3145         vnThreadsRunning[3]++;
3146         BitcoinMiner();
3147         vnThreadsRunning[3]--;
3148     }
3149     catch (std::exception& e) {
3150         vnThreadsRunning[3]--;
3151         PrintException(&e, "ThreadBitcoinMiner()");
3152     } catch (...) {
3153         vnThreadsRunning[3]--;
3154         PrintException(NULL, "ThreadBitcoinMiner()");
3155     }
3156     UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3157     nHPSTimerStart = 0;
3158     if (vnThreadsRunning[3] == 0)
3159         dHashesPerSec = 0;
3160     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3161 }
3162
3163
3164 int FormatHashBlocks(void* pbuffer, unsigned int len)
3165 {
3166     unsigned char* pdata = (unsigned char*)pbuffer;
3167     unsigned int blocks = 1 + ((len + 8) / 64);
3168     unsigned char* pend = pdata + 64 * blocks;
3169     memset(pdata + len, 0, 64 * blocks - len);
3170     pdata[len] = 0x80;
3171     unsigned int bits = len * 8;
3172     pend[-1] = (bits >> 0) & 0xff;
3173     pend[-2] = (bits >> 8) & 0xff;
3174     pend[-3] = (bits >> 16) & 0xff;
3175     pend[-4] = (bits >> 24) & 0xff;
3176     return blocks;
3177 }
3178
3179 using CryptoPP::ByteReverse;
3180
3181 static const unsigned int pSHA256InitState[8] =
3182 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3183
3184 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3185 {
3186     memcpy(pstate, pinit, 32);
3187     CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3188 }
3189
3190 //
3191 // ScanHash scans nonces looking for a hash with at least some zero bits.
3192 // It operates on big endian data.  Caller does the byte reversing.
3193 // All input buffers are 16-byte aligned.  nNonce is usually preserved
3194 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3195 // the block is rebuilt and nNonce starts over at zero.
3196 //
3197 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3198 {
3199     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3200     for (;;)
3201     {
3202         // Crypto++ SHA-256
3203         // Hash pdata using pmidstate as the starting state into
3204         // preformatted buffer phash1, then hash phash1 into phash
3205         nNonce++;
3206         SHA256Transform(phash1, pdata, pmidstate);
3207         SHA256Transform(phash, phash1, pSHA256InitState);
3208
3209         // Return the nonce if the hash has at least some zero bits,
3210         // caller will check if it has enough to reach the target
3211         if (((unsigned short*)phash)[14] == 0)
3212             return nNonce;
3213
3214         // If nothing found after trying for a while, return -1
3215         if ((nNonce & 0xffff) == 0)
3216         {
3217             nHashesDone = 0xffff+1;
3218             return -1;
3219         }
3220     }
3221 }
3222
3223
3224 class COrphan
3225 {
3226 public:
3227     CTransaction* ptx;
3228     set<uint256> setDependsOn;
3229     double dPriority;
3230
3231     COrphan(CTransaction* ptxIn)
3232     {
3233         ptx = ptxIn;
3234         dPriority = 0;
3235     }
3236
3237     void print() const
3238     {
3239         printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3240         BOOST_FOREACH(uint256 hash, setDependsOn)
3241             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3242     }
3243 };
3244
3245
3246 CBlock* CreateNewBlock(CReserveKey& reservekey)
3247 {
3248     CBlockIndex* pindexPrev = pindexBest;
3249
3250     // Create new block
3251     auto_ptr<CBlock> pblock(new CBlock());
3252     if (!pblock.get())
3253         return NULL;
3254
3255     // Create coinbase tx
3256     CTransaction txNew;
3257     txNew.vin.resize(1);
3258     txNew.vin[0].prevout.SetNull();
3259     txNew.vout.resize(1);
3260     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3261
3262     // Add our coinbase tx as first transaction
3263     pblock->vtx.push_back(txNew);
3264
3265     // Collect memory pool transactions into the block
3266     int64 nFees = 0;
3267     CRITICAL_BLOCK(cs_main)
3268     CRITICAL_BLOCK(cs_mapTransactions)
3269     {
3270         CTxDB txdb("r");
3271
3272         // Priority order to process transactions
3273         list<COrphan> vOrphan; // list memory doesn't move
3274         map<uint256, vector<COrphan*> > mapDependers;
3275         multimap<double, CTransaction*> mapPriority;
3276         for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3277         {
3278             CTransaction& tx = (*mi).second;
3279             if (tx.IsCoinBase() || !tx.IsFinal())
3280                 continue;
3281
3282             COrphan* porphan = NULL;
3283             double dPriority = 0;
3284             BOOST_FOREACH(const CTxIn& txin, tx.vin)
3285             {
3286                 // Read prev transaction
3287                 CTransaction txPrev;
3288                 CTxIndex txindex;
3289                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3290                 {
3291                     // Has to wait for dependencies
3292                     if (!porphan)
3293                     {
3294                         // Use list for automatic deletion
3295                         vOrphan.push_back(COrphan(&tx));
3296                         porphan = &vOrphan.back();
3297                     }
3298                     mapDependers[txin.prevout.hash].push_back(porphan);
3299                     porphan->setDependsOn.insert(txin.prevout.hash);
3300                     continue;
3301                 }
3302                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3303
3304                 // Read block header
3305                 int nConf = txindex.GetDepthInMainChain();
3306
3307                 dPriority += (double)nValueIn * nConf;
3308
3309                 if (fDebug && GetBoolArg("-printpriority"))
3310                     printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3311             }
3312
3313             // Priority is sum(valuein * age) / txsize
3314             dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3315
3316             if (porphan)
3317                 porphan->dPriority = dPriority;
3318             else
3319                 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3320
3321             if (fDebug && GetBoolArg("-printpriority"))
3322             {
3323                 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3324                 if (porphan)
3325                     porphan->print();
3326                 printf("\n");
3327             }
3328         }
3329
3330         // Collect transactions into block
3331         map<uint256, CTxIndex> mapTestPool;
3332         uint64 nBlockSize = 1000;
3333         int nBlockSigOps = 100;
3334         while (!mapPriority.empty())
3335         {
3336             // Take highest priority transaction off priority queue
3337             double dPriority = -(*mapPriority.begin()).first;
3338             CTransaction& tx = *(*mapPriority.begin()).second;
3339             mapPriority.erase(mapPriority.begin());
3340
3341             // Size limits
3342             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3343             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3344                 continue;
3345             int nTxSigOps = tx.GetSigOpCount();
3346             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3347                 continue;
3348
3349             // Transaction fee required depends on block size
3350             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3351             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
3352
3353             // Connecting shouldn't fail due to dependency on other memory pool transactions
3354             // because we're already processing them in order of dependency
3355             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3356             if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3357                 continue;
3358             swap(mapTestPool, mapTestPoolTmp);
3359
3360             // Added
3361             pblock->vtx.push_back(tx);
3362             nBlockSize += nTxSize;
3363             nBlockSigOps += nTxSigOps;
3364
3365             // Add transactions that depend on this one to the priority queue
3366             uint256 hash = tx.GetHash();
3367             if (mapDependers.count(hash))
3368             {
3369                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3370                 {
3371                     if (!porphan->setDependsOn.empty())
3372                     {
3373                         porphan->setDependsOn.erase(hash);
3374                         if (porphan->setDependsOn.empty())
3375                             mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3376                     }
3377                 }
3378             }
3379         }
3380     }
3381     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3382
3383     // Fill in header
3384     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
3385     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3386     pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3387     pblock->nBits          = GetNextWorkRequired(pindexPrev);
3388     pblock->nNonce         = 0;
3389
3390     return pblock.release();
3391 }
3392
3393
3394 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3395 {
3396     // Update nExtraNonce
3397     int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3398     if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3399     {
3400         nExtraNonce = 1;
3401         nPrevTime = nNow;
3402     }
3403     pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3404     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3405 }
3406
3407
3408 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3409 {
3410     //
3411     // Prebuild hash buffers
3412     //
3413     struct
3414     {
3415         struct unnamed2
3416         {
3417             int nVersion;
3418             uint256 hashPrevBlock;
3419             uint256 hashMerkleRoot;
3420             unsigned int nTime;
3421             unsigned int nBits;
3422             unsigned int nNonce;
3423         }
3424         block;
3425         unsigned char pchPadding0[64];
3426         uint256 hash1;
3427         unsigned char pchPadding1[64];
3428     }
3429     tmp;
3430     memset(&tmp, 0, sizeof(tmp));
3431
3432     tmp.block.nVersion       = pblock->nVersion;
3433     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
3434     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3435     tmp.block.nTime          = pblock->nTime;
3436     tmp.block.nBits          = pblock->nBits;
3437     tmp.block.nNonce         = pblock->nNonce;
3438
3439     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3440     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3441
3442     // Byte swap all the input buffer
3443     for (int i = 0; i < sizeof(tmp)/4; i++)
3444         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3445
3446     // Precalc the first half of the first hash, which stays constant
3447     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3448
3449     memcpy(pdata, &tmp.block, 128);
3450     memcpy(phash1, &tmp.hash1, 64);
3451 }
3452
3453
3454 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3455 {
3456     uint256 hash = pblock->GetHash();
3457     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3458
3459     if (hash > hashTarget)
3460         return false;
3461
3462     //// debug print
3463     printf("BitcoinMiner:\n");
3464     printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3465     pblock->print();
3466     printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3467     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3468
3469     // Found a solution
3470     CRITICAL_BLOCK(cs_main)
3471     {
3472         if (pblock->hashPrevBlock != hashBestChain)
3473             return error("BitcoinMiner : generated block is stale");
3474
3475         // Remove key from key pool
3476         reservekey.KeepKey();
3477
3478         // Track how many getdata requests this block gets
3479         CRITICAL_BLOCK(cs_mapRequestCount)
3480             mapRequestCount[pblock->GetHash()] = 0;
3481
3482         // Process this block the same as if we had received it from another node
3483         if (!ProcessBlock(NULL, pblock))
3484             return error("BitcoinMiner : ProcessBlock, block not accepted");
3485     }
3486
3487     Sleep(2000);
3488     return true;
3489 }
3490
3491
3492 void BitcoinMiner()
3493 {
3494     printf("BitcoinMiner started\n");
3495     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3496
3497     // Each thread has its own key and counter
3498     CReserveKey reservekey;
3499     unsigned int nExtraNonce = 0;
3500     int64 nPrevTime = 0;
3501
3502     while (fGenerateBitcoins)
3503     {
3504         if (AffinityBugWorkaround(ThreadBitcoinMiner))
3505             return;
3506         if (fShutdown)
3507             return;
3508         while (vNodes.empty() || IsInitialBlockDownload())
3509         {
3510             Sleep(1000);
3511             if (fShutdown)
3512                 return;
3513             if (!fGenerateBitcoins)
3514                 return;
3515         }
3516
3517
3518         //
3519         // Create new block
3520         //
3521         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3522         CBlockIndex* pindexPrev = pindexBest;
3523
3524         auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3525         if (!pblock.get())
3526             return;
3527         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3528
3529         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3530
3531
3532         //
3533         // Prebuild hash buffers
3534         //
3535         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3536         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
3537         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
3538
3539         FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3540
3541         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3542         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3543
3544
3545         //
3546         // Search
3547         //
3548         int64 nStart = GetTime();
3549         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3550         uint256 hashbuf[2];
3551         uint256& hash = *alignup<16>(hashbuf);
3552         loop
3553         {
3554             unsigned int nHashesDone = 0;
3555             unsigned int nNonceFound;
3556
3557             // Crypto++ SHA-256
3558             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3559                                             (char*)&hash, nHashesDone);
3560
3561             // Check if something found
3562             if (nNonceFound != -1)
3563             {
3564                 for (int i = 0; i < sizeof(hash)/4; i++)
3565                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3566
3567                 if (hash <= hashTarget)
3568                 {
3569                     // Found a solution
3570                     pblock->nNonce = ByteReverse(nNonceFound);
3571                     assert(hash == pblock->GetHash());
3572
3573                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3574                     CheckWork(pblock.get(), reservekey);
3575                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3576                     break;
3577                 }
3578             }
3579
3580             // Meter hashes/sec
3581             static int64 nHashCounter;
3582             if (nHPSTimerStart == 0)
3583             {
3584                 nHPSTimerStart = GetTimeMillis();
3585                 nHashCounter = 0;
3586             }
3587             else
3588                 nHashCounter += nHashesDone;
3589             if (GetTimeMillis() - nHPSTimerStart > 4000)
3590             {
3591                 static CCriticalSection cs;
3592                 CRITICAL_BLOCK(cs)
3593                 {
3594                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3595                     {
3596                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3597                         nHPSTimerStart = GetTimeMillis();
3598                         nHashCounter = 0;
3599                         string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
3600                         UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3601                         static int64 nLogTime;
3602                         if (GetTime() - nLogTime > 30 * 60)
3603                         {
3604                             nLogTime = GetTime();
3605                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3606                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3607                         }
3608                     }
3609                 }
3610             }
3611
3612             // Check for stop or if block needs to be rebuilt
3613             if (fShutdown)
3614                 return;
3615             if (!fGenerateBitcoins)
3616                 return;
3617             if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3618                 return;
3619             if (vNodes.empty())
3620                 break;
3621             if (nBlockNonce >= 0xffff0000)
3622                 break;
3623             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3624                 break;
3625             if (pindexPrev != pindexBest)
3626                 break;
3627
3628             // Update nTime every few seconds
3629             pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3630             nBlockTime = ByteReverse(pblock->nTime);
3631         }
3632     }
3633 }
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652 //////////////////////////////////////////////////////////////////////////////
3653 //
3654 // Actions
3655 //
3656
3657
3658 int64 GetBalance()
3659 {
3660     int64 nStart = GetTimeMillis();
3661
3662     int64 nTotal = 0;
3663     CRITICAL_BLOCK(cs_mapWallet)
3664     {
3665         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3666         {
3667             CWalletTx* pcoin = &(*it).second;
3668             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3669                 continue;
3670             nTotal += pcoin->GetAvailableCredit();
3671         }
3672     }
3673
3674     //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3675     return nTotal;
3676 }
3677
3678
3679 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3680 {
3681     setCoinsRet.clear();
3682     nValueRet = 0;
3683
3684     // List of values less than target
3685     pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;
3686     coinLowestLarger.first = INT64_MAX;
3687     coinLowestLarger.second.first = NULL;
3688     vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;
3689     int64 nTotalLower = 0;
3690
3691     CRITICAL_BLOCK(cs_mapWallet)
3692     {
3693        vector<CWalletTx*> vCoins;
3694        vCoins.reserve(mapWallet.size());
3695        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3696            vCoins.push_back(&(*it).second);
3697        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3698
3699        BOOST_FOREACH(CWalletTx* pcoin, vCoins)
3700        {
3701             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
3702                 continue;
3703
3704             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3705                 continue;
3706
3707             int nDepth = pcoin->GetDepthInMainChain();
3708             if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3709                 continue;
3710
3711             for (int i = 0; i < pcoin->vout.size(); i++)
3712             {
3713                 if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())
3714                     continue;
3715
3716                 int64 n = pcoin->vout[i].nValue;
3717
3718                 if (n <= 0)
3719                     continue;
3720
3721                 pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
3722
3723                 if (n == nTargetValue)
3724                 {
3725                     setCoinsRet.insert(coin.second);
3726                     nValueRet += coin.first;
3727                     return true;
3728                 }
3729                 else if (n < nTargetValue + CENT)
3730                 {
3731                     vValue.push_back(coin);
3732                     nTotalLower += n;
3733                 }
3734                 else if (n < coinLowestLarger.first)
3735                 {
3736                     coinLowestLarger = coin;
3737                 }
3738             }
3739         }
3740     }
3741
3742     if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
3743     {
3744         for (int i = 0; i < vValue.size(); ++i)
3745         {
3746             setCoinsRet.insert(vValue[i].second);
3747             nValueRet += vValue[i].first;
3748         }
3749         return true;
3750     }
3751
3752     if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
3753     {
3754         if (coinLowestLarger.second.first == NULL)
3755             return false;
3756         setCoinsRet.insert(coinLowestLarger.second);
3757         nValueRet += coinLowestLarger.first;
3758         return true;
3759     }
3760
3761     if (nTotalLower >= nTargetValue + CENT)
3762         nTargetValue += CENT;
3763
3764     // Solve subset sum by stochastic approximation
3765     sort(vValue.rbegin(), vValue.rend());
3766     vector<char> vfIncluded;
3767     vector<char> vfBest(vValue.size(), true);
3768     int64 nBest = nTotalLower;
3769
3770     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3771     {
3772         vfIncluded.assign(vValue.size(), false);
3773         int64 nTotal = 0;
3774         bool fReachedTarget = false;
3775         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3776         {
3777             for (int i = 0; i < vValue.size(); i++)
3778             {
3779                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3780                 {
3781                     nTotal += vValue[i].first;
3782                     vfIncluded[i] = true;
3783                     if (nTotal >= nTargetValue)
3784                     {
3785                         fReachedTarget = true;
3786                         if (nTotal < nBest)
3787                         {
3788                             nBest = nTotal;
3789                             vfBest = vfIncluded;
3790                         }
3791                         nTotal -= vValue[i].first;
3792                         vfIncluded[i] = false;
3793                     }
3794                 }
3795             }
3796         }
3797     }
3798
3799     // If the next larger is still closer, return it
3800     if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
3801     {
3802         setCoinsRet.insert(coinLowestLarger.second);
3803         nValueRet += coinLowestLarger.first;
3804     }
3805     else {
3806         for (int i = 0; i < vValue.size(); i++)
3807             if (vfBest[i])
3808             {
3809                 setCoinsRet.insert(vValue[i].second);
3810                 nValueRet += vValue[i].first;
3811             }
3812
3813         //// debug print
3814         printf("SelectCoins() best subset: ");
3815         for (int i = 0; i < vValue.size(); i++)
3816             if (vfBest[i])
3817                 printf("%s ", FormatMoney(vValue[i].first).c_str());
3818         printf("total %s\n", FormatMoney(nBest).c_str());
3819     }
3820
3821     return true;
3822 }
3823
3824 bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)
3825 {
3826     return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
3827             SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
3828             SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
3829 }
3830
3831
3832
3833
3834 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3835 {
3836     int64 nValue = 0;
3837     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3838     {
3839         if (nValue < 0)
3840             return false;
3841         nValue += s.second;
3842     }
3843     if (vecSend.empty() || nValue < 0)
3844         return false;
3845
3846     CRITICAL_BLOCK(cs_main)
3847     {
3848         // txdb must be opened before the mapWallet lock
3849         CTxDB txdb("r");
3850         CRITICAL_BLOCK(cs_mapWallet)
3851         {
3852             nFeeRet = nTransactionFee;
3853             loop
3854             {
3855                 wtxNew.vin.clear();
3856                 wtxNew.vout.clear();
3857                 wtxNew.fFromMe = true;
3858
3859                 int64 nTotalValue = nValue + nFeeRet;
3860                 double dPriority = 0;
3861                 // vouts to the payees
3862                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
3863                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
3864
3865                 // Choose coins to use
3866                 set<pair<CWalletTx*,unsigned int> > setCoins;
3867                 int64 nValueIn = 0;
3868                 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
3869                     return false;
3870                 BOOST_FOREACH(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)
3871                 {
3872                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
3873                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
3874                 }
3875
3876                 int64 nChange = nValueIn - nValue - nFeeRet;
3877
3878                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
3879                 // or until nChange becomes zero
3880                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
3881                 {
3882                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
3883                     nChange -= nMoveToFee;
3884                     nFeeRet += nMoveToFee;
3885                 }
3886
3887                 if (nChange > 0)
3888                 {
3889                     // Note: We use a new key here to keep it from being obvious which side is the change.
3890                     //  The drawback is that by not reusing a previous key, the change may be lost if a
3891                     //  backup is restored, if the backup doesn't have the new private key for the change.
3892                     //  If we reused the old key, it would be possible to add code to look for and
3893                     //  rediscover unknown transactions that were written with keys of ours to recover
3894                     //  post-backup change.
3895
3896                     // Reserve a new key pair from key pool
3897                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3898                     assert(mapKeys.count(vchPubKey));
3899
3900                     // Fill a vout to ourself, using same address type as the payment
3901                     CScript scriptChange;
3902                     if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
3903                         scriptChange.SetBitcoinAddress(vchPubKey);
3904                     else
3905                         scriptChange << vchPubKey << OP_CHECKSIG;
3906
3907                     // Insert change txn at random position:
3908                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
3909                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
3910                 }
3911                 else
3912                     reservekey.ReturnKey();
3913
3914                 // Fill vin
3915                 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3916                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
3917
3918                 // Sign
3919                 int nIn = 0;
3920                 BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
3921                     if (!SignSignature(*coin.first, wtxNew, nIn++))
3922                         return false;
3923
3924                 // Limit size
3925                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3926                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3927                     return false;
3928                 dPriority /= nBytes;
3929
3930                 // Check that enough fee is included
3931                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3932                 bool fAllowFree = CTransaction::AllowFree(dPriority);
3933                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
3934                 if (nFeeRet < max(nPayFee, nMinFee))
3935                 {
3936                     nFeeRet = max(nPayFee, nMinFee);
3937                     continue;
3938                 }
3939
3940                 // Fill vtxPrev by copying from previous transactions vtxPrev
3941                 wtxNew.AddSupportingTransactions(txdb);
3942                 wtxNew.fTimeReceivedIsTxTime = true;
3943
3944                 break;
3945             }
3946         }
3947     }
3948     return true;
3949 }
3950
3951 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3952 {
3953     vector< pair<CScript, int64> > vecSend;
3954     vecSend.push_back(make_pair(scriptPubKey, nValue));
3955     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
3956 }
3957
3958 // Call after CreateTransaction unless you want to abort
3959 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3960 {
3961     CRITICAL_BLOCK(cs_main)
3962     {
3963         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3964         CRITICAL_BLOCK(cs_mapWallet)
3965         {
3966             // This is only to keep the database open to defeat the auto-flush for the
3967             // duration of this scope.  This is the only place where this optimization
3968             // maybe makes sense; please don't do it anywhere else.
3969             CWalletDB walletdb("r");
3970
3971             // Take key pair from key pool so it won't be used again
3972             reservekey.KeepKey();
3973
3974             // Add tx to wallet, because if it has change it's also ours,
3975             // otherwise just for transaction history.
3976             AddToWallet(wtxNew);
3977
3978             // Mark old coins as spent
3979             set<CWalletTx*> setCoins;
3980             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3981             {
3982                 CWalletTx &pcoin = mapWallet[txin.prevout.hash];
3983                 pcoin.MarkSpent(txin.prevout.n);
3984                 pcoin.WriteToDisk();
3985                 vWalletUpdated.push_back(pcoin.GetHash());
3986             }
3987         }
3988
3989         // Track how many getdata requests our transaction gets
3990         CRITICAL_BLOCK(cs_mapRequestCount)
3991             mapRequestCount[wtxNew.GetHash()] = 0;
3992
3993         // Broadcast
3994         if (!wtxNew.AcceptToMemoryPool())
3995         {
3996             // This must not fail. The transaction has already been signed and recorded.
3997             printf("CommitTransaction() : Error: Transaction not valid");
3998             return false;
3999         }
4000         wtxNew.RelayWalletTransaction();
4001     }
4002     MainFrameRepaint();
4003     return true;
4004 }
4005
4006
4007
4008
4009 // requires cs_main lock
4010 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4011 {
4012     CReserveKey reservekey;
4013     int64 nFeeRequired;
4014     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
4015     {
4016         string strError;
4017         if (nValue + nFeeRequired > GetBalance())
4018             strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds  "), FormatMoney(nFeeRequired).c_str());
4019         else
4020             strError = _("Error: Transaction creation failed  ");
4021         printf("SendMoney() : %s", strError.c_str());
4022         return strError;
4023     }
4024
4025     if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4026         return "ABORTED";
4027
4028     if (!CommitTransaction(wtxNew, reservekey))
4029         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.");
4030
4031     MainFrameRepaint();
4032     return "";
4033 }
4034
4035
4036
4037 // requires cs_main lock
4038 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4039 {
4040     // Check amount
4041     if (nValue <= 0)
4042         return _("Invalid amount");
4043     if (nValue + nTransactionFee > GetBalance())
4044         return _("Insufficient funds");
4045
4046     // Parse bitcoin address
4047     CScript scriptPubKey;
4048     if (!scriptPubKey.SetBitcoinAddress(strAddress))
4049         return _("Invalid bitcoin address");
4050
4051     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
4052 }