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