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