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