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