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