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