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