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