Advertisement
Guest User

BTC/bitmox code original

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