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