Fix IsInitialBlockDownload if running on testnet
[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 || (!fTestNet && nBestHeight < 74000))
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         if (!pfrom->fInbound)
2176         {
2177             // Advertise our address
2178             if (addrLocalHost.IsRoutable() && !fUseProxy)
2179             {
2180                 CAddress addr(addrLocalHost);
2181                 addr.nTime = GetAdjustedTime();
2182                 pfrom->PushAddress(addr);
2183             }
2184
2185             // Get recent addresses
2186             if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2187             {
2188                 pfrom->PushMessage("getaddr");
2189                 pfrom->fGetAddr = true;
2190             }
2191         }
2192
2193         // Ask the first connected node for block updates
2194         static int nAskedForBlocks;
2195         if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2196         {
2197             nAskedForBlocks++;
2198             pfrom->PushGetBlocks(pindexBest, uint256(0));
2199         }
2200
2201         // Relay alerts
2202         CRITICAL_BLOCK(cs_mapAlerts)
2203             foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2204                 item.second.RelayTo(pfrom);
2205
2206         pfrom->fSuccessfullyConnected = true;
2207
2208         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2209     }
2210
2211
2212     else if (pfrom->nVersion == 0)
2213     {
2214         // Must have a version message before anything else
2215         return false;
2216     }
2217
2218
2219     else if (strCommand == "verack")
2220     {
2221         pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2222     }
2223
2224
2225     else if (strCommand == "addr")
2226     {
2227         vector<CAddress> vAddr;
2228         vRecv >> vAddr;
2229
2230         // Don't want addr from older versions unless seeding
2231         if (pfrom->nVersion < 209)
2232             return true;
2233         if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2234             return true;
2235         if (vAddr.size() > 1000)
2236             return error("message addr size() = %d", vAddr.size());
2237
2238         // Store the new addresses
2239         int64 nNow = GetAdjustedTime();
2240         int64 nSince = nNow - 10 * 60;
2241         foreach(CAddress& addr, vAddr)
2242         {
2243             if (fShutdown)
2244                 return true;
2245             // ignore IPv6 for now, since it isn't implemented anyway
2246             if (!addr.IsIPv4())
2247                 continue;
2248             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2249                 addr.nTime = nNow - 5 * 24 * 60 * 60;
2250             AddAddress(addr, 2 * 60 * 60);
2251             pfrom->AddAddressKnown(addr);
2252             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2253             {
2254                 // Relay to a limited number of other nodes
2255                 CRITICAL_BLOCK(cs_vNodes)
2256                 {
2257                     // Use deterministic randomness to send to the same nodes for 24 hours
2258                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2259                     static uint256 hashSalt;
2260                     if (hashSalt == 0)
2261                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2262                     uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2263                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2264                     multimap<uint256, CNode*> mapMix;
2265                     foreach(CNode* pnode, vNodes)
2266                     {
2267                         if (pnode->nVersion < 31402)
2268                             continue;
2269                         unsigned int nPointer;
2270                         memcpy(&nPointer, &pnode, sizeof(nPointer));
2271                         uint256 hashKey = hashRand ^ nPointer;
2272                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
2273                         mapMix.insert(make_pair(hashKey, pnode));
2274                     }
2275                     int nRelayNodes = 2;
2276                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2277                         ((*mi).second)->PushAddress(addr);
2278                 }
2279             }
2280         }
2281         if (vAddr.size() < 1000)
2282             pfrom->fGetAddr = false;
2283     }
2284
2285
2286     else if (strCommand == "inv")
2287     {
2288         vector<CInv> vInv;
2289         vRecv >> vInv;
2290         if (vInv.size() > 50000)
2291             return error("message inv size() = %d", vInv.size());
2292
2293         CTxDB txdb("r");
2294         foreach(const CInv& inv, vInv)
2295         {
2296             if (fShutdown)
2297                 return true;
2298             pfrom->AddInventoryKnown(inv);
2299
2300             bool fAlreadyHave = AlreadyHave(txdb, inv);
2301             printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2302
2303             if (!fAlreadyHave)
2304                 pfrom->AskFor(inv);
2305             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2306                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2307
2308             // Track requests for our stuff
2309             CRITICAL_BLOCK(cs_mapRequestCount)
2310             {
2311                 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2312                 if (mi != mapRequestCount.end())
2313                     (*mi).second++;
2314             }
2315         }
2316     }
2317
2318
2319     else if (strCommand == "getdata")
2320     {
2321         vector<CInv> vInv;
2322         vRecv >> vInv;
2323         if (vInv.size() > 50000)
2324             return error("message getdata size() = %d", vInv.size());
2325
2326         foreach(const CInv& inv, vInv)
2327         {
2328             if (fShutdown)
2329                 return true;
2330             printf("received getdata for: %s\n", inv.ToString().c_str());
2331
2332             if (inv.type == MSG_BLOCK)
2333             {
2334                 // Send block from disk
2335                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2336                 if (mi != mapBlockIndex.end())
2337                 {
2338                     //// could optimize this to send header straight from blockindex for client
2339                     CBlock block;
2340                     block.ReadFromDisk((*mi).second, !pfrom->fClient);
2341                     pfrom->PushMessage("block", block);
2342
2343                     // Trigger them to send a getblocks request for the next batch of inventory
2344                     if (inv.hash == pfrom->hashContinue)
2345                     {
2346                         // Bypass PushInventory, this must send even if redundant,
2347                         // and we want it right after the last block so they don't
2348                         // wait for other stuff first.
2349                         vector<CInv> vInv;
2350                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2351                         pfrom->PushMessage("inv", vInv);
2352                         pfrom->hashContinue = 0;
2353                     }
2354                 }
2355             }
2356             else if (inv.IsKnownType())
2357             {
2358                 // Send stream from relay memory
2359                 CRITICAL_BLOCK(cs_mapRelay)
2360                 {
2361                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2362                     if (mi != mapRelay.end())
2363                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2364                 }
2365             }
2366
2367             // Track requests for our stuff
2368             CRITICAL_BLOCK(cs_mapRequestCount)
2369             {
2370                 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2371                 if (mi != mapRequestCount.end())
2372                     (*mi).second++;
2373             }
2374         }
2375     }
2376
2377
2378     else if (strCommand == "getblocks")
2379     {
2380         CBlockLocator locator;
2381         uint256 hashStop;
2382         vRecv >> locator >> hashStop;
2383
2384         // Find the first block the caller has in the main chain
2385         CBlockIndex* pindex = locator.GetBlockIndex();
2386
2387         // Send the rest of the chain
2388         if (pindex)
2389             pindex = pindex->pnext;
2390         int nLimit = 500 + locator.GetDistanceBack();
2391         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2392         for (; pindex; pindex = pindex->pnext)
2393         {
2394             if (pindex->GetBlockHash() == hashStop)
2395             {
2396                 printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2397                 break;
2398             }
2399             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2400             if (--nLimit <= 0)
2401             {
2402                 // When this block is requested, we'll send an inv that'll make them
2403                 // getblocks the next batch of inventory.
2404                 printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2405                 pfrom->hashContinue = pindex->GetBlockHash();
2406                 break;
2407             }
2408         }
2409     }
2410
2411
2412     else if (strCommand == "tx")
2413     {
2414         vector<uint256> vWorkQueue;
2415         CDataStream vMsg(vRecv);
2416         CTransaction tx;
2417         vRecv >> tx;
2418
2419         CInv inv(MSG_TX, tx.GetHash());
2420         pfrom->AddInventoryKnown(inv);
2421
2422         bool fMissingInputs = false;
2423         if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2424         {
2425             AddToWalletIfMine(tx, NULL);
2426             RelayMessage(inv, vMsg);
2427             mapAlreadyAskedFor.erase(inv);
2428             vWorkQueue.push_back(inv.hash);
2429
2430             // Recursively process any orphan transactions that depended on this one
2431             for (int i = 0; i < vWorkQueue.size(); i++)
2432             {
2433                 uint256 hashPrev = vWorkQueue[i];
2434                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2435                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2436                      ++mi)
2437                 {
2438                     const CDataStream& vMsg = *((*mi).second);
2439                     CTransaction tx;
2440                     CDataStream(vMsg) >> tx;
2441                     CInv inv(MSG_TX, tx.GetHash());
2442
2443                     if (tx.AcceptToMemoryPool(true))
2444                     {
2445                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2446                         AddToWalletIfMine(tx, NULL);
2447                         RelayMessage(inv, vMsg);
2448                         mapAlreadyAskedFor.erase(inv);
2449                         vWorkQueue.push_back(inv.hash);
2450                     }
2451                 }
2452             }
2453
2454             foreach(uint256 hash, vWorkQueue)
2455                 EraseOrphanTx(hash);
2456         }
2457         else if (fMissingInputs)
2458         {
2459             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2460             AddOrphanTx(vMsg);
2461         }
2462     }
2463
2464
2465     else if (strCommand == "block")
2466     {
2467         auto_ptr<CBlock> pblock(new CBlock);
2468         vRecv >> *pblock;
2469
2470         //// debug print
2471         printf("received block %s\n", pblock->GetHash().ToString().substr(0,20).c_str());
2472         // pblock->print();
2473
2474         CInv inv(MSG_BLOCK, pblock->GetHash());
2475         pfrom->AddInventoryKnown(inv);
2476
2477         if (ProcessBlock(pfrom, pblock.release()))
2478             mapAlreadyAskedFor.erase(inv);
2479     }
2480
2481
2482     else if (strCommand == "getaddr")
2483     {
2484         // Nodes rebroadcast an addr every 24 hours
2485         pfrom->vAddrToSend.clear();
2486         int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2487         CRITICAL_BLOCK(cs_mapAddresses)
2488         {
2489             unsigned int nCount = 0;
2490             foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2491             {
2492                 const CAddress& addr = item.second;
2493                 if (addr.nTime > nSince)
2494                     nCount++;
2495             }
2496             foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2497             {
2498                 const CAddress& addr = item.second;
2499                 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2500                     pfrom->PushAddress(addr);
2501             }
2502         }
2503     }
2504
2505
2506     else if (strCommand == "checkorder")
2507     {
2508         uint256 hashReply;
2509         CWalletTx order;
2510         vRecv >> hashReply >> order;
2511
2512         if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2513         {
2514             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2515             return true;
2516         }
2517
2518         /// we have a chance to check the order here
2519
2520         // Keep giving the same key to the same ip until they use it
2521         if (!mapReuseKey.count(pfrom->addr.ip))
2522             mapReuseKey[pfrom->addr.ip] = CWalletDB().GetKeyFromKeyPool();
2523
2524         // Send back approval of order and pubkey to use
2525         CScript scriptPubKey;
2526         scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2527         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2528     }
2529
2530
2531     else if (strCommand == "submitorder")
2532     {
2533         uint256 hashReply;
2534         CWalletTx wtxNew;
2535         vRecv >> hashReply >> wtxNew;
2536         wtxNew.fFromMe = false;
2537
2538         if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2539         {
2540             pfrom->PushMessage("reply", hashReply, (int)2);
2541             return true;
2542         }
2543
2544         // Broadcast
2545         if (!wtxNew.AcceptWalletTransaction())
2546         {
2547             pfrom->PushMessage("reply", hashReply, (int)1);
2548             return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2549         }
2550         wtxNew.fTimeReceivedIsTxTime = true;
2551         AddToWallet(wtxNew);
2552         wtxNew.RelayWalletTransaction();
2553         mapReuseKey.erase(pfrom->addr.ip);
2554
2555         // Send back confirmation
2556         pfrom->PushMessage("reply", hashReply, (int)0);
2557     }
2558
2559
2560     else if (strCommand == "reply")
2561     {
2562         uint256 hashReply;
2563         vRecv >> hashReply;
2564
2565         CRequestTracker tracker;
2566         CRITICAL_BLOCK(pfrom->cs_mapRequests)
2567         {
2568             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2569             if (mi != pfrom->mapRequests.end())
2570             {
2571                 tracker = (*mi).second;
2572                 pfrom->mapRequests.erase(mi);
2573             }
2574         }
2575         if (!tracker.IsNull())
2576             tracker.fn(tracker.param1, vRecv);
2577     }
2578
2579
2580     else if (strCommand == "ping")
2581     {
2582     }
2583
2584
2585     else if (strCommand == "alert")
2586     {
2587         CAlert alert;
2588         vRecv >> alert;
2589
2590         if (alert.ProcessAlert())
2591         {
2592             // Relay
2593             pfrom->setKnown.insert(alert.GetHash());
2594             CRITICAL_BLOCK(cs_vNodes)
2595                 foreach(CNode* pnode, vNodes)
2596                     alert.RelayTo(pnode);
2597         }
2598     }
2599
2600
2601     else
2602     {
2603         // Ignore unknown commands for extensibility
2604     }
2605
2606
2607     // Update the last seen time for this node's address
2608     if (pfrom->fNetworkNode)
2609         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2610             AddressCurrentlyConnected(pfrom->addr);
2611
2612
2613     return true;
2614 }
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624 bool SendMessages(CNode* pto, bool fSendTrickle)
2625 {
2626     CRITICAL_BLOCK(cs_main)
2627     {
2628         // Don't send anything until we get their version message
2629         if (pto->nVersion == 0)
2630             return true;
2631
2632         // Keep-alive ping
2633         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2634             pto->PushMessage("ping");
2635
2636         // Resend wallet transactions that haven't gotten in a block yet
2637         ResendWalletTransactions();
2638
2639         // Address refresh broadcast
2640         static int64 nLastRebroadcast;
2641         if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2642         {
2643             nLastRebroadcast = GetTime();
2644             CRITICAL_BLOCK(cs_vNodes)
2645             {
2646                 foreach(CNode* pnode, vNodes)
2647                 {
2648                     // Periodically clear setAddrKnown to allow refresh broadcasts
2649                     pnode->setAddrKnown.clear();
2650
2651                     // Rebroadcast our address
2652                     if (addrLocalHost.IsRoutable() && !fUseProxy)
2653                     {
2654                         CAddress addr(addrLocalHost);
2655                         addr.nTime = GetAdjustedTime();
2656                         pnode->PushAddress(addr);
2657                     }
2658                 }
2659             }
2660         }
2661
2662         // Clear out old addresses periodically so it's not too much work at once
2663         static int64 nLastClear;
2664         if (nLastClear == 0)
2665             nLastClear = GetTime();
2666         if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2667         {
2668             nLastClear = GetTime();
2669             CRITICAL_BLOCK(cs_mapAddresses)
2670             {
2671                 CAddrDB addrdb;
2672                 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2673                 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2674                      mi != mapAddresses.end();)
2675                 {
2676                     const CAddress& addr = (*mi).second;
2677                     if (addr.nTime < nSince)
2678                     {
2679                         if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2680                             break;
2681                         addrdb.EraseAddress(addr);
2682                         mapAddresses.erase(mi++);
2683                     }
2684                     else
2685                         mi++;
2686                 }
2687             }
2688         }
2689
2690
2691         //
2692         // Message: addr
2693         //
2694         if (fSendTrickle)
2695         {
2696             vector<CAddress> vAddr;
2697             vAddr.reserve(pto->vAddrToSend.size());
2698             foreach(const CAddress& addr, pto->vAddrToSend)
2699             {
2700                 // returns true if wasn't already contained in the set
2701                 if (pto->setAddrKnown.insert(addr).second)
2702                 {
2703                     vAddr.push_back(addr);
2704                     // receiver rejects addr messages larger than 1000
2705                     if (vAddr.size() >= 1000)
2706                     {
2707                         pto->PushMessage("addr", vAddr);
2708                         vAddr.clear();
2709                     }
2710                 }
2711             }
2712             pto->vAddrToSend.clear();
2713             if (!vAddr.empty())
2714                 pto->PushMessage("addr", vAddr);
2715         }
2716
2717
2718         //
2719         // Message: inventory
2720         //
2721         vector<CInv> vInv;
2722         vector<CInv> vInvWait;
2723         CRITICAL_BLOCK(pto->cs_inventory)
2724         {
2725             vInv.reserve(pto->vInventoryToSend.size());
2726             vInvWait.reserve(pto->vInventoryToSend.size());
2727             foreach(const CInv& inv, pto->vInventoryToSend)
2728             {
2729                 if (pto->setInventoryKnown.count(inv))
2730                     continue;
2731
2732                 // trickle out tx inv to protect privacy
2733                 if (inv.type == MSG_TX && !fSendTrickle)
2734                 {
2735                     // 1/4 of tx invs blast to all immediately
2736                     static uint256 hashSalt;
2737                     if (hashSalt == 0)
2738                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2739                     uint256 hashRand = inv.hash ^ hashSalt;
2740                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2741                     bool fTrickleWait = ((hashRand & 3) != 0);
2742
2743                     // always trickle our own transactions
2744                     if (!fTrickleWait)
2745                     {
2746                         TRY_CRITICAL_BLOCK(cs_mapWallet)
2747                         {
2748                             map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2749                             if (mi != mapWallet.end())
2750                             {
2751                                 CWalletTx& wtx = (*mi).second;
2752                                 if (wtx.fFromMe)
2753                                     fTrickleWait = true;
2754                             }
2755                         }
2756                     }
2757
2758                     if (fTrickleWait)
2759                     {
2760                         vInvWait.push_back(inv);
2761                         continue;
2762                     }
2763                 }
2764
2765                 // returns true if wasn't already contained in the set
2766                 if (pto->setInventoryKnown.insert(inv).second)
2767                 {
2768                     vInv.push_back(inv);
2769                     if (vInv.size() >= 1000)
2770                     {
2771                         pto->PushMessage("inv", vInv);
2772                         vInv.clear();
2773                     }
2774                 }
2775             }
2776             pto->vInventoryToSend = vInvWait;
2777         }
2778         if (!vInv.empty())
2779             pto->PushMessage("inv", vInv);
2780
2781
2782         //
2783         // Message: getdata
2784         //
2785         vector<CInv> vGetData;
2786         int64 nNow = GetTime() * 1000000;
2787         CTxDB txdb("r");
2788         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2789         {
2790             const CInv& inv = (*pto->mapAskFor.begin()).second;
2791             if (!AlreadyHave(txdb, inv))
2792             {
2793                 printf("sending getdata: %s\n", inv.ToString().c_str());
2794                 vGetData.push_back(inv);
2795                 if (vGetData.size() >= 1000)
2796                 {
2797                     pto->PushMessage("getdata", vGetData);
2798                     vGetData.clear();
2799                 }
2800             }
2801             pto->mapAskFor.erase(pto->mapAskFor.begin());
2802         }
2803         if (!vGetData.empty())
2804             pto->PushMessage("getdata", vGetData);
2805
2806     }
2807     return true;
2808 }
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823 //////////////////////////////////////////////////////////////////////////////
2824 //
2825 // BitcoinMiner
2826 //
2827
2828 void GenerateBitcoins(bool fGenerate)
2829 {
2830     if (fGenerateBitcoins != fGenerate)
2831     {
2832         fGenerateBitcoins = fGenerate;
2833         CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2834         MainFrameRepaint();
2835     }
2836     if (fGenerateBitcoins)
2837     {
2838         int nProcessors = boost::thread::hardware_concurrency();
2839         printf("%d processors\n", nProcessors);
2840         if (nProcessors < 1)
2841             nProcessors = 1;
2842         if (fLimitProcessors && nProcessors > nLimitProcessors)
2843             nProcessors = nLimitProcessors;
2844         int nAddThreads = nProcessors - vnThreadsRunning[3];
2845         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2846         for (int i = 0; i < nAddThreads; i++)
2847         {
2848             if (!CreateThread(ThreadBitcoinMiner, NULL))
2849                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2850             Sleep(10);
2851         }
2852     }
2853 }
2854
2855 void ThreadBitcoinMiner(void* parg)
2856 {
2857     try
2858     {
2859         vnThreadsRunning[3]++;
2860         BitcoinMiner();
2861         vnThreadsRunning[3]--;
2862     }
2863     catch (std::exception& e) {
2864         vnThreadsRunning[3]--;
2865         PrintException(&e, "ThreadBitcoinMiner()");
2866     } catch (...) {
2867         vnThreadsRunning[3]--;
2868         PrintException(NULL, "ThreadBitcoinMiner()");
2869     }
2870     UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
2871     nHPSTimerStart = 0;
2872     if (vnThreadsRunning[3] == 0)
2873         dHashesPerSec = 0;
2874     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2875 }
2876
2877 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2878 void CallCPUID(int in, int& aret, int& cret)
2879 {
2880     int a, c;
2881     asm (
2882         "mov %2, %%eax; " // in into eax
2883         "cpuid;"
2884         "mov %%eax, %0;" // eax into a
2885         "mov %%ecx, %1;" // eax into c
2886         :"=r"(a),"=r"(c) /* output */
2887         :"r"(in) /* input */
2888         :"%eax","%ecx" /* clobbered register */
2889     );
2890     aret = a;
2891     cret = c;
2892 }
2893
2894 bool Detect128BitSSE2()
2895 {
2896     int a, c, nBrand;
2897     CallCPUID(0, a, nBrand);
2898     bool fIntel = (nBrand == 0x6c65746e); // ntel
2899     bool fAMD = (nBrand == 0x444d4163); // cAMD
2900
2901     struct
2902     {
2903         unsigned int nStepping : 4;
2904         unsigned int nModel : 4;
2905         unsigned int nFamily : 4;
2906         unsigned int nProcessorType : 2;
2907         unsigned int nUnused : 2;
2908         unsigned int nExtendedModel : 4;
2909         unsigned int nExtendedFamily : 8;
2910     }
2911     cpu;
2912     CallCPUID(1, a, c);
2913     memcpy(&cpu, &a, sizeof(cpu));
2914     int nFamily = cpu.nExtendedFamily + cpu.nFamily;
2915     int nModel = cpu.nExtendedModel*16 + cpu.nModel;
2916
2917     // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
2918     // Nehalem = i3/i5/i7 and some Xeon
2919     // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
2920     //  Intel Core i5  family 6, model 26 or 30
2921     //  Intel Core i7  family 6, model 26 or 30
2922     //  Intel Core i3  family 6, model 37
2923     //  AMD Phenom    family 16, model 10
2924     bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >=  60026) ||
2925                      (fAMD   && nFamily * 10000 + nModel >= 160010));
2926
2927     // AMD reports a lower model number in 64-bit mode
2928     if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
2929         fUseSSE2 = true;
2930
2931     static bool fPrinted;
2932     if (!fPrinted)
2933     {
2934         fPrinted = true;
2935         printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
2936     }
2937     return fUseSSE2;
2938 }
2939 #else
2940 bool Detect128BitSSE2() { return false; }
2941 #endif
2942
2943 int FormatHashBlocks(void* pbuffer, unsigned int len)
2944 {
2945     unsigned char* pdata = (unsigned char*)pbuffer;
2946     unsigned int blocks = 1 + ((len + 8) / 64);
2947     unsigned char* pend = pdata + 64 * blocks;
2948     memset(pdata + len, 0, 64 * blocks - len);
2949     pdata[len] = 0x80;
2950     unsigned int bits = len * 8;
2951     pend[-1] = (bits >> 0) & 0xff;
2952     pend[-2] = (bits >> 8) & 0xff;
2953     pend[-3] = (bits >> 16) & 0xff;
2954     pend[-4] = (bits >> 24) & 0xff;
2955     return blocks;
2956 }
2957
2958 using CryptoPP::ByteReverse;
2959
2960 static const unsigned int pSHA256InitState[8] =
2961 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2962
2963 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2964 {
2965     memcpy(pstate, pinit, 32);
2966     CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2967 }
2968
2969 //
2970 // ScanHash scans nonces looking for a hash with at least some zero bits.
2971 // It operates on big endian data.  Caller does the byte reversing.
2972 // All input buffers are 16-byte aligned.  nNonce is usually preserved
2973 // between calls, but periodically or if nNonce is above 0xff000000,
2974 // the block is rebuilt and nNonce starts over at zero.
2975 //
2976 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone)
2977 {
2978     unsigned int& nNonce = *(unsigned int*)(pblock + 12);
2979     for (;;)
2980     {
2981         // Crypto++ SHA-256
2982         // Hash pblock using pmidstate as the starting state into
2983         // preformatted buffer phash1, then hash phash1 into phash
2984         nNonce++;
2985         SHA256Transform(phash1, pblock, pmidstate);
2986         SHA256Transform(phash, phash1, pSHA256InitState);
2987
2988         // Return the nonce if the hash has at least some zero bits,
2989         // caller will check if it has enough to reach the target
2990         if (((unsigned short*)phash)[14] == 0)
2991             return nNonce;
2992
2993         // If nothing found after trying for a while, return -1
2994         if ((nNonce & 0xffff) == 0)
2995         {
2996             nHashesDone = 0xffff+1;
2997             return -1;
2998         }
2999     }
3000 }
3001
3002 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
3003
3004
3005
3006
3007 void BitcoinMiner()
3008 {
3009     printf("BitcoinMiner started\n");
3010     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3011     bool f4WaySSE2 = Detect128BitSSE2();
3012     if (mapArgs.count("-4way"))
3013         f4WaySSE2 = (mapArgs["-4way"] != "0");
3014
3015     CReserveKey reservekey;
3016     unsigned int nExtraNonce = 0;
3017     int64 nPrevTime = 0;
3018     while (fGenerateBitcoins)
3019     {
3020         if (AffinityBugWorkaround(ThreadBitcoinMiner))
3021             return;
3022         if (fShutdown)
3023             return;
3024         while (vNodes.empty() || IsInitialBlockDownload())
3025         {
3026             Sleep(1000);
3027             if (fShutdown)
3028                 return;
3029             if (!fGenerateBitcoins)
3030                 return;
3031         }
3032
3033         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3034         CBlockIndex* pindexPrev = pindexBest;
3035         unsigned int nBits = GetNextWorkRequired(pindexPrev);
3036
3037
3038         //
3039         // Create coinbase tx
3040         //
3041         CTransaction txNew;
3042         txNew.vin.resize(1);
3043         txNew.vin[0].prevout.SetNull();
3044         int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3045         if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3046         {
3047             nExtraNonce = 1;
3048             nPrevTime = nNow;
3049         }
3050         txNew.vin[0].scriptSig << nBits << CBigNum(nExtraNonce);
3051         txNew.vout.resize(1);
3052         txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3053
3054
3055         //
3056         // Create new block
3057         //
3058         auto_ptr<CBlock> pblock(new CBlock());
3059         if (!pblock.get())
3060             return;
3061
3062         // Add our coinbase tx as first transaction
3063         pblock->vtx.push_back(txNew);
3064
3065         // Collect memory pool transactions into the block
3066         int64 nFees = 0;
3067         CRITICAL_BLOCK(cs_main)
3068         CRITICAL_BLOCK(cs_mapTransactions)
3069         {
3070             CTxDB txdb("r");
3071             map<uint256, CTxIndex> mapTestPool;
3072             vector<char> vfAlreadyAdded(mapTransactions.size());
3073             uint64 nBlockSize = 1000;
3074             int nBlockSigOps = 100;
3075             bool fFoundSomething = true;
3076             while (fFoundSomething)
3077             {
3078                 fFoundSomething = false;
3079                 unsigned int n = 0;
3080                 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
3081                 {
3082                     if (vfAlreadyAdded[n])
3083                         continue;
3084                     CTransaction& tx = (*mi).second;
3085                     if (tx.IsCoinBase() || !tx.IsFinal())
3086                         continue;
3087                     unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3088                     if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3089                         continue;
3090                     int nTxSigOps = tx.GetSigOpCount();
3091                     if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3092                         continue;
3093
3094                     // Transaction fee based on block size
3095                     int64 nMinFee = tx.GetMinFee(nBlockSize);
3096
3097                     map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3098                     if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3099                         continue;
3100                     swap(mapTestPool, mapTestPoolTmp);
3101
3102                     pblock->vtx.push_back(tx);
3103                     nBlockSize += nTxSize;
3104                     nBlockSigOps += nTxSigOps;
3105                     vfAlreadyAdded[n] = true;
3106                     fFoundSomething = true;
3107                 }
3108             }
3109         }
3110         pblock->nBits = nBits;
3111         pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3112         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3113
3114
3115         //
3116         // Prebuild hash buffer
3117         //
3118         struct tmpworkspace
3119         {
3120             struct unnamed2
3121             {
3122                 int nVersion;
3123                 uint256 hashPrevBlock;
3124                 uint256 hashMerkleRoot;
3125                 unsigned int nTime;
3126                 unsigned int nBits;
3127                 unsigned int nNonce;
3128             }
3129             block;
3130             unsigned char pchPadding0[64];
3131             uint256 hash1;
3132             unsigned char pchPadding1[64];
3133         };
3134         char tmpbuf[sizeof(tmpworkspace)+16];
3135         tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
3136
3137         tmp.block.nVersion       = pblock->nVersion;
3138         tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
3139         tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3140         tmp.block.nTime          = pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3141         tmp.block.nBits          = pblock->nBits          = nBits;
3142         tmp.block.nNonce         = pblock->nNonce         = 0;
3143
3144         unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3145         unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3146
3147         // Byte swap all the input buffer
3148         for (int i = 0; i < sizeof(tmp)/4; i++)
3149             ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3150
3151         // Precalc the first half of the first hash, which stays constant
3152         uint256 midstatebuf[2];
3153         uint256& midstate = *alignup<16>(midstatebuf);
3154         SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
3155
3156
3157         //
3158         // Search
3159         //
3160         int64 nStart = GetTime();
3161         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3162         uint256 hashbuf[2];
3163         uint256& hash = *alignup<16>(hashbuf);
3164         loop
3165         {
3166             unsigned int nHashesDone = 0;
3167             unsigned int nNonceFound;
3168
3169 #ifdef FOURWAYSSE2
3170             if (f4WaySSE2)
3171                 // tcatm's 4-way 128-bit SSE2 SHA-256
3172                 nNonceFound = ScanHash_4WaySSE2((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3173             else
3174 #endif
3175                 // Crypto++ SHA-256
3176                 nNonceFound = ScanHash_CryptoPP((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3177
3178             // Check if something found
3179             if (nNonceFound != -1)
3180             {
3181                 for (int i = 0; i < sizeof(hash)/4; i++)
3182                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3183
3184                 if (hash <= hashTarget)
3185                 {
3186                     // Found a solution
3187                     pblock->nNonce = ByteReverse(nNonceFound);
3188                     assert(hash == pblock->GetHash());
3189
3190                         //// debug print
3191                         printf("BitcoinMiner:\n");
3192                         printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3193                         pblock->print();
3194                         printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3195                         printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3196
3197                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3198                     CRITICAL_BLOCK(cs_main)
3199                     {
3200                         if (pindexPrev == pindexBest)
3201                         {
3202                             // Remove key from key pool
3203                             reservekey.KeepKey();
3204
3205                             // Track how many getdata requests this block gets
3206                             CRITICAL_BLOCK(cs_mapRequestCount)
3207                                 mapRequestCount[pblock->GetHash()] = 0;
3208
3209                             // Process this block the same as if we had received it from another node
3210                             if (!ProcessBlock(NULL, pblock.release()))
3211                                 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
3212                         }
3213                     }
3214                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3215
3216                     Sleep(500);
3217                     break;
3218                 }
3219             }
3220
3221             // Meter hashes/sec
3222             static int64 nHashCounter;
3223             if (nHPSTimerStart == 0)
3224             {
3225                 nHPSTimerStart = GetTimeMillis();
3226                 nHashCounter = 0;
3227             }
3228             else
3229                 nHashCounter += nHashesDone;
3230             if (GetTimeMillis() - nHPSTimerStart > 4000)
3231             {
3232                 static CCriticalSection cs;
3233                 CRITICAL_BLOCK(cs)
3234                 {
3235                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3236                     {
3237                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3238                         nHPSTimerStart = GetTimeMillis();
3239                         nHashCounter = 0;
3240                         string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
3241                         UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3242                         static int64 nLogTime;
3243                         if (GetTime() - nLogTime > 30 * 60)
3244                         {
3245                             nLogTime = GetTime();
3246                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3247                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3248                         }
3249                     }
3250                 }
3251             }
3252
3253             // Check for stop or if block needs to be rebuilt
3254             if (fShutdown)
3255                 return;
3256             if (!fGenerateBitcoins)
3257                 return;
3258             if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3259                 return;
3260             if (vNodes.empty())
3261                 break;
3262             if (tmp.block.nNonce >= 0xff000000)
3263                 break;
3264             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3265                 break;
3266             if (pindexPrev != pindexBest)
3267                 break;
3268
3269             // Update nTime every few seconds
3270             pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3271             tmp.block.nTime = ByteReverse(pblock->nTime);
3272         }
3273     }
3274 }
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293 //////////////////////////////////////////////////////////////////////////////
3294 //
3295 // Actions
3296 //
3297
3298
3299 int64 GetBalance()
3300 {
3301     int64 nStart = GetTimeMillis();
3302
3303     int64 nTotal = 0;
3304     CRITICAL_BLOCK(cs_mapWallet)
3305     {
3306         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3307         {
3308             CWalletTx* pcoin = &(*it).second;
3309             if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3310                 continue;
3311             nTotal += pcoin->GetCredit(true);
3312         }
3313     }
3314
3315     //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3316     return nTotal;
3317 }
3318
3319
3320 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3321 {
3322     setCoinsRet.clear();
3323
3324     // List of values less than target
3325     int64 nLowestLarger = INT64_MAX;
3326     CWalletTx* pcoinLowestLarger = NULL;
3327     vector<pair<int64, CWalletTx*> > vValue;
3328     int64 nTotalLower = 0;
3329
3330     CRITICAL_BLOCK(cs_mapWallet)
3331     {
3332        vector<CWalletTx*> vCoins;
3333        vCoins.reserve(mapWallet.size());
3334        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3335            vCoins.push_back(&(*it).second);
3336        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3337
3338        foreach(CWalletTx* pcoin, vCoins)
3339        {
3340             if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3341                 continue;
3342             int64 n = pcoin->GetCredit();
3343             if (n <= 0)
3344                 continue;
3345             if (n < nTargetValue)
3346             {
3347                 vValue.push_back(make_pair(n, pcoin));
3348                 nTotalLower += n;
3349             }
3350             else if (n == nTargetValue)
3351             {
3352                 setCoinsRet.insert(pcoin);
3353                 return true;
3354             }
3355             else if (n < nLowestLarger)
3356             {
3357                 nLowestLarger = n;
3358                 pcoinLowestLarger = pcoin;
3359             }
3360         }
3361     }
3362
3363     if (nTotalLower < nTargetValue)
3364     {
3365         if (pcoinLowestLarger == NULL)
3366             return false;
3367         setCoinsRet.insert(pcoinLowestLarger);
3368         return true;
3369     }
3370
3371     // Solve subset sum by stochastic approximation
3372     sort(vValue.rbegin(), vValue.rend());
3373     vector<char> vfIncluded;
3374     vector<char> vfBest(vValue.size(), true);
3375     int64 nBest = nTotalLower;
3376
3377     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3378     {
3379         vfIncluded.assign(vValue.size(), false);
3380         int64 nTotal = 0;
3381         bool fReachedTarget = false;
3382         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3383         {
3384             for (int i = 0; i < vValue.size(); i++)
3385             {
3386                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3387                 {
3388                     nTotal += vValue[i].first;
3389                     vfIncluded[i] = true;
3390                     if (nTotal >= nTargetValue)
3391                     {
3392                         fReachedTarget = true;
3393                         if (nTotal < nBest)
3394                         {
3395                             nBest = nTotal;
3396                             vfBest = vfIncluded;
3397                         }
3398                         nTotal -= vValue[i].first;
3399                         vfIncluded[i] = false;
3400                     }
3401                 }
3402             }
3403         }
3404     }
3405
3406     // If the next larger is still closer, return it
3407     if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3408         setCoinsRet.insert(pcoinLowestLarger);
3409     else
3410     {
3411         for (int i = 0; i < vValue.size(); i++)
3412             if (vfBest[i])
3413                 setCoinsRet.insert(vValue[i].second);
3414
3415         //// debug print
3416         printf("SelectCoins() best subset: ");
3417         for (int i = 0; i < vValue.size(); i++)
3418             if (vfBest[i])
3419                 printf("%s ", FormatMoney(vValue[i].first).c_str());
3420         printf("total %s\n", FormatMoney(nBest).c_str());
3421     }
3422
3423     return true;
3424 }
3425
3426
3427
3428
3429 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRequiredRet)
3430 {
3431     nFeeRequiredRet = 0;
3432     CRITICAL_BLOCK(cs_main)
3433     {
3434         // txdb must be opened before the mapWallet lock
3435         CTxDB txdb("r");
3436         CRITICAL_BLOCK(cs_mapWallet)
3437         {
3438             int64 nFee = nTransactionFee;
3439             loop
3440             {
3441                 wtxNew.vin.clear();
3442                 wtxNew.vout.clear();
3443                 wtxNew.fFromMe = true;
3444                 if (nValue < 0)
3445                     return false;
3446                 int64 nValueOut = nValue;
3447                 int64 nTotalValue = nValue + nFee;
3448
3449                 // Choose coins to use
3450                 set<CWalletTx*> setCoins;
3451                 if (!SelectCoins(nTotalValue, setCoins))
3452                     return false;
3453                 int64 nValueIn = 0;
3454                 foreach(CWalletTx* pcoin, setCoins)
3455                     nValueIn += pcoin->GetCredit();
3456
3457                 // Fill a vout to the payee
3458                 bool fChangeFirst = GetRand(2);
3459                 if (!fChangeFirst)
3460                     wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3461
3462                 // Fill a vout back to self with any change
3463                 int64 nChange = nValueIn - nTotalValue;
3464                 if (nChange >= CENT)
3465                 {
3466                     // Note: We use a new key here to keep it from being obvious which side is the change.
3467                     //  The drawback is that by not reusing a previous key, the change may be lost if a
3468                     //  backup is restored, if the backup doesn't have the new private key for the change.
3469                     //  If we reused the old key, it would be possible to add code to look for and
3470                     //  rediscover unknown transactions that were written with keys of ours to recover
3471                     //  post-backup change.
3472
3473                     // Reserve a new key pair from key pool
3474                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3475                     assert(mapKeys.count(vchPubKey));
3476
3477                     // Fill a vout to ourself, using same address type as the payment
3478                     CScript scriptChange;
3479                     if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3480                         scriptChange.SetBitcoinAddress(vchPubKey);
3481                     else
3482                         scriptChange << vchPubKey << OP_CHECKSIG;
3483                     wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3484                 }
3485                 else
3486                     reservekey.ReturnKey();
3487
3488                 // Fill a vout to the payee
3489                 if (fChangeFirst)
3490                     wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3491
3492                 // Fill vin
3493                 foreach(CWalletTx* pcoin, setCoins)
3494                     for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3495                         if (pcoin->vout[nOut].IsMine())
3496                             wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3497
3498                 // Sign
3499                 int nIn = 0;
3500                 foreach(CWalletTx* pcoin, setCoins)
3501                     for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3502                         if (pcoin->vout[nOut].IsMine())
3503                             if (!SignSignature(*pcoin, wtxNew, nIn++))
3504                                 return false;
3505
3506                 // Limit size
3507                 if (::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK) >= MAX_BLOCK_SIZE_GEN/5)
3508                     return false;
3509
3510                 // Check that enough fee is included
3511                 if (nFee < wtxNew.GetMinFee())
3512                 {
3513                     nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3514                     continue;
3515                 }
3516
3517                 // Fill vtxPrev by copying from previous transactions vtxPrev
3518                 wtxNew.AddSupportingTransactions(txdb);
3519                 wtxNew.fTimeReceivedIsTxTime = true;
3520
3521                 break;
3522             }
3523         }
3524     }
3525     return true;
3526 }
3527
3528 // Call after CreateTransaction unless you want to abort
3529 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3530 {
3531     CRITICAL_BLOCK(cs_main)
3532     {
3533         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3534         CRITICAL_BLOCK(cs_mapWallet)
3535         {
3536             // This is only to keep the database open to defeat the auto-flush for the
3537             // duration of this scope.  This is the only place where this optimization
3538             // maybe makes sense; please don't do it anywhere else.
3539             CWalletDB walletdb("r");
3540
3541             // Take key pair from key pool so it won't be used again
3542             reservekey.KeepKey();
3543
3544             // Add tx to wallet, because if it has change it's also ours,
3545             // otherwise just for transaction history.
3546             AddToWallet(wtxNew);
3547
3548             // Mark old coins as spent
3549             set<CWalletTx*> setCoins;
3550             foreach(const CTxIn& txin, wtxNew.vin)
3551                 setCoins.insert(&mapWallet[txin.prevout.hash]);
3552             foreach(CWalletTx* pcoin, setCoins)
3553             {
3554                 pcoin->fSpent = true;
3555                 pcoin->WriteToDisk();
3556                 vWalletUpdated.push_back(pcoin->GetHash());
3557             }
3558         }
3559
3560         // Track how many getdata requests our transaction gets
3561         CRITICAL_BLOCK(cs_mapRequestCount)
3562             mapRequestCount[wtxNew.GetHash()] = 0;
3563
3564         // Broadcast
3565         if (!wtxNew.AcceptToMemoryPool())
3566         {
3567             // This must not fail. The transaction has already been signed and recorded.
3568             printf("CommitTransaction() : Error: Transaction not valid");
3569             return false;
3570         }
3571         wtxNew.RelayWalletTransaction();
3572     }
3573     MainFrameRepaint();
3574     return true;
3575 }
3576
3577
3578
3579
3580 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3581 {
3582     CRITICAL_BLOCK(cs_main)
3583     {
3584         CReserveKey reservekey;
3585         int64 nFeeRequired;
3586         if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3587         {
3588             string strError;
3589             if (nValue + nFeeRequired > GetBalance())
3590                 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s  "), FormatMoney(nFeeRequired).c_str());
3591             else
3592                 strError = _("Error: Transaction creation failed  ");
3593             printf("SendMoney() : %s", strError.c_str());
3594             return strError;
3595         }
3596
3597         if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3598             return "ABORTED";
3599
3600         if (!CommitTransaction(wtxNew, reservekey))
3601             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.");
3602     }
3603     MainFrameRepaint();
3604     return "";
3605 }
3606
3607
3608
3609 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3610 {
3611     // Check amount
3612     if (nValue <= 0)
3613         return _("Invalid amount");
3614     if (nValue + nTransactionFee > GetBalance())
3615         return _("Insufficient funds");
3616
3617     // Parse bitcoin address
3618     CScript scriptPubKey;
3619     if (!scriptPubKey.SetBitcoinAddress(strAddress))
3620         return _("Invalid bitcoin address");
3621
3622     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
3623 }