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