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