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