Advertisement
Guest User

Modification where a light version of "PoSign" was added

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