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