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