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