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