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