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