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