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