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