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