Advertisement
Guest User

Genesis block

a guest
May 25th, 2018
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 105.52 KB | None | 0 0
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
  4.  
  5. #include "headers.h"
  6. #include "cryptopp/sha.h"
  7.  
  8.  
  9.  
  10.  
  11.  
  12. //
  13. // Global state
  14. //
  15.  
  16. CCriticalSection cs_main;
  17.  
  18. map<uint256, CTransaction> mapTransactions;
  19. CCriticalSection cs_mapTransactions;
  20. unsigned int nTransactionsUpdated = 0;
  21. map<COutPoint, CInPoint> mapNextTx;
  22.  
  23. map<uint256, CBlockIndex*> mapBlockIndex;
  24. const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
  25. CBlockIndex* pindexGenesisBlock = NULL;
  26. int nBestHeight = -1;
  27. CBigNum bnBestChainWork = 0;
  28. CBigNum bnBestInvalidWork = 0;
  29. uint256 hashBestChain = 0;
  30. CBlockIndex* pindexBest = NULL;
  31. int64 nTimeBestReceived = 0;
  32.  
  33. map<uint256, CBlock*> mapOrphanBlocks;
  34. multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
  35.  
  36. map<uint256, CDataStream*> mapOrphanTransactions;
  37. multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
  38.  
  39. map<uint256, CWalletTx> mapWallet;
  40. vector<uint256> vWalletUpdated;
  41. CCriticalSection cs_mapWallet;
  42.  
  43. map<vector<unsigned char>, CPrivKey> mapKeys;
  44. map<uint160, vector<unsigned char> > mapPubKeys;
  45. CCriticalSection cs_mapKeys;
  46. CKey keyUser;
  47.  
  48. map<uint256, int> mapRequestCount;
  49. CCriticalSection cs_mapRequestCount;
  50.  
  51. map<string, string> mapAddressBook;
  52. CCriticalSection cs_mapAddressBook;
  53.  
  54. vector<unsigned char> vchDefaultKey;
  55.  
  56. double dHashesPerSec;
  57. int64 nHPSTimerStart;
  58.  
  59. // Settings
  60. int fGenerateBitcoins = false;
  61. int64 nTransactionFee = 0;
  62. CAddress addrIncoming;
  63. int fLimitProcessors = false;
  64. int nLimitProcessors = 1;
  65. int fMinimizeToTray = true;
  66. int fMinimizeOnClose = true;
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73. //////////////////////////////////////////////////////////////////////////////
  74. //
  75. // mapKeys
  76. //
  77.  
  78. bool AddKey(const CKey& key)
  79. {
  80.     CRITICAL_BLOCK(cs_mapKeys)
  81.     {
  82.         mapKeys[key.GetPubKey()] = key.GetPrivKey();
  83.         mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
  84.     }
  85.     return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
  86. }
  87.  
  88. vector<unsigned char> GenerateNewKey()
  89. {
  90.     RandAddSeedPerfmon();
  91.     CKey key;
  92.     key.MakeNewKey();
  93.     if (!AddKey(key))
  94.         throw runtime_error("GenerateNewKey() : AddKey failed\n");
  95.     return key.GetPubKey();
  96. }
  97.  
  98.  
  99.  
  100.  
  101. //////////////////////////////////////////////////////////////////////////////
  102. //
  103. // mapWallet
  104. //
  105.  
  106. bool AddToWallet(const CWalletTx& wtxIn)
  107. {
  108.     uint256 hash = wtxIn.GetHash();
  109.     CRITICAL_BLOCK(cs_mapWallet)
  110.     {
  111.         // Inserts only if not already there, returns tx inserted or tx found
  112.         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
  113.         CWalletTx& wtx = (*ret.first).second;
  114.         bool fInsertedNew = ret.second;
  115.         if (fInsertedNew)
  116.             wtx.nTimeReceived = GetAdjustedTime();
  117.  
  118.         bool fUpdated = false;
  119.         if (!fInsertedNew)
  120.         {
  121.             // Merge
  122.             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
  123.             {
  124.                 wtx.hashBlock = wtxIn.hashBlock;
  125.                 fUpdated = true;
  126.             }
  127.             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
  128.             {
  129.                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
  130.                 wtx.nIndex = wtxIn.nIndex;
  131.                 fUpdated = true;
  132.             }
  133.             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
  134.             {
  135.                 wtx.fFromMe = wtxIn.fFromMe;
  136.                 fUpdated = true;
  137.             }
  138.             if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
  139.             {
  140.                 wtx.fSpent = wtxIn.fSpent;
  141.                 fUpdated = true;
  142.             }
  143.         }
  144.  
  145.         //// debug print
  146.         printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
  147.  
  148.         // Write to disk
  149.         if (fInsertedNew || fUpdated)
  150.             if (!wtx.WriteToDisk())
  151.                 return false;
  152.  
  153.         // If default receiving address gets used, replace it with a new one
  154.         CScript scriptDefaultKey;
  155.         scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
  156.         foreach(const CTxOut& txout, wtx.vout)
  157.         {
  158.             if (txout.scriptPubKey == scriptDefaultKey)
  159.             {
  160.                 CWalletDB walletdb;
  161.                 walletdb.WriteDefaultKey(GenerateNewKey());
  162.                 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
  163.             }
  164.         }
  165.  
  166.         // Notify UI
  167.         vWalletUpdated.push_back(hash);
  168.     }
  169.  
  170.     // Refresh UI
  171.     MainFrameRepaint();
  172.     return true;
  173. }
  174.  
  175. bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
  176. {
  177.     if (tx.IsMine() || mapWallet.count(tx.GetHash()))
  178.     {
  179.         CWalletTx wtx(tx);
  180.         // Get merkle branch if transaction was found in a block
  181.         if (pblock)
  182.             wtx.SetMerkleBranch(pblock);
  183.         return AddToWallet(wtx);
  184.     }
  185.     return true;
  186. }
  187.  
  188. bool EraseFromWallet(uint256 hash)
  189. {
  190.     CRITICAL_BLOCK(cs_mapWallet)
  191.     {
  192.         if (mapWallet.erase(hash))
  193.             CWalletDB().EraseTx(hash);
  194.     }
  195.     return true;
  196. }
  197.  
  198. void WalletUpdateSpent(const COutPoint& prevout)
  199. {
  200.     // Anytime a signature is successfully verified, it's proof the outpoint is spent.
  201.     // Update the wallet spent flag if it doesn't know due to wallet.dat being
  202.     // restored from backup or the user making copies of wallet.dat.
  203.     CRITICAL_BLOCK(cs_mapWallet)
  204.     {
  205.         map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
  206.         if (mi != mapWallet.end())
  207.         {
  208.             CWalletTx& wtx = (*mi).second;
  209.             if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
  210.             {
  211.                 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
  212.                 wtx.fSpent = true;
  213.                 wtx.WriteToDisk();
  214.                 vWalletUpdated.push_back(prevout.hash);
  215.             }
  216.         }
  217.     }
  218. }
  219.  
  220.  
  221.  
  222.  
  223.  
  224.  
  225.  
  226.  
  227. //////////////////////////////////////////////////////////////////////////////
  228. //
  229. // mapOrphanTransactions
  230. //
  231.  
  232. void AddOrphanTx(const CDataStream& vMsg)
  233. {
  234.     CTransaction tx;
  235.     CDataStream(vMsg) >> tx;
  236.     uint256 hash = tx.GetHash();
  237.     if (mapOrphanTransactions.count(hash))
  238.         return;
  239.     CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
  240.     foreach(const CTxIn& txin, tx.vin)
  241.         mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
  242. }
  243.  
  244. void EraseOrphanTx(uint256 hash)
  245. {
  246.     if (!mapOrphanTransactions.count(hash))
  247.         return;
  248.     const CDataStream* pvMsg = mapOrphanTransactions[hash];
  249.     CTransaction tx;
  250.     CDataStream(*pvMsg) >> tx;
  251.     foreach(const CTxIn& txin, tx.vin)
  252.     {
  253.         for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
  254.              mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
  255.         {
  256.             if ((*mi).second == pvMsg)
  257.                 mapOrphanTransactionsByPrev.erase(mi++);
  258.             else
  259.                 mi++;
  260.         }
  261.     }
  262.     delete pvMsg;
  263.     mapOrphanTransactions.erase(hash);
  264. }
  265.  
  266.  
  267.  
  268.  
  269.  
  270.  
  271.  
  272.  
  273. //////////////////////////////////////////////////////////////////////////////
  274. //
  275. // CTransaction
  276. //
  277.  
  278. bool CTxIn::IsMine() const
  279. {
  280.     CRITICAL_BLOCK(cs_mapWallet)
  281.     {
  282.         map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
  283.         if (mi != mapWallet.end())
  284.         {
  285.             const CWalletTx& prev = (*mi).second;
  286.             if (prevout.n < prev.vout.size())
  287.                 if (prev.vout[prevout.n].IsMine())
  288.                     return true;
  289.         }
  290.     }
  291.     return false;
  292. }
  293.  
  294. int64 CTxIn::GetDebit() const
  295. {
  296.     CRITICAL_BLOCK(cs_mapWallet)
  297.     {
  298.         map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
  299.         if (mi != mapWallet.end())
  300.         {
  301.             const CWalletTx& prev = (*mi).second;
  302.             if (prevout.n < prev.vout.size())
  303.                 if (prev.vout[prevout.n].IsMine())
  304.                     return prev.vout[prevout.n].nValue;
  305.         }
  306.     }
  307.     return 0;
  308. }
  309.  
  310. int64 CWalletTx::GetTxTime() const
  311. {
  312.     if (!fTimeReceivedIsTxTime && hashBlock != 0)
  313.     {
  314.         // If we did not receive the transaction directly, we rely on the block's
  315.         // time to figure out when it happened.  We use the median over a range
  316.         // of blocks to try to filter out inaccurate block times.
  317.         map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  318.         if (mi != mapBlockIndex.end())
  319.         {
  320.             CBlockIndex* pindex = (*mi).second;
  321.             if (pindex)
  322.                 return pindex->GetMedianTime();
  323.         }
  324.     }
  325.     return nTimeReceived;
  326. }
  327.  
  328. int CWalletTx::GetRequestCount() const
  329. {
  330.     // Returns -1 if it wasn't being tracked
  331.     int nRequests = -1;
  332.     CRITICAL_BLOCK(cs_mapRequestCount)
  333.     {
  334.         if (IsCoinBase())
  335.         {
  336.             // Generated block
  337.             if (hashBlock != 0)
  338.             {
  339.                 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
  340.                 if (mi != mapRequestCount.end())
  341.                     nRequests = (*mi).second;
  342.             }
  343.         }
  344.         else
  345.         {
  346.             // Did anyone request this transaction?
  347.             map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
  348.             if (mi != mapRequestCount.end())
  349.             {
  350.                 nRequests = (*mi).second;
  351.  
  352.                 // How about the block it's in?
  353.                 if (nRequests == 0 && hashBlock != 0)
  354.                 {
  355.                     map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
  356.                     if (mi != mapRequestCount.end())
  357.                         nRequests = (*mi).second;
  358.                     else
  359.                         nRequests = 1; // If it's in someone else's block it must have got out
  360.                 }
  361.             }
  362.         }
  363.     }
  364.     return nRequests;
  365. }
  366.  
  367.  
  368.  
  369.  
  370. int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
  371. {
  372.     if (fClient)
  373.     {
  374.         if (hashBlock == 0)
  375.             return 0;
  376.     }
  377.     else
  378.     {
  379.         CBlock blockTmp;
  380.         if (pblock == NULL)
  381.         {
  382.             // Load the block this tx is in
  383.             CTxIndex txindex;
  384.             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
  385.                 return 0;
  386.             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
  387.                 return 0;
  388.             pblock = &blockTmp;
  389.         }
  390.  
  391.         // Update the tx's hashBlock
  392.         hashBlock = pblock->GetHash();
  393.  
  394.         // Locate the transaction
  395.         for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
  396.             if (pblock->vtx[nIndex] == *(CTransaction*)this)
  397.                 break;
  398.         if (nIndex == pblock->vtx.size())
  399.         {
  400.             vMerkleBranch.clear();
  401.             nIndex = -1;
  402.             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
  403.             return 0;
  404.         }
  405.  
  406.         // Fill in merkle branch
  407.         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
  408.     }
  409.  
  410.     // Is the tx in a block that's in the main chain
  411.     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  412.     if (mi == mapBlockIndex.end())
  413.         return 0;
  414.     CBlockIndex* pindex = (*mi).second;
  415.     if (!pindex || !pindex->IsInMainChain())
  416.         return 0;
  417.  
  418.     return pindexBest->nHeight - pindex->nHeight + 1;
  419. }
  420.  
  421.  
  422.  
  423. void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
  424. {
  425.     vtxPrev.clear();
  426.  
  427.     const int COPY_DEPTH = 3;
  428.     if (SetMerkleBranch() < COPY_DEPTH)
  429.     {
  430.         vector<uint256> vWorkQueue;
  431.         foreach(const CTxIn& txin, vin)
  432.             vWorkQueue.push_back(txin.prevout.hash);
  433.  
  434.         // This critsect is OK because txdb is already open
  435.         CRITICAL_BLOCK(cs_mapWallet)
  436.         {
  437.             map<uint256, const CMerkleTx*> mapWalletPrev;
  438.             set<uint256> setAlreadyDone;
  439.             for (int i = 0; i < vWorkQueue.size(); i++)
  440.             {
  441.                 uint256 hash = vWorkQueue[i];
  442.                 if (setAlreadyDone.count(hash))
  443.                     continue;
  444.                 setAlreadyDone.insert(hash);
  445.  
  446.                 CMerkleTx tx;
  447.                 if (mapWallet.count(hash))
  448.                 {
  449.                     tx = mapWallet[hash];
  450.                     foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
  451.                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
  452.                 }
  453.                 else if (mapWalletPrev.count(hash))
  454.                 {
  455.                     tx = *mapWalletPrev[hash];
  456.                 }
  457.                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
  458.                 {
  459.                     ;
  460.                 }
  461.                 else
  462.                 {
  463.                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
  464.                     continue;
  465.                 }
  466.  
  467.                 int nDepth = tx.SetMerkleBranch();
  468.                 vtxPrev.push_back(tx);
  469.  
  470.                 if (nDepth < COPY_DEPTH)
  471.                     foreach(const CTxIn& txin, tx.vin)
  472.                         vWorkQueue.push_back(txin.prevout.hash);
  473.             }
  474.         }
  475.     }
  476.  
  477.     reverse(vtxPrev.begin(), vtxPrev.end());
  478. }
  479.  
  480.  
  481.  
  482.  
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490. bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
  491. {
  492.     if (pfMissingInputs)
  493.         *pfMissingInputs = false;
  494.  
  495.     // Coinbase is only valid in a block, not as a loose transaction
  496.     if (IsCoinBase())
  497.         return error("AcceptTransaction() : coinbase as individual tx");
  498.  
  499.     if (!CheckTransaction())
  500.         return error("AcceptTransaction() : CheckTransaction failed");
  501.  
  502.     // To help v0.1.5 clients who would see it as a negative number
  503.     if (nLockTime > INT_MAX)
  504.         return error("AcceptTransaction() : not accepting nLockTime beyond 2038");
  505.  
  506.     // Do we already have it?
  507.     uint256 hash = GetHash();
  508.     CRITICAL_BLOCK(cs_mapTransactions)
  509.         if (mapTransactions.count(hash))
  510.             return false;
  511.     if (fCheckInputs)
  512.         if (txdb.ContainsTx(hash))
  513.             return false;
  514.  
  515.     // Check for conflicts with in-memory transactions
  516.     CTransaction* ptxOld = NULL;
  517.     for (int i = 0; i < vin.size(); i++)
  518.     {
  519.         COutPoint outpoint = vin[i].prevout;
  520.         if (mapNextTx.count(outpoint))
  521.         {
  522.             // Allow replacing with a newer version of the same transaction
  523.             if (i != 0)
  524.                 return false;
  525.             ptxOld = mapNextTx[outpoint].ptx;
  526.             if (!IsNewerThan(*ptxOld))
  527.                 return false;
  528.             for (int i = 0; i < vin.size(); i++)
  529.             {
  530.                 COutPoint outpoint = vin[i].prevout;
  531.                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
  532.                     return false;
  533.             }
  534.             break;
  535.         }
  536.     }
  537.  
  538.     // Check against previous transactions
  539.     map<uint256, CTxIndex> mapUnused;
  540.     int64 nFees = 0;
  541.     if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
  542.     {
  543.         if (pfMissingInputs)
  544.             *pfMissingInputs = true;
  545.         return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());
  546.     }
  547.  
  548.     // Store transaction in memory
  549.     CRITICAL_BLOCK(cs_mapTransactions)
  550.     {
  551.         if (ptxOld)
  552.         {
  553.             printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());
  554.             mapTransactions.erase(ptxOld->GetHash());
  555.         }
  556.         AddToMemoryPool();
  557.     }
  558.  
  559.     ///// are we sure this is ok when loading transactions or restoring block txes
  560.     // If updated, erase old tx from wallet
  561.     if (ptxOld)
  562.         EraseFromWallet(ptxOld->GetHash());
  563.  
  564.     printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());
  565.     return true;
  566. }
  567.  
  568.  
  569. bool CTransaction::AddToMemoryPool()
  570. {
  571.     // Add to memory pool without checking anything.  Don't call this directly,
  572.     // call AcceptTransaction to properly check the transaction first.
  573.     CRITICAL_BLOCK(cs_mapTransactions)
  574.     {
  575.         uint256 hash = GetHash();
  576.         mapTransactions[hash] = *this;
  577.         for (int i = 0; i < vin.size(); i++)
  578.             mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
  579.         nTransactionsUpdated++;
  580.     }
  581.     return true;
  582. }
  583.  
  584.  
  585. bool CTransaction::RemoveFromMemoryPool()
  586. {
  587.     // Remove transaction from memory pool
  588.     CRITICAL_BLOCK(cs_mapTransactions)
  589.     {
  590.         foreach(const CTxIn& txin, vin)
  591.             mapNextTx.erase(txin.prevout);
  592.         mapTransactions.erase(GetHash());
  593.         nTransactionsUpdated++;
  594.     }
  595.     return true;
  596. }
  597.  
  598.  
  599.  
  600.  
  601.  
  602.  
  603. int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
  604. {
  605.     if (hashBlock == 0 || nIndex == -1)
  606.         return 0;
  607.  
  608.     // Find the block it claims to be in
  609.     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  610.     if (mi == mapBlockIndex.end())
  611.         return 0;
  612.     CBlockIndex* pindex = (*mi).second;
  613.     if (!pindex || !pindex->IsInMainChain())
  614.         return 0;
  615.  
  616.     // Make sure the merkle branch connects to this block
  617.     if (!fMerkleVerified)
  618.     {
  619.         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
  620.             return 0;
  621.         fMerkleVerified = true;
  622.     }
  623.  
  624.     nHeightRet = pindex->nHeight;
  625.     return pindexBest->nHeight - pindex->nHeight + 1;
  626. }
  627.  
  628.  
  629. int CMerkleTx::GetBlocksToMaturity() const
  630. {
  631.     if (!IsCoinBase())
  632.         return 0;
  633.     return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
  634. }
  635.  
  636.  
  637. bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
  638. {
  639.     if (fClient)
  640.     {
  641.         if (!IsInMainChain() && !ClientConnectInputs())
  642.             return false;
  643.         return CTransaction::AcceptTransaction(txdb, false);
  644.     }
  645.     else
  646.     {
  647.         return CTransaction::AcceptTransaction(txdb, fCheckInputs);
  648.     }
  649. }
  650.  
  651.  
  652.  
  653. bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
  654. {
  655.     CRITICAL_BLOCK(cs_mapTransactions)
  656.     {
  657.         foreach(CMerkleTx& tx, vtxPrev)
  658.         {
  659.             if (!tx.IsCoinBase())
  660.             {
  661.                 uint256 hash = tx.GetHash();
  662.                 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
  663.                     tx.AcceptTransaction(txdb, fCheckInputs);
  664.             }
  665.         }
  666.         if (!IsCoinBase())
  667.             return AcceptTransaction(txdb, fCheckInputs);
  668.     }
  669.     return true;
  670. }
  671.  
  672. void ReacceptWalletTransactions()
  673. {
  674.     CTxDB txdb("r");
  675.     CRITICAL_BLOCK(cs_mapWallet)
  676.     {
  677.         foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
  678.         {
  679.             CWalletTx& wtx = item.second;
  680.             if (wtx.fSpent && wtx.IsCoinBase())
  681.                 continue;
  682.  
  683.             CTxIndex txindex;
  684.             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
  685.             {
  686.                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
  687.                 if (!wtx.fSpent)
  688.                 {
  689.                     if (txindex.vSpent.size() != wtx.vout.size())
  690.                     {
  691.                         printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
  692.                         continue;
  693.                     }
  694.                     for (int i = 0; i < txindex.vSpent.size(); i++)
  695.                     {
  696.                         if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
  697.                         {
  698.                             printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
  699.                             wtx.fSpent = true;
  700.                             wtx.WriteToDisk();
  701.                             break;
  702.                         }
  703.                     }
  704.                 }
  705.             }
  706.             else
  707.             {
  708.                 // Reaccept any txes of ours that aren't already in a block
  709.                 if (!wtx.IsCoinBase())
  710.                     wtx.AcceptWalletTransaction(txdb, false);
  711.             }
  712.         }
  713.     }
  714. }
  715.  
  716.  
  717. void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
  718. {
  719.     foreach(const CMerkleTx& tx, vtxPrev)
  720.     {
  721.         if (!tx.IsCoinBase())
  722.         {
  723.             uint256 hash = tx.GetHash();
  724.             if (!txdb.ContainsTx(hash))
  725.                 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
  726.         }
  727.     }
  728.     if (!IsCoinBase())
  729.     {
  730.         uint256 hash = GetHash();
  731.         if (!txdb.ContainsTx(hash))
  732.         {
  733.             printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());
  734.             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
  735.         }
  736.     }
  737. }
  738.  
  739. void ResendWalletTransactions()
  740. {
  741.     // Do this infrequently and randomly to avoid giving away
  742.     // that these are our transactions.
  743.     static int64 nNextTime;
  744.     if (GetTime() < nNextTime)
  745.         return;
  746.     bool fFirst = (nNextTime == 0);
  747.     nNextTime = GetTime() + GetRand(30 * 60);
  748.     if (fFirst)
  749.         return;
  750.  
  751.     // Rebroadcast any of our txes that aren't in a block yet
  752.     printf("ResendWalletTransactions()\n");
  753.     CTxDB txdb("r");
  754.     CRITICAL_BLOCK(cs_mapWallet)
  755.     {
  756.         // Sort them in chronological order
  757.         multimap<unsigned int, CWalletTx*> mapSorted;
  758.         foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
  759.         {
  760.             CWalletTx& wtx = item.second;
  761.             // Don't rebroadcast until it's had plenty of time that
  762.             // it should have gotten in already by now.
  763.             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
  764.                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
  765.         }
  766.         foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
  767.         {
  768.             CWalletTx& wtx = *item.second;
  769.             wtx.RelayWalletTransaction(txdb);
  770.         }
  771.     }
  772. }
  773.  
  774.  
  775.  
  776.  
  777.  
  778.  
  779.  
  780.  
  781.  
  782.  
  783. //////////////////////////////////////////////////////////////////////////////
  784. //
  785. // CBlock and CBlockIndex
  786. //
  787.  
  788. bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)
  789. {
  790.     return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);
  791. }
  792.  
  793. uint256 GetOrphanRoot(const CBlock* pblock)
  794. {
  795.     // Work back to the first block in the orphan chain
  796.     while (mapOrphanBlocks.count(pblock->hashPrevBlock))
  797.         pblock = mapOrphanBlocks[pblock->hashPrevBlock];
  798.     return pblock->GetHash();
  799. }
  800.  
  801. int64 CBlock::GetBlockValue(int nHeight, int64 nFees) const
  802. {
  803.     int64 nSubsidy = 50 * COIN;
  804.  
  805.     // Subsidy is cut in half every 4 years
  806.     nSubsidy >>= (nHeight / 210000);
  807.  
  808.     return nSubsidy + nFees;
  809. }
  810.  
  811. unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
  812. {
  813.     const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
  814.     const int64 nTargetSpacing = 10 * 60;
  815.     const int64 nInterval = nTargetTimespan / nTargetSpacing;
  816.  
  817.     // Genesis block
  818.     if (pindexLast == NULL)
  819.         return bnProofOfWorkLimit.GetCompact();
  820.  
  821.     // Only change once per interval
  822.     if ((pindexLast->nHeight+1) % nInterval != 0)
  823.         return pindexLast->nBits;
  824.  
  825.     // Go back by what we want to be 14 days worth of blocks
  826.     const CBlockIndex* pindexFirst = pindexLast;
  827.     for (int i = 0; pindexFirst && i < nInterval-1; i++)
  828.         pindexFirst = pindexFirst->pprev;
  829.     assert(pindexFirst);
  830.  
  831.     // Limit adjustment step
  832.     int64 nActualTimespan = (int64)pindexLast->nTime - (int64)pindexFirst->nTime;
  833.     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
  834.     if (nActualTimespan < nTargetTimespan/4)
  835.         nActualTimespan = nTargetTimespan/4;
  836.     if (nActualTimespan > nTargetTimespan*4)
  837.         nActualTimespan = nTargetTimespan*4;
  838.  
  839.     // Retarget
  840.     CBigNum bnNew;
  841.     bnNew.SetCompact(pindexLast->nBits);
  842.     bnNew *= nActualTimespan;
  843.     bnNew /= nTargetTimespan;
  844.  
  845.     if (bnNew > bnProofOfWorkLimit)
  846.         bnNew = bnProofOfWorkLimit;
  847.  
  848.     /// debug print
  849.     printf("GetNextWorkRequired RETARGET\n");
  850.     printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
  851.     printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
  852.     printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
  853.  
  854.     return bnNew.GetCompact();
  855. }
  856.  
  857. bool IsInitialBlockDownload()
  858. {
  859.     if (pindexBest == NULL)
  860.         return true;
  861.     static int64 nLastUpdate;
  862.     static CBlockIndex* pindexLastBest;
  863.     if (pindexBest != pindexLastBest)
  864.     {
  865.         pindexLastBest = pindexBest;
  866.         nLastUpdate = GetTime();
  867.     }
  868.     return (GetTime() - nLastUpdate < 10 &&
  869.             pindexBest->nTime < GetTime() - 24 * 60 * 60);
  870. }
  871.  
  872. bool IsLockdown()
  873. {
  874.     if (!pindexBest)
  875.         return false;
  876.     return (bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6);
  877. }
  878.  
  879. void Lockdown(CBlockIndex* pindexNew)
  880. {
  881.     if (pindexNew->bnChainWork > bnBestInvalidWork)
  882.     {
  883.         bnBestInvalidWork = pindexNew->bnChainWork;
  884.         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
  885.         MainFrameRepaint();
  886.     }
  887.     printf("Lockdown: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,22).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
  888.     printf("Lockdown:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
  889.     printf("Lockdown: IsLockdown()=%d\n", (IsLockdown() ? 1 : 0));
  890.     if (IsLockdown())
  891.         printf("Lockdown: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
  892. }
  893.  
  894.  
  895.  
  896.  
  897.  
  898.  
  899.  
  900.  
  901. bool CTransaction::DisconnectInputs(CTxDB& txdb)
  902. {
  903.     // Relinquish previous transactions' spent pointers
  904.     if (!IsCoinBase())
  905.     {
  906.         foreach(const CTxIn& txin, vin)
  907.         {
  908.             COutPoint prevout = txin.prevout;
  909.  
  910.             // Get prev txindex from disk
  911.             CTxIndex txindex;
  912.             if (!txdb.ReadTxIndex(prevout.hash, txindex))
  913.                 return error("DisconnectInputs() : ReadTxIndex failed");
  914.  
  915.             if (prevout.n >= txindex.vSpent.size())
  916.                 return error("DisconnectInputs() : prevout.n out of range");
  917.  
  918.             // Mark outpoint as not spent
  919.             txindex.vSpent[prevout.n].SetNull();
  920.  
  921.             // Write back
  922.             txdb.UpdateTxIndex(prevout.hash, txindex);
  923.         }
  924.     }
  925.  
  926.     // Remove transaction from index
  927.     if (!txdb.EraseTxIndex(*this))
  928.         return error("DisconnectInputs() : EraseTxPos failed");
  929.  
  930.     return true;
  931. }
  932.  
  933.  
  934. bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
  935.                                  CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
  936. {
  937.     // Take over previous transactions' spent pointers
  938.     if (!IsCoinBase())
  939.     {
  940.         int64 nValueIn = 0;
  941.         for (int i = 0; i < vin.size(); i++)
  942.         {
  943.             COutPoint prevout = vin[i].prevout;
  944.  
  945.             // Read txindex
  946.             CTxIndex txindex;
  947.             bool fFound = true;
  948.             if (fMiner && mapTestPool.count(prevout.hash))
  949.             {
  950.                 // Get txindex from current proposed changes
  951.                 txindex = mapTestPool[prevout.hash];
  952.             }
  953.             else
  954.             {
  955.                 // Read txindex from txdb
  956.                 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
  957.             }
  958.             if (!fFound && (fBlock || fMiner))
  959.                 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());
  960.  
  961.             // Read txPrev
  962.             CTransaction txPrev;
  963.             if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
  964.             {
  965.                 // Get prev tx from single transactions in memory
  966.                 CRITICAL_BLOCK(cs_mapTransactions)
  967.                 {
  968.                     if (!mapTransactions.count(prevout.hash))
  969.                         return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());
  970.                     txPrev = mapTransactions[prevout.hash];
  971.                 }
  972.                 if (!fFound)
  973.                     txindex.vSpent.resize(txPrev.vout.size());
  974.             }
  975.             else
  976.             {
  977.                 // Get prev tx from disk
  978.                 if (!txPrev.ReadFromDisk(txindex.pos))
  979.                     return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());
  980.             }
  981.  
  982.             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
  983.                 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,6).c_str(), txPrev.ToString().c_str());
  984.  
  985.             // If prev is coinbase, check that it's matured
  986.             if (txPrev.IsCoinBase())
  987.                 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
  988.                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
  989.                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
  990.  
  991.             // Verify signature
  992.             if (!VerifySignature(txPrev, *this, i))
  993.                 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
  994.  
  995.             // Check for conflicts
  996.             if (!txindex.vSpent[prevout.n].IsNull())
  997.                 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,6).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
  998.  
  999.             // Mark outpoints as spent
  1000.             txindex.vSpent[prevout.n] = posThisTx;
  1001.  
  1002.             // Write back
  1003.             if (fBlock)
  1004.                 txdb.UpdateTxIndex(prevout.hash, txindex);
  1005.             else if (fMiner)
  1006.                 mapTestPool[prevout.hash] = txindex;
  1007.  
  1008.             nValueIn += txPrev.vout[prevout.n].nValue;
  1009.  
  1010.             // Check for negative or overflow input values
  1011.             if (txPrev.vout[prevout.n].nValue < 0)
  1012.                 return error("ConnectInputs() : txin.nValue negative");
  1013.             if (txPrev.vout[prevout.n].nValue > MAX_MONEY)
  1014.                 return error("ConnectInputs() : txin.nValue too high");
  1015.             if (nValueIn > MAX_MONEY)
  1016.                 return error("ConnectInputs() : txin total too high");
  1017.         }
  1018.  
  1019.         // Tally transaction fees
  1020.         int64 nTxFee = nValueIn - GetValueOut();
  1021.         if (nTxFee < 0)
  1022.             return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
  1023.         if (nTxFee < nMinFee)
  1024.             return false;
  1025.         nFees += nTxFee;
  1026.     }
  1027.  
  1028.     if (fBlock)
  1029.     {
  1030.         // Add transaction to disk index
  1031.         if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
  1032.             return error("ConnectInputs() : AddTxPos failed");
  1033.     }
  1034.     else if (fMiner)
  1035.     {
  1036.         // Add transaction to test pool
  1037.         mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
  1038.     }
  1039.  
  1040.     return true;
  1041. }
  1042.  
  1043.  
  1044. bool CTransaction::ClientConnectInputs()
  1045. {
  1046.     if (IsCoinBase())
  1047.         return false;
  1048.  
  1049.     // Take over previous transactions' spent pointers
  1050.     CRITICAL_BLOCK(cs_mapTransactions)
  1051.     {
  1052.         int64 nValueIn = 0;
  1053.         for (int i = 0; i < vin.size(); i++)
  1054.         {
  1055.             // Get prev tx from single transactions in memory
  1056.             COutPoint prevout = vin[i].prevout;
  1057.             if (!mapTransactions.count(prevout.hash))
  1058.                 return false;
  1059.             CTransaction& txPrev = mapTransactions[prevout.hash];
  1060.  
  1061.             if (prevout.n >= txPrev.vout.size())
  1062.                 return false;
  1063.  
  1064.             // Verify signature
  1065.             if (!VerifySignature(txPrev, *this, i))
  1066.                 return error("ConnectInputs() : VerifySignature failed");
  1067.  
  1068.             ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
  1069.             ///// this has to go away now that posNext is gone
  1070.             // // Check for conflicts
  1071.             // if (!txPrev.vout[prevout.n].posNext.IsNull())
  1072.             //     return error("ConnectInputs() : prev tx already used");
  1073.             //
  1074.             // // Flag outpoints as used
  1075.             // txPrev.vout[prevout.n].posNext = posThisTx;
  1076.  
  1077.             nValueIn += txPrev.vout[prevout.n].nValue;
  1078.         }
  1079.         if (GetValueOut() > nValueIn)
  1080.             return false;
  1081.     }
  1082.  
  1083.     return true;
  1084. }
  1085.  
  1086.  
  1087.  
  1088.  
  1089. bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
  1090. {
  1091.     // Disconnect in reverse order
  1092.     for (int i = vtx.size()-1; i >= 0; i--)
  1093.         if (!vtx[i].DisconnectInputs(txdb))
  1094.             return false;
  1095.  
  1096.     // Update block index on disk without changing it in memory.
  1097.     // The memory index structure will be changed after the db commits.
  1098.     if (pindex->pprev)
  1099.     {
  1100.         CDiskBlockIndex blockindexPrev(pindex->pprev);
  1101.         blockindexPrev.hashNext = 0;
  1102.         txdb.WriteBlockIndex(blockindexPrev);
  1103.     }
  1104.  
  1105.     return true;
  1106. }
  1107.  
  1108. bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
  1109. {
  1110.     //// issue here: it doesn't know the version
  1111.     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
  1112.  
  1113.     map<uint256, CTxIndex> mapUnused;
  1114.     int64 nFees = 0;
  1115.     foreach(CTransaction& tx, vtx)
  1116.     {
  1117.         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
  1118.         nTxPos += ::GetSerializeSize(tx, SER_DISK);
  1119.  
  1120.         if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
  1121.             return false;
  1122.     }
  1123.  
  1124.     if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
  1125.         return false;
  1126.  
  1127.     // Update block index on disk without changing it in memory.
  1128.     // The memory index structure will be changed after the db commits.
  1129.     if (pindex->pprev)
  1130.     {
  1131.         CDiskBlockIndex blockindexPrev(pindex->pprev);
  1132.         blockindexPrev.hashNext = pindex->GetBlockHash();
  1133.         txdb.WriteBlockIndex(blockindexPrev);
  1134.     }
  1135.  
  1136.     // Watch for transactions paying to me
  1137.     foreach(CTransaction& tx, vtx)
  1138.         AddToWalletIfMine(tx, this);
  1139.  
  1140.     return true;
  1141. }
  1142.  
  1143.  
  1144.  
  1145. bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
  1146. {
  1147.     printf("REORGANIZE\n");
  1148.  
  1149.     // Find the fork
  1150.     CBlockIndex* pfork = pindexBest;
  1151.     CBlockIndex* plonger = pindexNew;
  1152.     while (pfork != plonger)
  1153.     {
  1154.         while (plonger->nHeight > pfork->nHeight)
  1155.             if (!(plonger = plonger->pprev))
  1156.                 return error("Reorganize() : plonger->pprev is null");
  1157.         if (pfork == plonger)
  1158.             break;
  1159.         if (!(pfork = pfork->pprev))
  1160.             return error("Reorganize() : pfork->pprev is null");
  1161.     }
  1162.  
  1163.     // List of what to disconnect
  1164.     vector<CBlockIndex*> vDisconnect;
  1165.     for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
  1166.         vDisconnect.push_back(pindex);
  1167.  
  1168.     // List of what to connect
  1169.     vector<CBlockIndex*> vConnect;
  1170.     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
  1171.         vConnect.push_back(pindex);
  1172.     reverse(vConnect.begin(), vConnect.end());
  1173.  
  1174.     // Disconnect shorter branch
  1175.     vector<CTransaction> vResurrect;
  1176.     foreach(CBlockIndex* pindex, vDisconnect)
  1177.     {
  1178.         CBlock block;
  1179.         if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
  1180.             return error("Reorganize() : ReadFromDisk for disconnect failed");
  1181.         if (!block.DisconnectBlock(txdb, pindex))
  1182.             return error("Reorganize() : DisconnectBlock failed");
  1183.  
  1184.         // Queue memory transactions to resurrect
  1185.         foreach(const CTransaction& tx, block.vtx)
  1186.             if (!tx.IsCoinBase())
  1187.                 vResurrect.push_back(tx);
  1188.     }
  1189.  
  1190.     // Connect longer branch
  1191.     vector<CTransaction> vDelete;
  1192.     for (int i = 0; i < vConnect.size(); i++)
  1193.     {
  1194.         CBlockIndex* pindex = vConnect[i];
  1195.         CBlock block;
  1196.         if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
  1197.             return error("Reorganize() : ReadFromDisk for connect failed");
  1198.         if (!block.ConnectBlock(txdb, pindex))
  1199.         {
  1200.             // Invalid block
  1201.             txdb.TxnAbort();
  1202.             return error("Reorganize() : ConnectBlock failed");
  1203.         }
  1204.  
  1205.         // Queue memory transactions to delete
  1206.         foreach(const CTransaction& tx, block.vtx)
  1207.             vDelete.push_back(tx);
  1208.     }
  1209.     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
  1210.         return error("Reorganize() : WriteHashBestChain failed");
  1211.  
  1212.     // Commit now because resurrecting could take some time
  1213.     txdb.TxnCommit();
  1214.  
  1215.     // Disconnect shorter branch
  1216.     foreach(CBlockIndex* pindex, vDisconnect)
  1217.         if (pindex->pprev)
  1218.             pindex->pprev->pnext = NULL;
  1219.  
  1220.     // Connect longer branch
  1221.     foreach(CBlockIndex* pindex, vConnect)
  1222.         if (pindex->pprev)
  1223.             pindex->pprev->pnext = pindex;
  1224.  
  1225.     // Resurrect memory transactions that were in the disconnected branch
  1226.     foreach(CTransaction& tx, vResurrect)
  1227.         tx.AcceptTransaction(txdb, false);
  1228.  
  1229.     // Delete redundant memory transactions that are in the connected branch
  1230.     foreach(CTransaction& tx, vDelete)
  1231.         tx.RemoveFromMemoryPool();
  1232.  
  1233.     return true;
  1234. }
  1235.  
  1236.  
  1237. bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
  1238. {
  1239.     // Check for duplicate
  1240.     uint256 hash = GetHash();
  1241.     if (mapBlockIndex.count(hash))
  1242.         return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());
  1243.  
  1244.     // Construct new block index object
  1245.     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
  1246.     if (!pindexNew)
  1247.         return error("AddToBlockIndex() : new CBlockIndex failed");
  1248.     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  1249.     pindexNew->phashBlock = &((*mi).first);
  1250.     map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
  1251.     if (miPrev != mapBlockIndex.end())
  1252.     {
  1253.         pindexNew->pprev = (*miPrev).second;
  1254.         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  1255.     }
  1256.     pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
  1257.  
  1258.     CTxDB txdb;
  1259.     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
  1260.  
  1261.     // New best
  1262.     if (pindexNew->bnChainWork > bnBestChainWork)
  1263.     {
  1264.         txdb.TxnBegin();
  1265.         if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
  1266.         {
  1267.             pindexGenesisBlock = pindexNew;
  1268.             txdb.WriteHashBestChain(hash);
  1269.         }
  1270.         else if (hashPrevBlock == hashBestChain)
  1271.         {
  1272.             // Adding to current best branch
  1273.             if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
  1274.             {
  1275.                 txdb.TxnAbort();
  1276.                 Lockdown(pindexNew);
  1277.                 return error("AddToBlockIndex() : ConnectBlock failed");
  1278.             }
  1279.             txdb.TxnCommit();
  1280.             pindexNew->pprev->pnext = pindexNew;
  1281.  
  1282.             // Delete redundant memory transactions
  1283.             foreach(CTransaction& tx, vtx)
  1284.                 tx.RemoveFromMemoryPool();
  1285.         }
  1286.         else
  1287.         {
  1288.             // New best branch
  1289.             if (!Reorganize(txdb, pindexNew))
  1290.             {
  1291.                 txdb.TxnAbort();
  1292.                 Lockdown(pindexNew);
  1293.                 return error("AddToBlockIndex() : Reorganize failed");
  1294.             }
  1295.         }
  1296.         txdb.TxnCommit();
  1297.  
  1298.         // New best block
  1299.         hashBestChain = hash;
  1300.         pindexBest = pindexNew;
  1301.         nBestHeight = pindexBest->nHeight;
  1302.         bnBestChainWork = pindexNew->bnChainWork;
  1303.         nTimeBestReceived = GetTime();
  1304.         nTransactionsUpdated++;
  1305.         printf("AddToBlockIndex: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
  1306.     }
  1307.  
  1308.     txdb.Close();
  1309.  
  1310.     if (pindexNew == pindexBest)
  1311.     {
  1312.         // Notify UI to display prev block's coinbase if it was ours
  1313.         static uint256 hashPrevBestCoinBase;
  1314.         CRITICAL_BLOCK(cs_mapWallet)
  1315.             vWalletUpdated.push_back(hashPrevBestCoinBase);
  1316.         hashPrevBestCoinBase = vtx[0].GetHash();
  1317.     }
  1318.  
  1319.     MainFrameRepaint();
  1320.     return true;
  1321. }
  1322.  
  1323.  
  1324.  
  1325.  
  1326. bool CBlock::CheckBlock() const
  1327. {
  1328.     // These are checks that are independent of context
  1329.     // that can be verified before saving an orphan block.
  1330.  
  1331.     // Size limits
  1332.     if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
  1333.         return error("CheckBlock() : size limits failed");
  1334.  
  1335.     // Check timestamp
  1336.     if (nTime > GetAdjustedTime() + 2 * 60 * 60)
  1337.         return error("CheckBlock() : block timestamp too far in the future");
  1338.  
  1339.     // First transaction must be coinbase, the rest must not be
  1340.     if (vtx.empty() || !vtx[0].IsCoinBase())
  1341.         return error("CheckBlock() : first tx is not coinbase");
  1342.     for (int i = 1; i < vtx.size(); i++)
  1343.         if (vtx[i].IsCoinBase())
  1344.             return error("CheckBlock() : more than one coinbase");
  1345.  
  1346.     // Check transactions
  1347.     foreach(const CTransaction& tx, vtx)
  1348.         if (!tx.CheckTransaction())
  1349.             return error("CheckBlock() : CheckTransaction failed");
  1350.  
  1351.     // Check proof of work matches claimed amount
  1352.     if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
  1353.         return error("CheckBlock() : nBits below minimum work");
  1354.     if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
  1355.         return error("CheckBlock() : hash doesn't match nBits");
  1356.  
  1357.     // Check merkleroot
  1358.     if (hashMerkleRoot != BuildMerkleTree())
  1359.         return error("CheckBlock() : hashMerkleRoot mismatch");
  1360.  
  1361.     return true;
  1362. }
  1363.  
  1364. bool CBlock::AcceptBlock()
  1365. {
  1366.     // Check for duplicate
  1367.     uint256 hash = GetHash();
  1368.     if (mapBlockIndex.count(hash))
  1369.         return error("AcceptBlock() : block already in mapBlockIndex");
  1370.  
  1371.     // Get prev block index
  1372.     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
  1373.     if (mi == mapBlockIndex.end())
  1374.         return error("AcceptBlock() : prev block not found");
  1375.     CBlockIndex* pindexPrev = (*mi).second;
  1376.  
  1377.     // Check timestamp against prev
  1378.     if (nTime <= pindexPrev->GetMedianTimePast())
  1379.         return error("AcceptBlock() : block's timestamp is too early");
  1380.  
  1381.     // Check that all transactions are finalized
  1382.     foreach(const CTransaction& tx, vtx)
  1383.         if (!tx.IsFinal(pindexPrev->nHeight+1, nTime))
  1384.             return error("AcceptBlock() : contains a non-final transaction");
  1385.  
  1386.     // Check proof of work
  1387.     if (nBits != GetNextWorkRequired(pindexPrev))
  1388.         return error("AcceptBlock() : incorrect proof of work");
  1389.  
  1390.     // Check that the block chain matches the known block chain up to a checkpoint
  1391.     if ((pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
  1392.         (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
  1393.         (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
  1394.         (pindexPrev->nHeight+1 == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
  1395.         (pindexPrev->nHeight+1 == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
  1396.         return error("AcceptBlock() : rejected by checkpoint lockin at %d", pindexPrev->nHeight+1);
  1397.  
  1398.     // Scanback checkpoint lockin
  1399.     for (CBlockIndex* pindex = pindexPrev; pindex->nHeight >= 74000; pindex = pindex->pprev)
  1400.     {
  1401.         if (pindex->nHeight == 74000 && pindex->GetBlockHash() != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
  1402.             return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);
  1403.         if (pindex->nHeight == 74638 && pindex->GetBlockHash() == uint256("0x0000000000790ab3f22ec756ad43b6ab569abf0bddeb97c67a6f7b1470a7ec1c"))
  1404.             return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);
  1405.     }
  1406.  
  1407.     // Write block to history file
  1408.     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
  1409.         return error("AcceptBlock() : out of disk space");
  1410.     unsigned int nFile;
  1411.     unsigned int nBlockPos;
  1412.     if (!WriteToDisk(!fClient, nFile, nBlockPos))
  1413.         return error("AcceptBlock() : WriteToDisk failed");
  1414.     if (!AddToBlockIndex(nFile, nBlockPos))
  1415.         return error("AcceptBlock() : AddToBlockIndex failed");
  1416.  
  1417.     // Relay inventory, but don't relay old inventory during initial block download
  1418.     if (hashBestChain == hash)
  1419.         CRITICAL_BLOCK(cs_vNodes)
  1420.             foreach(CNode* pnode, vNodes)
  1421.                 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
  1422.                     pnode->PushInventory(CInv(MSG_BLOCK, hash));
  1423.  
  1424.     return true;
  1425. }
  1426.  
  1427. bool ProcessBlock(CNode* pfrom, CBlock* pblock)
  1428. {
  1429.     // Check for duplicate
  1430.     uint256 hash = pblock->GetHash();
  1431.     if (mapBlockIndex.count(hash))
  1432.         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());
  1433.     if (mapOrphanBlocks.count(hash))
  1434.         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());
  1435.  
  1436.     // Preliminary checks
  1437.     if (!pblock->CheckBlock())
  1438.     {
  1439.         delete pblock;
  1440.         return error("ProcessBlock() : CheckBlock FAILED");
  1441.     }
  1442.  
  1443.     // If don't already have its previous block, shunt it off to holding area until we get it
  1444.     if (!mapBlockIndex.count(pblock->hashPrevBlock))
  1445.     {
  1446.         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());
  1447.         mapOrphanBlocks.insert(make_pair(hash, pblock));
  1448.         mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
  1449.  
  1450.         // Ask this guy to fill in what we're missing
  1451.         if (pfrom)
  1452.             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
  1453.         return true;
  1454.     }
  1455.  
  1456.     // Store to disk
  1457.     if (!pblock->AcceptBlock())
  1458.     {
  1459.         delete pblock;
  1460.         return error("ProcessBlock() : AcceptBlock FAILED");
  1461.     }
  1462.     delete pblock;
  1463.  
  1464.     // Recursively process any orphan blocks that depended on this one
  1465.     vector<uint256> vWorkQueue;
  1466.     vWorkQueue.push_back(hash);
  1467.     for (int i = 0; i < vWorkQueue.size(); i++)
  1468.     {
  1469.         uint256 hashPrev = vWorkQueue[i];
  1470.         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
  1471.              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
  1472.              ++mi)
  1473.         {
  1474.             CBlock* pblockOrphan = (*mi).second;
  1475.             if (pblockOrphan->AcceptBlock())
  1476.                 vWorkQueue.push_back(pblockOrphan->GetHash());
  1477.             mapOrphanBlocks.erase(pblockOrphan->GetHash());
  1478.             delete pblockOrphan;
  1479.         }
  1480.         mapOrphanBlocksByPrev.erase(hashPrev);
  1481.     }
  1482.  
  1483.     printf("ProcessBlock: ACCEPTED\n");
  1484.     return true;
  1485. }
  1486.  
  1487.  
  1488.  
  1489.  
  1490.  
  1491.  
  1492.  
  1493.  
  1494. template<typename Stream>
  1495. bool ScanMessageStart(Stream& s)
  1496. {
  1497.     // Scan ahead to the next pchMessageStart, which should normally be immediately
  1498.     // at the file pointer.  Leaves file pointer at end of pchMessageStart.
  1499.     s.clear(0);
  1500.     short prevmask = s.exceptions(0);
  1501.     const char* p = BEGIN(pchMessageStart);
  1502.     try
  1503.     {
  1504.         loop
  1505.         {
  1506.             char c;
  1507.             s.read(&c, 1);
  1508.             if (s.fail())
  1509.             {
  1510.                 s.clear(0);
  1511.                 s.exceptions(prevmask);
  1512.                 return false;
  1513.             }
  1514.             if (*p != c)
  1515.                 p = BEGIN(pchMessageStart);
  1516.             if (*p == c)
  1517.             {
  1518.                 if (++p == END(pchMessageStart))
  1519.                 {
  1520.                     s.clear(0);
  1521.                     s.exceptions(prevmask);
  1522.                     return true;
  1523.                 }
  1524.             }
  1525.         }
  1526.     }
  1527.     catch (...)
  1528.     {
  1529.         s.clear(0);
  1530.         s.exceptions(prevmask);
  1531.         return false;
  1532.     }
  1533. }
  1534.  
  1535. bool CheckDiskSpace(int64 nAdditionalBytes)
  1536. {
  1537.     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
  1538.  
  1539.     // Check for 15MB because database could create another 10MB log file at any time
  1540.     if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)
  1541.     {
  1542.         fShutdown = true;
  1543.         printf("***  %s***\n", _("Warning: Disk space is low  "));
  1544. #ifdef GUI
  1545.         ThreadSafeMessageBox(_("Warning: Disk space is low  "), "Bitcoin", wxOK | wxICON_EXCLAMATION);
  1546. #endif
  1547.         CreateThread(Shutdown, NULL);
  1548.         return false;
  1549.     }
  1550.     return true;
  1551. }
  1552.  
  1553. FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
  1554. {
  1555.     if (nFile == -1)
  1556.         return NULL;
  1557.     FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
  1558.     if (!file)
  1559.         return NULL;
  1560.     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
  1561.     {
  1562.         if (fseek(file, nBlockPos, SEEK_SET) != 0)
  1563.         {
  1564.             fclose(file);
  1565.             return NULL;
  1566.         }
  1567.     }
  1568.     return file;
  1569. }
  1570.  
  1571. static unsigned int nCurrentBlockFile = 1;
  1572.  
  1573. FILE* AppendBlockFile(unsigned int& nFileRet)
  1574. {
  1575.     nFileRet = 0;
  1576.     loop
  1577.     {
  1578.         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
  1579.         if (!file)
  1580.             return NULL;
  1581.         if (fseek(file, 0, SEEK_END) != 0)
  1582.             return NULL;
  1583.         // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
  1584.         if (ftell(file) < 0x7F000000 - MAX_SIZE)
  1585.         {
  1586.             nFileRet = nCurrentBlockFile;
  1587.             return file;
  1588.         }
  1589.         fclose(file);
  1590.         nCurrentBlockFile++;
  1591.     }
  1592. }
  1593.  
  1594. bool LoadBlockIndex(bool fAllowNew)
  1595. {
  1596.     //
  1597.     // Load block index
  1598.     //
  1599.     CTxDB txdb("cr");
  1600.     if (!txdb.LoadBlockIndex())
  1601.         return false;
  1602.     txdb.Close();
  1603.  
  1604.     //
  1605.     // Init with genesis block
  1606.     //
  1607.     if (mapBlockIndex.empty())
  1608.     {
  1609.         if (!fAllowNew)
  1610.             return false;
  1611.  
  1612.  
  1613.         // Genesis Block:
  1614.         // GetHash()      = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
  1615.         // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
  1616.         // txNew.vin[0].scriptSig     = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
  1617.         // txNew.vout[0].nValue       = 5000000000
  1618.         // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG
  1619.         // block.nVersion = 1
  1620.         // block.nTime    = 1231006505
  1621.         // block.nBits    = 0x1d00ffff
  1622.         // block.nNonce   = 2083236893
  1623.         // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
  1624.         //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
  1625.         //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
  1626.         //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
  1627.         //   vMerkleTree: 4a5e1e
  1628.  
  1629.         // Genesis block
  1630.         const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
  1631.         CTransaction txNew;
  1632.         txNew.vin.resize(1);
  1633.         txNew.vout.resize(1);
  1634.         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
  1635.         txNew.vout[0].nValue = 50 * COIN;
  1636.         CBigNum bnPubKey;
  1637.         bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");
  1638.         txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;
  1639.         CBlock block;
  1640.         block.vtx.push_back(txNew);
  1641.         block.hashPrevBlock = 0;
  1642.         block.hashMerkleRoot = block.BuildMerkleTree();
  1643.         block.nVersion = 1;
  1644.         block.nTime    = 1231006505;
  1645.         block.nBits    = 0x1d00ffff;
  1646.         block.nNonce   = 2083236893;
  1647.  
  1648.             //// debug print
  1649.             printf("%s\n", block.GetHash().ToString().c_str());
  1650.             printf("%s\n", block.hashMerkleRoot.ToString().c_str());
  1651.             printf("%s\n", hashGenesisBlock.ToString().c_str());
  1652.             txNew.vout[0].scriptPubKey.print();
  1653.             block.print();
  1654.             assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
  1655.  
  1656.         assert(block.GetHash() == hashGenesisBlock);
  1657.  
  1658.         // Start new block file
  1659.         unsigned int nFile;
  1660.         unsigned int nBlockPos;
  1661.         if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
  1662.             return error("LoadBlockIndex() : writing genesis block to disk failed");
  1663.         if (!block.AddToBlockIndex(nFile, nBlockPos))
  1664.             return error("LoadBlockIndex() : genesis block not accepted");
  1665.     }
  1666.  
  1667.     return true;
  1668. }
  1669.  
  1670.  
  1671.  
  1672. void PrintBlockTree()
  1673. {
  1674.     // precompute tree structure
  1675.     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
  1676.     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  1677.     {
  1678.         CBlockIndex* pindex = (*mi).second;
  1679.         mapNext[pindex->pprev].push_back(pindex);
  1680.         // test
  1681.         //while (rand() % 3 == 0)
  1682.         //    mapNext[pindex->pprev].push_back(pindex);
  1683.     }
  1684.  
  1685.     vector<pair<int, CBlockIndex*> > vStack;
  1686.     vStack.push_back(make_pair(0, pindexGenesisBlock));
  1687.  
  1688.     int nPrevCol = 0;
  1689.     while (!vStack.empty())
  1690.     {
  1691.         int nCol = vStack.back().first;
  1692.         CBlockIndex* pindex = vStack.back().second;
  1693.         vStack.pop_back();
  1694.  
  1695.         // print split or gap
  1696.         if (nCol > nPrevCol)
  1697.         {
  1698.             for (int i = 0; i < nCol-1; i++)
  1699.                 printf("| ");
  1700.             printf("|\\\n");
  1701.         }
  1702.         else if (nCol < nPrevCol)
  1703.         {
  1704.             for (int i = 0; i < nCol; i++)
  1705.                 printf("| ");
  1706.             printf("|\n");
  1707.         }
  1708.         nPrevCol = nCol;
  1709.  
  1710.         // print columns
  1711.         for (int i = 0; i < nCol; i++)
  1712.             printf("| ");
  1713.  
  1714.         // print item
  1715.         CBlock block;
  1716.         block.ReadFromDisk(pindex);
  1717.         printf("%d (%u,%u) %s  %s  tx %d",
  1718.             pindex->nHeight,
  1719.             pindex->nFile,
  1720.             pindex->nBlockPos,
  1721.             block.GetHash().ToString().substr(0,16).c_str(),
  1722.             DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),
  1723.             block.vtx.size());
  1724.  
  1725.         CRITICAL_BLOCK(cs_mapWallet)
  1726.         {
  1727.             if (mapWallet.count(block.vtx[0].GetHash()))
  1728.             {
  1729.                 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
  1730.                 printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
  1731.             }
  1732.         }
  1733.         printf("\n");
  1734.  
  1735.  
  1736.         // put the main timechain first
  1737.         vector<CBlockIndex*>& vNext = mapNext[pindex];
  1738.         for (int i = 0; i < vNext.size(); i++)
  1739.         {
  1740.             if (vNext[i]->pnext)
  1741.             {
  1742.                 swap(vNext[0], vNext[i]);
  1743.                 break;
  1744.             }
  1745.         }
  1746.  
  1747.         // iterate children
  1748.         for (int i = 0; i < vNext.size(); i++)
  1749.             vStack.push_back(make_pair(nCol+i, vNext[i]));
  1750.     }
  1751. }
  1752.  
  1753.  
  1754.  
  1755.  
  1756.  
  1757.  
  1758.  
  1759.  
  1760.  
  1761.  
  1762. //////////////////////////////////////////////////////////////////////////////
  1763. //
  1764. // Messages
  1765. //
  1766.  
  1767.  
  1768. bool AlreadyHave(CTxDB& txdb, const CInv& inv)
  1769. {
  1770.     switch (inv.type)
  1771.     {
  1772.     case MSG_TX:    return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
  1773.     case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
  1774.     }
  1775.     // Don't know what it is, just say we already got one
  1776.     return true;
  1777. }
  1778.  
  1779.  
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785. bool ProcessMessages(CNode* pfrom)
  1786. {
  1787.     CDataStream& vRecv = pfrom->vRecv;
  1788.     if (vRecv.empty())
  1789.         return true;
  1790.     //if (fDebug)
  1791.     //    printf("ProcessMessages(%d bytes)\n", vRecv.size());
  1792.  
  1793.     //
  1794.     // Message format
  1795.     //  (4) message start
  1796.     //  (12) command
  1797.     //  (4) size
  1798.     //  (4) checksum
  1799.     //  (x) data
  1800.     //
  1801.  
  1802.     loop
  1803.     {
  1804.         // Scan for message start
  1805.         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
  1806.         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
  1807.         if (vRecv.end() - pstart < nHeaderSize)
  1808.         {
  1809.             if (vRecv.size() > nHeaderSize)
  1810.             {
  1811.                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
  1812.                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
  1813.             }
  1814.             break;
  1815.         }
  1816.         if (pstart - vRecv.begin() > 0)
  1817.             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
  1818.         vRecv.erase(vRecv.begin(), pstart);
  1819.  
  1820.         // Read header
  1821.         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
  1822.         CMessageHeader hdr;
  1823.         vRecv >> hdr;
  1824.         if (!hdr.IsValid())
  1825.         {
  1826.             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
  1827.             continue;
  1828.         }
  1829.         string strCommand = hdr.GetCommand();
  1830.  
  1831.         // Message size
  1832.         unsigned int nMessageSize = hdr.nMessageSize;
  1833.         if (nMessageSize > vRecv.size())
  1834.         {
  1835.             // Rewind and wait for rest of message
  1836.             ///// need a mechanism to give up waiting for overlong message size error
  1837.             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
  1838.             break;
  1839.         }
  1840.  
  1841.         // Copy message to its own buffer
  1842.         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
  1843.         vRecv.ignore(nMessageSize);
  1844.  
  1845.         // Checksum
  1846.         if (vRecv.GetVersion() >= 209)
  1847.         {
  1848.             uint256 hash = Hash(vMsg.begin(), vMsg.end());
  1849.             unsigned int nChecksum = 0;
  1850.             memcpy(&nChecksum, &hash, sizeof(nChecksum));
  1851.             if (nChecksum != hdr.nChecksum)
  1852.             {
  1853.                 printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
  1854.                        strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
  1855.                 continue;
  1856.             }
  1857.         }
  1858.  
  1859.         // Process message
  1860.         bool fRet = false;
  1861.         try
  1862.         {
  1863.             CRITICAL_BLOCK(cs_main)
  1864.                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
  1865.             if (fShutdown)
  1866.                 return true;
  1867.         }
  1868.         catch (std::ios_base::failure& e)
  1869.         {
  1870.             if (strstr(e.what(), "CDataStream::read() : end of data"))
  1871.             {
  1872.                 // Allow exceptions from underlength message on vRecv
  1873.                 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
  1874.             }
  1875.             else if (strstr(e.what(), ": size too large"))
  1876.             {
  1877.                 // Allow exceptions from overlong size
  1878.                 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
  1879.             }
  1880.             else
  1881.             {
  1882.                 PrintException(&e, "ProcessMessage()");
  1883.             }
  1884.         }
  1885.         catch (std::exception& e) {
  1886.             PrintException(&e, "ProcessMessage()");
  1887.         } catch (...) {
  1888.             PrintException(NULL, "ProcessMessage()");
  1889.         }
  1890.  
  1891.         if (!fRet)
  1892.             printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);
  1893.     }
  1894.  
  1895.     vRecv.Compact();
  1896.     return true;
  1897. }
  1898.  
  1899.  
  1900.  
  1901.  
  1902. bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
  1903. {
  1904.     static map<unsigned int, vector<unsigned char> > mapReuseKey;
  1905.     RandAddSeedPerfmon();
  1906.     if (fDebug)
  1907.         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
  1908.     printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
  1909.     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
  1910.     {
  1911.         printf("dropmessagestest DROPPING RECV MESSAGE\n");
  1912.         return true;
  1913.     }
  1914.  
  1915.  
  1916.  
  1917.  
  1918.  
  1919.     if (strCommand == "version")
  1920.     {
  1921.         // Each connection can only send one version message
  1922.         if (pfrom->nVersion != 0)
  1923.             return false;
  1924.  
  1925.         int64 nTime;
  1926.         CAddress addrMe;
  1927.         CAddress addrFrom;
  1928.         uint64 nNonce = 1;
  1929.         string strSubVer;
  1930.         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
  1931.         if (pfrom->nVersion == 10300)
  1932.             pfrom->nVersion = 300;
  1933.         if (pfrom->nVersion >= 106 && !vRecv.empty())
  1934.             vRecv >> addrFrom >> nNonce;
  1935.         if (pfrom->nVersion >= 106 && !vRecv.empty())
  1936.             vRecv >> strSubVer;
  1937.         if (pfrom->nVersion >= 209 && !vRecv.empty())
  1938.             vRecv >> pfrom->nStartingHeight;
  1939.  
  1940.         if (pfrom->nVersion == 0)
  1941.             return false;
  1942.  
  1943.         // Disconnect if we connected to ourself
  1944.         if (nNonce == nLocalHostNonce && nNonce > 1)
  1945.         {
  1946.             pfrom->fDisconnect = true;
  1947.             return true;
  1948.         }
  1949.  
  1950.         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
  1951.         if (pfrom->fClient)
  1952.         {
  1953.             pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
  1954.             pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
  1955.         }
  1956.  
  1957.         AddTimeData(pfrom->addr.ip, nTime);
  1958.  
  1959.         // Change version
  1960.         if (pfrom->nVersion >= 209)
  1961.             pfrom->PushMessage("verack");
  1962.         pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
  1963.         if (pfrom->nVersion < 209)
  1964.             pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
  1965.  
  1966.         // Ask the first connected node for block updates
  1967.         static int nAskedForBlocks;
  1968.         if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
  1969.         {
  1970.             nAskedForBlocks++;
  1971.             pfrom->PushGetBlocks(pindexBest, uint256(0));
  1972.         }
  1973.  
  1974.         pfrom->fSuccessfullyConnected = true;
  1975.  
  1976.         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
  1977.     }
  1978.  
  1979.  
  1980.     else if (pfrom->nVersion == 0)
  1981.     {
  1982.         // Must have a version message before anything else
  1983.         return false;
  1984.     }
  1985.  
  1986.  
  1987.     else if (strCommand == "verack")
  1988.     {
  1989.         pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
  1990.     }
  1991.  
  1992.  
  1993.     else if (strCommand == "addr")
  1994.     {
  1995.         vector<CAddress> vAddr;
  1996.         vRecv >> vAddr;
  1997.         if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
  1998.             return true;
  1999.         if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
  2000.             return true;
  2001.         if (vAddr.size() > 1000)
  2002.             return error("message addr size() = %d", vAddr.size());
  2003.  
  2004.         // Store the new addresses
  2005.         foreach(CAddress& addr, vAddr)
  2006.         {
  2007.             if (fShutdown)
  2008.                 return true;
  2009.             // ignore IPv6 for now, since it isn't implemented anyway
  2010.             if (!addr.IsIPv4())
  2011.                 continue;
  2012.             addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
  2013.             if (pfrom->fGetAddr || vAddr.size() > 10)
  2014.                 addr.nTime -= 5 * 24 * 60 * 60;
  2015.             AddAddress(addr);
  2016.             pfrom->AddAddressKnown(addr);
  2017.             if (!pfrom->fGetAddr && addr.IsRoutable())
  2018.             {
  2019.                 // Relay to a limited number of other nodes
  2020.                 CRITICAL_BLOCK(cs_vNodes)
  2021.                 {
  2022.                     // Use deterministic randomness to send to
  2023.                     // the same places for 12 hours at a time
  2024.                     static uint256 hashSalt;
  2025.                     if (hashSalt == 0)
  2026.                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
  2027.                     uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;
  2028.                     multimap<uint256, CNode*> mapMix;
  2029.                     foreach(CNode* pnode, vNodes)
  2030.                         mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));
  2031.                     int nRelayNodes = 4;
  2032.                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
  2033.                         ((*mi).second)->PushAddress(addr);
  2034.                 }
  2035.             }
  2036.         }
  2037.         if (vAddr.size() < 1000)
  2038.             pfrom->fGetAddr = false;
  2039.     }
  2040.  
  2041.  
  2042.     else if (strCommand == "inv")
  2043.     {
  2044.         vector<CInv> vInv;
  2045.         vRecv >> vInv;
  2046.         if (vInv.size() > 50000)
  2047.             return error("message inv size() = %d", vInv.size());
  2048.  
  2049.         CTxDB txdb("r");
  2050.         foreach(const CInv& inv, vInv)
  2051.         {
  2052.             if (fShutdown)
  2053.                 return true;
  2054.             pfrom->AddInventoryKnown(inv);
  2055.  
  2056.             bool fAlreadyHave = AlreadyHave(txdb, inv);
  2057.             printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
  2058.  
  2059.             if (!fAlreadyHave)
  2060.                 pfrom->AskFor(inv);
  2061.             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
  2062.                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
  2063.  
  2064.             // Track requests for our stuff
  2065.             CRITICAL_BLOCK(cs_mapRequestCount)
  2066.             {
  2067.                 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
  2068.                 if (mi != mapRequestCount.end())
  2069.                     (*mi).second++;
  2070.             }
  2071.         }
  2072.     }
  2073.  
  2074.  
  2075.     else if (strCommand == "getdata")
  2076.     {
  2077.         vector<CInv> vInv;
  2078.         vRecv >> vInv;
  2079.         if (vInv.size() > 50000)
  2080.             return error("message getdata size() = %d", vInv.size());
  2081.  
  2082.         foreach(const CInv& inv, vInv)
  2083.         {
  2084.             if (fShutdown)
  2085.                 return true;
  2086.             printf("received getdata for: %s\n", inv.ToString().c_str());
  2087.  
  2088.             if (inv.type == MSG_BLOCK)
  2089.             {
  2090.                 // Send block from disk
  2091.                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
  2092.                 if (mi != mapBlockIndex.end())
  2093.                 {
  2094.                     //// could optimize this to send header straight from blockindex for client
  2095.                     CBlock block;
  2096.                     block.ReadFromDisk((*mi).second, !pfrom->fClient);
  2097.                     pfrom->PushMessage("block", block);
  2098.  
  2099.                     // Trigger them to send a getblocks request for the next batch of inventory
  2100.                     if (inv.hash == pfrom->hashContinue)
  2101.                     {
  2102.                         // Bypass PushInventory, this must send even if redundant,
  2103.                         // and we want it right after the last block so they don't
  2104.                         // wait for other stuff first.
  2105.                         vector<CInv> vInv;
  2106.                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
  2107.                         pfrom->PushMessage("inv", vInv);
  2108.                         pfrom->hashContinue = 0;
  2109.                     }
  2110.                 }
  2111.             }
  2112.             else if (inv.IsKnownType())
  2113.             {
  2114.                 // Send stream from relay memory
  2115.                 CRITICAL_BLOCK(cs_mapRelay)
  2116.                 {
  2117.                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
  2118.                     if (mi != mapRelay.end())
  2119.                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
  2120.                 }
  2121.             }
  2122.  
  2123.             // Track requests for our stuff
  2124.             CRITICAL_BLOCK(cs_mapRequestCount)
  2125.             {
  2126.                 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
  2127.                 if (mi != mapRequestCount.end())
  2128.                     (*mi).second++;
  2129.             }
  2130.         }
  2131.     }
  2132.  
  2133.  
  2134.     else if (strCommand == "getblocks")
  2135.     {
  2136.         CBlockLocator locator;
  2137.         uint256 hashStop;
  2138.         vRecv >> locator >> hashStop;
  2139.  
  2140.         // Find the first block the caller has in the main chain
  2141.         CBlockIndex* pindex = locator.GetBlockIndex();
  2142.  
  2143.         // Send the rest of the chain
  2144.         if (pindex)
  2145.             pindex = pindex->pnext;
  2146.         int nLimit = 500 + locator.GetDistanceBack();
  2147.         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);
  2148.         for (; pindex; pindex = pindex->pnext)
  2149.         {
  2150.             if (pindex->GetBlockHash() == hashStop)
  2151.             {
  2152.                 printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
  2153.                 break;
  2154.             }
  2155.             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  2156.             if (--nLimit <= 0)
  2157.             {
  2158.                 // When this block is requested, we'll send an inv that'll make them
  2159.                 // getblocks the next batch of inventory.
  2160.                 printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
  2161.                 pfrom->hashContinue = pindex->GetBlockHash();
  2162.                 break;
  2163.             }
  2164.         }
  2165.     }
  2166.  
  2167.  
  2168.     else if (strCommand == "tx")
  2169.     {
  2170.         vector<uint256> vWorkQueue;
  2171.         CDataStream vMsg(vRecv);
  2172.         CTransaction tx;
  2173.         vRecv >> tx;
  2174.  
  2175.         CInv inv(MSG_TX, tx.GetHash());
  2176.         pfrom->AddInventoryKnown(inv);
  2177.  
  2178.         bool fMissingInputs = false;
  2179.         if (tx.AcceptTransaction(true, &fMissingInputs))
  2180.         {
  2181.             AddToWalletIfMine(tx, NULL);
  2182.             RelayMessage(inv, vMsg);
  2183.             mapAlreadyAskedFor.erase(inv);
  2184.             vWorkQueue.push_back(inv.hash);
  2185.  
  2186.             // Recursively process any orphan transactions that depended on this one
  2187.             for (int i = 0; i < vWorkQueue.size(); i++)
  2188.             {
  2189.                 uint256 hashPrev = vWorkQueue[i];
  2190.                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
  2191.                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
  2192.                      ++mi)
  2193.                 {
  2194.                     const CDataStream& vMsg = *((*mi).second);
  2195.                     CTransaction tx;
  2196.                     CDataStream(vMsg) >> tx;
  2197.                     CInv inv(MSG_TX, tx.GetHash());
  2198.  
  2199.                     if (tx.AcceptTransaction(true))
  2200.                     {
  2201.                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
  2202.                         AddToWalletIfMine(tx, NULL);
  2203.                         RelayMessage(inv, vMsg);
  2204.                         mapAlreadyAskedFor.erase(inv);
  2205.                         vWorkQueue.push_back(inv.hash);
  2206.                     }
  2207.                 }
  2208.             }
  2209.  
  2210.             foreach(uint256 hash, vWorkQueue)
  2211.                 EraseOrphanTx(hash);
  2212.         }
  2213.         else if (fMissingInputs)
  2214.         {
  2215.             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
  2216.             AddOrphanTx(vMsg);
  2217.         }
  2218.     }
  2219.  
  2220.  
  2221.     else if (strCommand == "block")
  2222.     {
  2223.         auto_ptr<CBlock> pblock(new CBlock);
  2224.         vRecv >> *pblock;
  2225.  
  2226.         //// debug print
  2227.         printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());
  2228.         // pblock->print();
  2229.  
  2230.         CInv inv(MSG_BLOCK, pblock->GetHash());
  2231.         pfrom->AddInventoryKnown(inv);
  2232.  
  2233.         if (ProcessBlock(pfrom, pblock.release()))
  2234.             mapAlreadyAskedFor.erase(inv);
  2235.     }
  2236.  
  2237.  
  2238.     else if (strCommand == "getaddr")
  2239.     {
  2240.         // This includes all nodes that are currently online,
  2241.         // since they rebroadcast an addr every 24 hours
  2242.         pfrom->vAddrToSend.clear();
  2243.         int64 nSince = GetAdjustedTime() - 12 * 60 * 60; // in the last 12 hours
  2244.         CRITICAL_BLOCK(cs_mapAddresses)
  2245.         {
  2246.             unsigned int nSize = mapAddresses.size();
  2247.             foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
  2248.             {
  2249.                 if (fShutdown)
  2250.                     return true;
  2251.                 const CAddress& addr = item.second;
  2252.                 if (addr.nTime > nSince)
  2253.                     pfrom->PushAddress(addr);
  2254.             }
  2255.         }
  2256.     }
  2257.  
  2258.  
  2259.     else if (strCommand == "checkorder")
  2260.     {
  2261.         uint256 hashReply;
  2262.         CWalletTx order;
  2263.         vRecv >> hashReply >> order;
  2264.  
  2265.         /// we have a chance to check the order here
  2266.  
  2267.         // Keep giving the same key to the same ip until they use it
  2268.         if (!mapReuseKey.count(pfrom->addr.ip))
  2269.             mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
  2270.  
  2271.         // Send back approval of order and pubkey to use
  2272.         CScript scriptPubKey;
  2273.         scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
  2274.         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
  2275.     }
  2276.  
  2277.  
  2278.     else if (strCommand == "submitorder")
  2279.     {
  2280.         uint256 hashReply;
  2281.         CWalletTx wtxNew;
  2282.         vRecv >> hashReply >> wtxNew;
  2283.         wtxNew.fFromMe = false;
  2284.  
  2285.         // Broadcast
  2286.         if (!wtxNew.AcceptWalletTransaction())
  2287.         {
  2288.             pfrom->PushMessage("reply", hashReply, (int)1);
  2289.             return error("submitorder AcceptWalletTransaction() failed, returning error 1");
  2290.         }
  2291.         wtxNew.fTimeReceivedIsTxTime = true;
  2292.         AddToWallet(wtxNew);
  2293.         wtxNew.RelayWalletTransaction();
  2294.         mapReuseKey.erase(pfrom->addr.ip);
  2295.  
  2296.         // Send back confirmation
  2297.         pfrom->PushMessage("reply", hashReply, (int)0);
  2298.     }
  2299.  
  2300.  
  2301.     else if (strCommand == "reply")
  2302.     {
  2303.         uint256 hashReply;
  2304.         vRecv >> hashReply;
  2305.  
  2306.         CRequestTracker tracker;
  2307.         CRITICAL_BLOCK(pfrom->cs_mapRequests)
  2308.         {
  2309.             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
  2310.             if (mi != pfrom->mapRequests.end())
  2311.             {
  2312.                 tracker = (*mi).second;
  2313.                 pfrom->mapRequests.erase(mi);
  2314.             }
  2315.         }
  2316.         if (!tracker.IsNull())
  2317.             tracker.fn(tracker.param1, vRecv);
  2318.     }
  2319.  
  2320.  
  2321.     else if (strCommand == "ping")
  2322.     {
  2323.     }
  2324.  
  2325.  
  2326.     else
  2327.     {
  2328.         // Ignore unknown commands for extensibility
  2329.     }
  2330.  
  2331.  
  2332.     // Update the last seen time for this node's address
  2333.     if (pfrom->fNetworkNode)
  2334.         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
  2335.             AddressCurrentlyConnected(pfrom->addr);
  2336.  
  2337.  
  2338.     return true;
  2339. }
  2340.  
  2341.  
  2342.  
  2343.  
  2344.  
  2345.  
  2346.  
  2347.  
  2348.  
  2349. bool SendMessages(CNode* pto, bool fSendTrickle)
  2350. {
  2351.     CRITICAL_BLOCK(cs_main)
  2352.     {
  2353.         // Don't send anything until we get their version message
  2354.         if (pto->nVersion == 0)
  2355.             return true;
  2356.  
  2357.         // Keep-alive ping
  2358.         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
  2359.             pto->PushMessage("ping");
  2360.  
  2361.         // Address refresh broadcast
  2362.         static int64 nLastRebroadcast;
  2363.         if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
  2364.         {
  2365.             nLastRebroadcast = GetTime();
  2366.             CRITICAL_BLOCK(cs_vNodes)
  2367.             {
  2368.                 foreach(CNode* pnode, vNodes)
  2369.                 {
  2370.                     // Periodically clear setAddrKnown to allow refresh broadcasts
  2371.                     pnode->setAddrKnown.clear();
  2372.  
  2373.                     // Rebroadcast our address
  2374.                     if (addrLocalHost.IsRoutable() && !fUseProxy)
  2375.                         pnode->PushAddress(addrLocalHost);
  2376.                 }
  2377.             }
  2378.         }
  2379.  
  2380.         // Resend wallet transactions that haven't gotten in a block yet
  2381.         ResendWalletTransactions();
  2382.  
  2383.  
  2384.         //
  2385.         // Message: addr
  2386.         //
  2387.         if (fSendTrickle)
  2388.         {
  2389.             vector<CAddress> vAddr;
  2390.             vAddr.reserve(pto->vAddrToSend.size());
  2391.             foreach(const CAddress& addr, pto->vAddrToSend)
  2392.             {
  2393.                 // returns true if wasn't already contained in the set
  2394.                 if (pto->setAddrKnown.insert(addr).second)
  2395.                 {
  2396.                     vAddr.push_back(addr);
  2397.                     // receiver rejects addr messages larger than 1000
  2398.                     if (vAddr.size() >= 1000)
  2399.                     {
  2400.                         pto->PushMessage("addr", vAddr);
  2401.                         vAddr.clear();
  2402.                     }
  2403.                 }
  2404.             }
  2405.             pto->vAddrToSend.clear();
  2406.             if (!vAddr.empty())
  2407.                 pto->PushMessage("addr", vAddr);
  2408.         }
  2409.  
  2410.  
  2411.         //
  2412.         // Message: inventory
  2413.         //
  2414.         vector<CInv> vInv;
  2415.         vector<CInv> vInvWait;
  2416.         CRITICAL_BLOCK(pto->cs_inventory)
  2417.         {
  2418.             vInv.reserve(pto->vInventoryToSend.size());
  2419.             vInvWait.reserve(pto->vInventoryToSend.size());
  2420.             foreach(const CInv& inv, pto->vInventoryToSend)
  2421.             {
  2422.                 if (pto->setInventoryKnown.count(inv))
  2423.                     continue;
  2424.  
  2425.                 // trickle out tx inv to protect privacy
  2426.                 if (inv.type == MSG_TX && !fSendTrickle)
  2427.                 {
  2428.                     // 1/4 of tx invs blast to all immediately
  2429.                     static uint256 hashSalt;
  2430.                     if (hashSalt == 0)
  2431.                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
  2432.                     uint256 hashRand = inv.hash ^ hashSalt;
  2433.                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
  2434.                     bool fTrickleWait = ((hashRand & 3) != 0);
  2435.  
  2436.                     // always trickle our own transactions
  2437.                     if (!fTrickleWait)
  2438.                     {
  2439.                         TRY_CRITICAL_BLOCK(cs_mapWallet)
  2440.                         {
  2441.                             map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
  2442.                             if (mi != mapWallet.end())
  2443.                             {
  2444.                                 CWalletTx& wtx = (*mi).second;
  2445.                                 if (wtx.fFromMe)
  2446.                                     fTrickleWait = true;
  2447.                             }
  2448.                         }
  2449.                     }
  2450.  
  2451.                     if (fTrickleWait)
  2452.                     {
  2453.                         vInvWait.push_back(inv);
  2454.                         continue;
  2455.                     }
  2456.                 }
  2457.  
  2458.                 // returns true if wasn't already contained in the set
  2459.                 if (pto->setInventoryKnown.insert(inv).second)
  2460.                 {
  2461.                     vInv.push_back(inv);
  2462.                     if (vInv.size() >= 1000)
  2463.                     {
  2464.                         pto->PushMessage("inv", vInv);
  2465.                         vInv.clear();
  2466.                     }
  2467.                 }
  2468.             }
  2469.             pto->vInventoryToSend = vInvWait;
  2470.         }
  2471.         if (!vInv.empty())
  2472.             pto->PushMessage("inv", vInv);
  2473.  
  2474.  
  2475.         //
  2476.         // Message: getdata
  2477.         //
  2478.         vector<CInv> vGetData;
  2479.         int64 nNow = GetTime() * 1000000;
  2480.         CTxDB txdb("r");
  2481.         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  2482.         {
  2483.             const CInv& inv = (*pto->mapAskFor.begin()).second;
  2484.             if (!AlreadyHave(txdb, inv))
  2485.             {
  2486.                 printf("sending getdata: %s\n", inv.ToString().c_str());
  2487.                 vGetData.push_back(inv);
  2488.                 if (vGetData.size() >= 1000)
  2489.                 {
  2490.                     pto->PushMessage("getdata", vGetData);
  2491.                     vGetData.clear();
  2492.                 }
  2493.             }
  2494.             pto->mapAskFor.erase(pto->mapAskFor.begin());
  2495.         }
  2496.         if (!vGetData.empty())
  2497.             pto->PushMessage("getdata", vGetData);
  2498.  
  2499.     }
  2500.     return true;
  2501. }
  2502.  
  2503.  
  2504.  
  2505.  
  2506.  
  2507.  
  2508.  
  2509.  
  2510.  
  2511.  
  2512.  
  2513.  
  2514.  
  2515.  
  2516. //////////////////////////////////////////////////////////////////////////////
  2517. //
  2518. // BitcoinMiner
  2519. //
  2520.  
  2521. void GenerateBitcoins(bool fGenerate)
  2522. {
  2523.     if (fGenerateBitcoins != fGenerate)
  2524.     {
  2525.         fGenerateBitcoins = fGenerate;
  2526.         CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
  2527.         MainFrameRepaint();
  2528.     }
  2529.     if (fGenerateBitcoins)
  2530.     {
  2531.         int nProcessors = boost::thread::hardware_concurrency();
  2532.         printf("%d processors\n", nProcessors);
  2533.         if (nProcessors < 1)
  2534.             nProcessors = 1;
  2535.         if (fLimitProcessors && nProcessors > nLimitProcessors)
  2536.             nProcessors = nLimitProcessors;
  2537.         int nAddThreads = nProcessors - vnThreadsRunning[3];
  2538.         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
  2539.         for (int i = 0; i < nAddThreads; i++)
  2540.         {
  2541.             if (!CreateThread(ThreadBitcoinMiner, NULL))
  2542.                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
  2543.             Sleep(10);
  2544.         }
  2545.     }
  2546. }
  2547.  
  2548. void ThreadBitcoinMiner(void* parg)
  2549. {
  2550.     try
  2551.     {
  2552.         vnThreadsRunning[3]++;
  2553.         BitcoinMiner();
  2554.         vnThreadsRunning[3]--;
  2555.     }
  2556.     catch (std::exception& e) {
  2557.         vnThreadsRunning[3]--;
  2558.         PrintException(&e, "ThreadBitcoinMiner()");
  2559.     } catch (...) {
  2560.         vnThreadsRunning[3]--;
  2561.         PrintException(NULL, "ThreadBitcoinMiner()");
  2562.     }
  2563.     UIThreadCall(bind(CalledSetStatusBar, "", 0));
  2564.     nHPSTimerStart = 0;
  2565.     if (vnThreadsRunning[3] == 0)
  2566.         dHashesPerSec = 0;
  2567.     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
  2568. }
  2569.  
  2570. int FormatHashBlocks(void* pbuffer, unsigned int len)
  2571. {
  2572.     unsigned char* pdata = (unsigned char*)pbuffer;
  2573.     unsigned int blocks = 1 + ((len + 8) / 64);
  2574.     unsigned char* pend = pdata + 64 * blocks;
  2575.     memset(pdata + len, 0, 64 * blocks - len);
  2576.     pdata[len] = 0x80;
  2577.     unsigned int bits = len * 8;
  2578.     pend[-1] = (bits >> 0) & 0xff;
  2579.     pend[-2] = (bits >> 8) & 0xff;
  2580.     pend[-3] = (bits >> 16) & 0xff;
  2581.     pend[-4] = (bits >> 24) & 0xff;
  2582.     return blocks;
  2583. }
  2584.  
  2585. using CryptoPP::ByteReverse;
  2586.  
  2587. static const unsigned int pSHA256InitState[8] =
  2588. {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
  2589.  
  2590. inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
  2591. {
  2592.     memcpy(pstate, pinit, 32);
  2593.     CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
  2594. }
  2595.  
  2596. static const int NPAR = 32;
  2597. extern void Double_BlockSHA256(const void* pin, void* pout, const void* pinit, unsigned int hash[8][NPAR], const void* init2);
  2598.  
  2599.  
  2600.  
  2601.  
  2602. void BitcoinMiner()
  2603. {
  2604.     printf("BitcoinMiner started\n");
  2605.     SetThreadPriority(THREAD_PRIORITY_LOWEST);
  2606.  
  2607.     CKey key;
  2608.     key.MakeNewKey();
  2609.     CBigNum bnExtraNonce = 0;
  2610.     while (fGenerateBitcoins)
  2611.     {
  2612.         Sleep(50);
  2613.         if (fShutdown)
  2614.             return;
  2615.         while (vNodes.empty() || IsInitialBlockDownload())
  2616.         {
  2617.             Sleep(1000);
  2618.             if (fShutdown)
  2619.                 return;
  2620.             if (!fGenerateBitcoins)
  2621.                 return;
  2622.         }
  2623.  
  2624.         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
  2625.         CBlockIndex* pindexPrev = pindexBest;
  2626.         unsigned int nBits = GetNextWorkRequired(pindexPrev);
  2627.  
  2628.  
  2629.         //
  2630.         // Create coinbase tx
  2631.         //
  2632.         CTransaction txNew;
  2633.         txNew.vin.resize(1);
  2634.         txNew.vin[0].prevout.SetNull();
  2635.         txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
  2636.         txNew.vout.resize(1);
  2637.         txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
  2638.  
  2639.  
  2640.         //
  2641.         // Create new block
  2642.         //
  2643.         auto_ptr<CBlock> pblock(new CBlock());
  2644.         if (!pblock.get())
  2645.             return;
  2646.  
  2647.         // Add our coinbase tx as first transaction
  2648.         pblock->vtx.push_back(txNew);
  2649.  
  2650.         // Collect the latest transactions into the block
  2651.         int64 nFees = 0;
  2652.         CRITICAL_BLOCK(cs_main)
  2653.         CRITICAL_BLOCK(cs_mapTransactions)
  2654.         {
  2655.             CTxDB txdb("r");
  2656.             map<uint256, CTxIndex> mapTestPool;
  2657.             vector<char> vfAlreadyAdded(mapTransactions.size());
  2658.             bool fFoundSomething = true;
  2659.             unsigned int nBlockSize = 0;
  2660.             while (fFoundSomething && nBlockSize < MAX_SIZE/2)
  2661.             {
  2662.                 fFoundSomething = false;
  2663.                 unsigned int n = 0;
  2664.                 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
  2665.                 {
  2666.                     if (vfAlreadyAdded[n])
  2667.                         continue;
  2668.                     CTransaction& tx = (*mi).second;
  2669.                     if (tx.IsCoinBase() || !tx.IsFinal())
  2670.                         continue;
  2671.                     unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
  2672.                     if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)
  2673.                         continue;
  2674.  
  2675.                     // Transaction fee based on block size
  2676.                     int64 nMinFee = tx.GetMinFee(nBlockSize);
  2677.  
  2678.                     map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
  2679.                     if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
  2680.                         continue;
  2681.                     swap(mapTestPool, mapTestPoolTmp);
  2682.  
  2683.                     pblock->vtx.push_back(tx);
  2684.                     nBlockSize += nTxSize;
  2685.                     vfAlreadyAdded[n] = true;
  2686.                     fFoundSomething = true;
  2687.                 }
  2688.             }
  2689.         }
  2690.         pblock->nBits = nBits;
  2691.         pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(pindexPrev->nHeight+1, nFees);
  2692.         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
  2693.  
  2694.  
  2695.         //
  2696.         // Prebuild hash buffer
  2697.         //
  2698.         struct tmpworkspace
  2699.         {
  2700.             struct unnamed2
  2701.             {
  2702.                 int nVersion;
  2703.                 uint256 hashPrevBlock;
  2704.                 uint256 hashMerkleRoot;
  2705.                 unsigned int nTime;
  2706.                 unsigned int nBits;
  2707.                 unsigned int nNonce;
  2708.             }
  2709.             block;
  2710.             unsigned char pchPadding0[64];
  2711.             uint256 hash1;
  2712.             unsigned char pchPadding1[64];
  2713.         };
  2714.         char tmpbuf[sizeof(tmpworkspace)+16];
  2715.         tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
  2716.  
  2717.         tmp.block.nVersion       = pblock->nVersion;
  2718.         tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
  2719.         tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  2720.         tmp.block.nTime          = pblock->nTime          = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
  2721.         tmp.block.nBits          = pblock->nBits          = nBits;
  2722.         tmp.block.nNonce         = pblock->nNonce         = 0;
  2723.  
  2724.         unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
  2725.         unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
  2726.  
  2727.         // Byte swap all the input buffer
  2728.         for (int i = 0; i < sizeof(tmp)/4; i++)
  2729.             ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
  2730.  
  2731.         // Precalc the first half of the first hash, which stays constant
  2732.         uint256 midstatebuf[2];
  2733.         uint256& midstate = *alignup<16>(midstatebuf);
  2734.         SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
  2735.  
  2736.  
  2737.         //
  2738.         // Search
  2739.         //
  2740.         bool f4WaySSE2 = mapArgs.count("-4way");
  2741.         int64 nStart = GetTime();
  2742.         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  2743.         uint256 hashbuf[2];
  2744.         uint256& hash = *alignup<16>(hashbuf);
  2745.         loop
  2746.         {
  2747. #ifdef FOURWAYSSE2
  2748.             if (f4WaySSE2)
  2749.             {
  2750.                 // tcatm's 4-way SSE2 SHA-256
  2751.                 tmp.block.nNonce += NPAR;
  2752.                 unsigned int thashbuf[9][NPAR];
  2753.                 unsigned int (&thash)[9][NPAR] = *alignup<16>(&thashbuf);
  2754.                 Double_BlockSHA256((char*)&tmp.block + 64, &tmp.hash1, &midstate, thash, pSHA256InitState);
  2755.                 ((unsigned short*)&hash)[14] = 0xffff;
  2756.                 for (int j = 0; j < NPAR; j++)
  2757.                 {
  2758.                     if (thash[7][j] == 0)
  2759.                     {
  2760.                         for (int i = 0; i < sizeof(hash)/4; i++)
  2761.                             ((unsigned int*)&hash)[i] = thash[i][j];
  2762.                         pblock->nNonce = ByteReverse(tmp.block.nNonce + j);
  2763.                     }
  2764.                 }
  2765.             }
  2766.             else
  2767. #endif
  2768.             {
  2769.                 // Crypto++ SHA-256
  2770.                 tmp.block.nNonce++;
  2771.                 SHA256Transform(&tmp.hash1, (char*)&tmp.block + 64, &midstate);
  2772.                 SHA256Transform(&hash, &tmp.hash1, pSHA256InitState);
  2773.             }
  2774.  
  2775.             if (((unsigned short*)&hash)[14] == 0)
  2776.             {
  2777.                 // Byte swap the result after preliminary check
  2778.                 for (int i = 0; i < sizeof(hash)/4; i++)
  2779.                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
  2780.  
  2781.                 if (hash <= hashTarget)
  2782.                 {
  2783. #ifdef FOURWAYSSE2
  2784.                     if (!f4WaySSE2)
  2785. #endif
  2786.                         pblock->nNonce = ByteReverse(tmp.block.nNonce);
  2787.                     assert(hash == pblock->GetHash());
  2788.  
  2789.                         //// debug print
  2790.                         printf("BitcoinMiner:\n");
  2791.                         printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
  2792.                         pblock->print();
  2793.                         printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
  2794.                         printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
  2795.  
  2796.                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
  2797.                     CRITICAL_BLOCK(cs_main)
  2798.                     {
  2799.                         if (pindexPrev == pindexBest)
  2800.                         {
  2801.                             // Save key
  2802.                             if (!AddKey(key))
  2803.                                 return;
  2804.                             key.MakeNewKey();
  2805.  
  2806.                             // Track how many getdata requests this block gets
  2807.                             CRITICAL_BLOCK(cs_mapRequestCount)
  2808.                                 mapRequestCount[pblock->GetHash()] = 0;
  2809.  
  2810.                             // Process this block the same as if we had received it from another node
  2811.                             if (!ProcessBlock(NULL, pblock.release()))
  2812.                                 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
  2813.                         }
  2814.                     }
  2815.                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
  2816.  
  2817.                     Sleep(500);
  2818.                     break;
  2819.                 }
  2820.             }
  2821.  
  2822.             // Update nTime every few seconds
  2823.             const unsigned int nMask = 0xffff;
  2824.             const int nHashesPerCycle = (nMask+1);
  2825.             if ((tmp.block.nNonce & nMask) == 0)
  2826.             {
  2827.                 // Meter hashes/sec
  2828.                 static int nCycleCounter;
  2829.                 if (nHPSTimerStart == 0)
  2830.                 {
  2831.                     nHPSTimerStart = GetTimeMillis();
  2832.                     nCycleCounter = 0;
  2833.                 }
  2834.                 else
  2835.                     nCycleCounter++;
  2836.                 if (GetTimeMillis() - nHPSTimerStart > 4000)
  2837.                 {
  2838.                     static CCriticalSection cs;
  2839.                     CRITICAL_BLOCK(cs)
  2840.                     {
  2841.                         if (GetTimeMillis() - nHPSTimerStart > 4000)
  2842.                         {
  2843.                             dHashesPerSec = 1000.0 * nHashesPerCycle * nCycleCounter / (GetTimeMillis() - nHPSTimerStart);
  2844.                             nHPSTimerStart = GetTimeMillis();
  2845.                             nCycleCounter = 0;
  2846.                             string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
  2847.                             UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));
  2848.                             static int64 nLogTime;
  2849.                             if (GetTime() - nLogTime > 30 * 60)
  2850.                             {
  2851.                                 nLogTime = GetTime();
  2852.                                 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
  2853.                                 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
  2854.                             }
  2855.                         }
  2856.                     }
  2857.                 }
  2858.  
  2859.                 // Check for stop or if block needs to be rebuilt
  2860.                 if (fShutdown)
  2861.                     return;
  2862.                 if (!fGenerateBitcoins)
  2863.                     return;
  2864.                 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
  2865.                     return;
  2866.                 if (vNodes.empty())
  2867.                     break;
  2868.                 if (tmp.block.nNonce == 0)
  2869.                     break;
  2870.                 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  2871.                     break;
  2872.                 if (pindexPrev != pindexBest)
  2873.                     break;
  2874.  
  2875.                 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  2876.                 tmp.block.nTime = ByteReverse(pblock->nTime);
  2877.             }
  2878.         }
  2879.     }
  2880. }
  2881.  
  2882.  
  2883.  
  2884.  
  2885.  
  2886.  
  2887.  
  2888.  
  2889.  
  2890.  
  2891.  
  2892.  
  2893.  
  2894.  
  2895.  
  2896.  
  2897.  
  2898.  
  2899. //////////////////////////////////////////////////////////////////////////////
  2900. //
  2901. // Actions
  2902. //
  2903.  
  2904.  
  2905. int64 GetBalance()
  2906. {
  2907.     int64 nStart = GetTimeMillis();
  2908.  
  2909.     int64 nTotal = 0;
  2910.     CRITICAL_BLOCK(cs_mapWallet)
  2911.     {
  2912.         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
  2913.         {
  2914.             CWalletTx* pcoin = &(*it).second;
  2915.             if (!pcoin->IsFinal() || pcoin->fSpent)
  2916.                 continue;
  2917.             nTotal += pcoin->GetCredit(true);
  2918.         }
  2919.     }
  2920.  
  2921.     //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
  2922.     return nTotal;
  2923. }
  2924.  
  2925.  
  2926. int GetRandInt(int nMax)
  2927. {
  2928.     return GetRand(nMax);
  2929. }
  2930.  
  2931. bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
  2932. {
  2933.     setCoinsRet.clear();
  2934.  
  2935.     // List of values less than target
  2936.     int64 nLowestLarger = INT64_MAX;
  2937.     CWalletTx* pcoinLowestLarger = NULL;
  2938.     vector<pair<int64, CWalletTx*> > vValue;
  2939.     int64 nTotalLower = 0;
  2940.  
  2941.     CRITICAL_BLOCK(cs_mapWallet)
  2942.     {
  2943.        vector<CWalletTx*> vCoins;
  2944.        vCoins.reserve(mapWallet.size());
  2945.        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
  2946.            vCoins.push_back(&(*it).second);
  2947.        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
  2948.  
  2949.        foreach(CWalletTx* pcoin, vCoins)
  2950.        {
  2951.             if (!pcoin->IsFinal() || pcoin->fSpent)
  2952.                 continue;
  2953.             int64 n = pcoin->GetCredit();
  2954.             if (n <= 0)
  2955.                 continue;
  2956.             if (n < nTargetValue)
  2957.             {
  2958.                 vValue.push_back(make_pair(n, pcoin));
  2959.                 nTotalLower += n;
  2960.             }
  2961.             else if (n == nTargetValue)
  2962.             {
  2963.                 setCoinsRet.insert(pcoin);
  2964.                 return true;
  2965.             }
  2966.             else if (n < nLowestLarger)
  2967.             {
  2968.                 nLowestLarger = n;
  2969.                 pcoinLowestLarger = pcoin;
  2970.             }
  2971.         }
  2972.     }
  2973.  
  2974.     if (nTotalLower < nTargetValue)
  2975.     {
  2976.         if (pcoinLowestLarger == NULL)
  2977.             return false;
  2978.         setCoinsRet.insert(pcoinLowestLarger);
  2979.         return true;
  2980.     }
  2981.  
  2982.     // Solve subset sum by stochastic approximation
  2983.     sort(vValue.rbegin(), vValue.rend());
  2984.     vector<char> vfIncluded;
  2985.     vector<char> vfBest(vValue.size(), true);
  2986.     int64 nBest = nTotalLower;
  2987.  
  2988.     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
  2989.     {
  2990.         vfIncluded.assign(vValue.size(), false);
  2991.         int64 nTotal = 0;
  2992.         bool fReachedTarget = false;
  2993.         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
  2994.         {
  2995.             for (int i = 0; i < vValue.size(); i++)
  2996.             {
  2997.                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
  2998.                 {
  2999.                     nTotal += vValue[i].first;
  3000.                     vfIncluded[i] = true;
  3001.                     if (nTotal >= nTargetValue)
  3002.                     {
  3003.                         fReachedTarget = true;
  3004.                         if (nTotal < nBest)
  3005.                         {
  3006.                             nBest = nTotal;
  3007.                             vfBest = vfIncluded;
  3008.                         }
  3009.                         nTotal -= vValue[i].first;
  3010.                         vfIncluded[i] = false;
  3011.                     }
  3012.                 }
  3013.             }
  3014.         }
  3015.     }
  3016.  
  3017.     // If the next larger is still closer, return it
  3018.     if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
  3019.         setCoinsRet.insert(pcoinLowestLarger);
  3020.     else
  3021.     {
  3022.         for (int i = 0; i < vValue.size(); i++)
  3023.             if (vfBest[i])
  3024.                 setCoinsRet.insert(vValue[i].second);
  3025.  
  3026.         //// debug print
  3027.         printf("SelectCoins() best subset: ");
  3028.         for (int i = 0; i < vValue.size(); i++)
  3029.             if (vfBest[i])
  3030.                 printf("%s ", FormatMoney(vValue[i].first).c_str());
  3031.         printf("total %s\n", FormatMoney(nBest).c_str());
  3032.     }
  3033.  
  3034.     return true;
  3035. }
  3036.  
  3037.  
  3038.  
  3039.  
  3040. bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
  3041. {
  3042.     nFeeRequiredRet = 0;
  3043.     CRITICAL_BLOCK(cs_main)
  3044.     {
  3045.         // txdb must be opened before the mapWallet lock
  3046.         CTxDB txdb("r");
  3047.         CRITICAL_BLOCK(cs_mapWallet)
  3048.         {
  3049.             int64 nFee = nTransactionFee;
  3050.             loop
  3051.             {
  3052.                 wtxNew.vin.clear();
  3053.                 wtxNew.vout.clear();
  3054.                 wtxNew.fFromMe = true;
  3055.                 if (nValue < 0)
  3056.                     return false;
  3057.                 int64 nValueOut = nValue;
  3058.                 int64 nTotalValue = nValue + nFee;
  3059.  
  3060.                 // Choose coins to use
  3061.                 set<CWalletTx*> setCoins;
  3062.                 if (!SelectCoins(nTotalValue, setCoins))
  3063.                     return false;
  3064.                 int64 nValueIn = 0;
  3065.                 foreach(CWalletTx* pcoin, setCoins)
  3066.                     nValueIn += pcoin->GetCredit();
  3067.  
  3068.                 // Fill a vout to the payee
  3069.                 bool fChangeFirst = GetRand(2);
  3070.                 if (!fChangeFirst)
  3071.                     wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
  3072.  
  3073.                 // Fill a vout back to self with any change
  3074.                 if (nValueIn > nTotalValue)
  3075.                 {
  3076.                     // Note: We use a new key here to keep it from being obvious which side is the change.
  3077.                     //  The drawback is that by not reusing a previous key, the change may be lost if a
  3078.                     //  backup is restored, if the backup doesn't have the new private key for the change.
  3079.                     //  If we reused the old key, it would be possible to add code to look for and
  3080.                     //  rediscover unknown transactions that were written with keys of ours to recover
  3081.                     //  post-backup change.
  3082.  
  3083.                     // New private key
  3084.                     if (keyRet.IsNull())
  3085.                         keyRet.MakeNewKey();
  3086.  
  3087.                     // Fill a vout to ourself, using same address type as the payment
  3088.                     CScript scriptChange;
  3089.                     if (scriptPubKey.GetBitcoinAddressHash160() != 0)
  3090.                         scriptChange.SetBitcoinAddress(keyRet.GetPubKey());
  3091.                     else
  3092.                         scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;
  3093.                     wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));
  3094.                 }
  3095.  
  3096.                 // Fill a vout to the payee
  3097.                 if (fChangeFirst)
  3098.                     wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
  3099.  
  3100.                 // Fill vin
  3101.                 foreach(CWalletTx* pcoin, setCoins)
  3102.                     for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
  3103.                         if (pcoin->vout[nOut].IsMine())
  3104.                             wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
  3105.  
  3106.                 // Sign
  3107.                 int nIn = 0;
  3108.                 foreach(CWalletTx* pcoin, setCoins)
  3109.                     for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
  3110.                         if (pcoin->vout[nOut].IsMine())
  3111.                             if (!SignSignature(*pcoin, wtxNew, nIn++))
  3112.                                 return false;
  3113.  
  3114.                 // Check that enough fee is included
  3115.                 if (nFee < wtxNew.GetMinFee())
  3116.                 {
  3117.                     nFee = nFeeRequiredRet = wtxNew.GetMinFee();
  3118.                     continue;
  3119.                 }
  3120.  
  3121.                 // Fill vtxPrev by copying from previous transactions vtxPrev
  3122.                 wtxNew.AddSupportingTransactions(txdb);
  3123.                 wtxNew.fTimeReceivedIsTxTime = true;
  3124.  
  3125.                 break;
  3126.             }
  3127.         }
  3128.     }
  3129.     return true;
  3130. }
  3131.  
  3132. // Call after CreateTransaction unless you want to abort
  3133. bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)
  3134. {
  3135.     CRITICAL_BLOCK(cs_main)
  3136.     {
  3137.         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
  3138.         CRITICAL_BLOCK(cs_mapWallet)
  3139.         {
  3140.             // This is only to keep the database open to defeat the auto-flush for the
  3141.             // duration of this scope.  This is the only place where this optimization
  3142.             // maybe makes sense; please don't do it anywhere else.
  3143.             CWalletDB walletdb("r");
  3144.  
  3145.             // Add the change's private key to wallet
  3146.             if (!key.IsNull() && !AddKey(key))
  3147.                 throw runtime_error("CommitTransaction() : AddKey failed\n");
  3148.  
  3149.             // Add tx to wallet, because if it has change it's also ours,
  3150.             // otherwise just for transaction history.
  3151.             AddToWallet(wtxNew);
  3152.  
  3153.             // Mark old coins as spent
  3154.             set<CWalletTx*> setCoins;
  3155.             foreach(const CTxIn& txin, wtxNew.vin)
  3156.                 setCoins.insert(&mapWallet[txin.prevout.hash]);
  3157.             foreach(CWalletTx* pcoin, setCoins)
  3158.             {
  3159.                 pcoin->fSpent = true;
  3160.                 pcoin->WriteToDisk();
  3161.                 vWalletUpdated.push_back(pcoin->GetHash());
  3162.             }
  3163.         }
  3164.  
  3165.         // Track how many getdata requests our transaction gets
  3166.         CRITICAL_BLOCK(cs_mapRequestCount)
  3167.             mapRequestCount[wtxNew.GetHash()] = 0;
  3168.  
  3169.         // Broadcast
  3170.         if (!wtxNew.AcceptTransaction())
  3171.         {
  3172.             // This must not fail. The transaction has already been signed and recorded.
  3173.             printf("CommitTransaction() : Error: Transaction not valid");
  3174.             return false;
  3175.         }
  3176.         wtxNew.RelayWalletTransaction();
  3177.     }
  3178.     MainFrameRepaint();
  3179.     return true;
  3180. }
  3181.  
  3182.  
  3183.  
  3184.  
  3185. string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
  3186. {
  3187.     CRITICAL_BLOCK(cs_main)
  3188.     {
  3189.         CKey key;
  3190.         int64 nFeeRequired;
  3191.         if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
  3192.         {
  3193.             string strError;
  3194.             if (nValue + nFeeRequired > GetBalance())
  3195.                 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s  "), FormatMoney(nFeeRequired).c_str());
  3196.             else
  3197.                 strError = _("Error: Transaction creation failed  ");
  3198.             printf("SendMoney() : %s", strError.c_str());
  3199.             return strError;
  3200.         }
  3201.  
  3202.         if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
  3203.             return "ABORTED";
  3204.  
  3205.         if (!CommitTransaction(wtxNew, key))
  3206.             return _("Error: The transaction was rejected.  This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
  3207.     }
  3208.     MainFrameRepaint();
  3209.     return "";
  3210. }
  3211.  
  3212.  
  3213.  
  3214. string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
  3215. {
  3216.     // Check amount
  3217.     if (nValue <= 0)
  3218.         return _("Invalid amount");
  3219.     if (nValue + nTransactionFee > GetBalance())
  3220.         return _("Insufficient funds");
  3221.  
  3222.     // Parse bitcoin address
  3223.     CScript scriptPubKey;
  3224.     if (!scriptPubKey.SetBitcoinAddress(strAddress))
  3225.         return _("Invalid bitcoin address");
  3226.  
  3227.     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
  3228. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement