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