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