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