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