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