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