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