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