-
+ E37A9EB6A10745A2B0F52AACD915809961D5663185CCE5792862579D340D6C98C1633A669A04FCD76835839EE13FDA982E9B8ED3F190DE24583F1A50167DEE3Bbitcoin/src/main.cpp(0 . 0)(1 . 3250)
9306 // Copyright (c) 2009-2010 Satoshi Nakamoto
9307 // Copyright (c) 2009-2012 The Bitcoin developers
9308 // Distributed under the MIT/X11 software license, see the accompanying
9309 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
9310 #include "headers.h"
9311 #include "checkpoints.h"
9312 #include "db.h"
9313 #include "net.h"
9314 #include "init.h"
9315 #include <boost/filesystem.hpp>
9316 #include <boost/filesystem/fstream.hpp>
9317
9318 using namespace std;
9319 using namespace boost;
9320
9321 //
9322 // Global state
9323 //
9324
9325 CCriticalSection cs_setpwalletRegistered;
9326 set<CWallet*> setpwalletRegistered;
9327
9328 CCriticalSection cs_main;
9329
9330 static map<uint256, CTransaction> mapTransactions;
9331 CCriticalSection cs_mapTransactions;
9332 unsigned int nTransactionsUpdated = 0;
9333 map<COutPoint, CInPoint> mapNextTx;
9334
9335 map<uint256, CBlockIndex*> mapBlockIndex;
9336 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
9337 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
9338 CBlockIndex* pindexGenesisBlock = NULL;
9339 int nBestHeight = -1;
9340 CBigNum bnBestChainWork = 0;
9341 CBigNum bnBestInvalidWork = 0;
9342 uint256 hashBestChain = 0;
9343 CBlockIndex* pindexBest = NULL;
9344 int64 nTimeBestReceived = 0;
9345
9346 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
9347
9348 map<uint256, CBlock*> mapOrphanBlocks;
9349 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
9350
9351 map<uint256, CDataStream*> mapOrphanTransactions;
9352 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
9353
9354
9355 double dHashesPerSec;
9356 int64 nHPSTimerStart;
9357
9358 // Settings
9359 int fGenerateBitcoins = false;
9360 int64 nTransactionFee = 0;
9361 int fLimitProcessors = false;
9362 int nLimitProcessors = 1;
9363 int fMinimizeToTray = true;
9364 int fMinimizeOnClose = true;
9365 #if USE_UPNP
9366 int fUseUPnP = true;
9367 #else
9368 int fUseUPnP = false;
9369 #endif
9370
9371
9372 //////////////////////////////////////////////////////////////////////////////
9373 //
9374 // dispatching functions
9375 //
9376
9377 // These functions dispatch to one or all registered wallets
9378
9379
9380 void RegisterWallet(CWallet* pwalletIn)
9381 {
9382 CRITICAL_BLOCK(cs_setpwalletRegistered)
9383 {
9384 setpwalletRegistered.insert(pwalletIn);
9385 }
9386 }
9387
9388 void UnregisterWallet(CWallet* pwalletIn)
9389 {
9390 CRITICAL_BLOCK(cs_setpwalletRegistered)
9391 {
9392 setpwalletRegistered.erase(pwalletIn);
9393 }
9394 }
9395
9396 // check whether the passed transaction is from us
9397 bool static IsFromMe(CTransaction& tx)
9398 {
9399 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9400 if (pwallet->IsFromMe(tx))
9401 return true;
9402 return false;
9403 }
9404
9405 // get the wallet transaction with the given hash (if it exists)
9406 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
9407 {
9408 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9409 if (pwallet->GetTransaction(hashTx,wtx))
9410 return true;
9411 return false;
9412 }
9413
9414 // erases transaction with the given hash from all wallets
9415 void static EraseFromWallets(uint256 hash)
9416 {
9417 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9418 pwallet->EraseFromWallet(hash);
9419 }
9420
9421 // make sure all wallets know about the given transaction, in the given block
9422 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
9423 {
9424 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9425 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
9426 }
9427
9428 // notify wallets about a new best chain
9429 void static SetBestChain(const CBlockLocator& loc)
9430 {
9431 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9432 pwallet->SetBestChain(loc);
9433 }
9434
9435 // notify wallets about an updated transaction
9436 void static UpdatedTransaction(const uint256& hashTx)
9437 {
9438 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9439 pwallet->UpdatedTransaction(hashTx);
9440 }
9441
9442 // dump all wallets
9443 void static PrintWallets(const CBlock& block)
9444 {
9445 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9446 pwallet->PrintWallet(block);
9447 }
9448
9449 // notify wallets about an incoming inventory (for request counts)
9450 void static Inventory(const uint256& hash)
9451 {
9452 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9453 pwallet->Inventory(hash);
9454 }
9455
9456 // ask wallets to resend their transactions
9457 void static ResendWalletTransactions()
9458 {
9459 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
9460 pwallet->ResendWalletTransactions();
9461 }
9462
9463
9464
9465
9466
9467
9468
9469 //////////////////////////////////////////////////////////////////////////////
9470 //
9471 // mapOrphanTransactions
9472 //
9473
9474 void AddOrphanTx(const CDataStream& vMsg)
9475 {
9476 CTransaction tx;
9477 CDataStream(vMsg) >> tx;
9478 uint256 hash = tx.GetHash();
9479 if (mapOrphanTransactions.count(hash))
9480 return;
9481
9482 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
9483 BOOST_FOREACH(const CTxIn& txin, tx.vin)
9484 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
9485 }
9486
9487 void static EraseOrphanTx(uint256 hash)
9488 {
9489 if (!mapOrphanTransactions.count(hash))
9490 return;
9491 const CDataStream* pvMsg = mapOrphanTransactions[hash];
9492 CTransaction tx;
9493 CDataStream(*pvMsg) >> tx;
9494 BOOST_FOREACH(const CTxIn& txin, tx.vin)
9495 {
9496 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
9497 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
9498 {
9499 if ((*mi).second == pvMsg)
9500 mapOrphanTransactionsByPrev.erase(mi++);
9501 else
9502 mi++;
9503 }
9504 }
9505 delete pvMsg;
9506 mapOrphanTransactions.erase(hash);
9507 }
9508
9509 int LimitOrphanTxSize(int nMaxOrphans)
9510 {
9511 int nEvicted = 0;
9512 while (mapOrphanTransactions.size() > nMaxOrphans)
9513 {
9514 // Evict a random orphan:
9515 std::vector<unsigned char> randbytes(32);
9516 RAND_bytes(&randbytes[0], 32);
9517 uint256 randomhash(randbytes);
9518 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
9519 if (it == mapOrphanTransactions.end())
9520 it = mapOrphanTransactions.begin();
9521 EraseOrphanTx(it->first);
9522 ++nEvicted;
9523 }
9524 return nEvicted;
9525 }
9526
9527
9528
9529
9530
9531
9532
9533 //////////////////////////////////////////////////////////////////////////////
9534 //
9535 // CTransaction and CTxIndex
9536 //
9537
9538 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
9539 {
9540 SetNull();
9541 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
9542 return false;
9543 if (!ReadFromDisk(txindexRet.pos))
9544 return false;
9545 if (prevout.n >= vout.size())
9546 {
9547 SetNull();
9548 return false;
9549 }
9550 return true;
9551 }
9552
9553 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
9554 {
9555 CTxIndex txindex;
9556 return ReadFromDisk(txdb, prevout, txindex);
9557 }
9558
9559 bool CTransaction::ReadFromDisk(COutPoint prevout)
9560 {
9561 CTxDB txdb("r");
9562 CTxIndex txindex;
9563 return ReadFromDisk(txdb, prevout, txindex);
9564 }
9565
9566
9567
9568 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
9569 {
9570 if (fClient)
9571 {
9572 if (hashBlock == 0)
9573 return 0;
9574 }
9575 else
9576 {
9577 CBlock blockTmp;
9578 if (pblock == NULL)
9579 {
9580 // Load the block this tx is in
9581 CTxIndex txindex;
9582 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
9583 return 0;
9584 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
9585 return 0;
9586 pblock = &blockTmp;
9587 }
9588
9589 // Update the tx's hashBlock
9590 hashBlock = pblock->GetHash();
9591
9592 // Locate the transaction
9593 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
9594 if (pblock->vtx[nIndex] == *(CTransaction*)this)
9595 break;
9596 if (nIndex == pblock->vtx.size())
9597 {
9598 vMerkleBranch.clear();
9599 nIndex = -1;
9600 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
9601 return 0;
9602 }
9603
9604 // Fill in merkle branch
9605 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
9606 }
9607
9608 // Is the tx in a block that's in the main chain
9609 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
9610 if (mi == mapBlockIndex.end())
9611 return 0;
9612 CBlockIndex* pindex = (*mi).second;
9613 if (!pindex || !pindex->IsInMainChain())
9614 return 0;
9615
9616 return pindexBest->nHeight - pindex->nHeight + 1;
9617 }
9618
9619
9620
9621
9622
9623
9624
9625 bool CTransaction::CheckTransaction() const
9626 {
9627 // Basic checks that don't depend on any context
9628 if (vin.empty())
9629 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
9630 if (vout.empty())
9631 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
9632 // Size limits
9633 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
9634 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
9635
9636 // Check for negative or overflow output values
9637 int64 nValueOut = 0;
9638 BOOST_FOREACH(const CTxOut& txout, vout)
9639 {
9640 if (txout.nValue < 0)
9641 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
9642 if (txout.nValue > MAX_MONEY)
9643 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
9644 nValueOut += txout.nValue;
9645 if (!MoneyRange(nValueOut))
9646 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
9647 }
9648
9649 // Check for duplicate inputs
9650 set<COutPoint> vInOutPoints;
9651 BOOST_FOREACH(const CTxIn& txin, vin)
9652 {
9653 if (vInOutPoints.count(txin.prevout))
9654 return false;
9655 vInOutPoints.insert(txin.prevout);
9656 }
9657
9658 if (IsCoinBase())
9659 {
9660 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
9661 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
9662 }
9663 else
9664 {
9665 BOOST_FOREACH(const CTxIn& txin, vin)
9666 if (txin.prevout.IsNull())
9667 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
9668 }
9669
9670 return true;
9671 }
9672
9673 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
9674 {
9675 if (pfMissingInputs)
9676 *pfMissingInputs = false;
9677
9678 if (!CheckTransaction())
9679 return error("AcceptToMemoryPool() : CheckTransaction failed");
9680
9681 // Coinbase is only valid in a block, not as a loose transaction
9682 if (IsCoinBase())
9683 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
9684
9685 // To help v0.1.5 clients who would see it as a negative number
9686 if ((int64)nLockTime > INT_MAX)
9687 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
9688
9689 // Safety limits
9690 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
9691 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
9692 // attacks disallow transactions with more than one SigOp per 34 bytes.
9693 // 34 bytes because a TxOut is:
9694 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
9695 if (GetSigOpCount() > nSize / 34 || nSize < 100)
9696 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
9697
9698 // Rather not work on nonstandard transactions (unless -testnet)
9699 if (!fTestNet && !IsStandard())
9700 return error("AcceptToMemoryPool() : nonstandard transaction type");
9701
9702 // Do we already have it?
9703 uint256 hash = GetHash();
9704 CRITICAL_BLOCK(cs_mapTransactions)
9705 if (mapTransactions.count(hash))
9706 return false;
9707 if (fCheckInputs)
9708 if (txdb.ContainsTx(hash))
9709 return false;
9710
9711 // Check for conflicts with in-memory transactions
9712 CTransaction* ptxOld = NULL;
9713 for (int i = 0; i < vin.size(); i++)
9714 {
9715 COutPoint outpoint = vin[i].prevout;
9716 if (mapNextTx.count(outpoint))
9717 {
9718 // Disable replacement feature for now
9719 return false;
9720
9721 // Allow replacing with a newer version of the same transaction
9722 if (i != 0)
9723 return false;
9724 ptxOld = mapNextTx[outpoint].ptx;
9725 if (ptxOld->IsFinal())
9726 return false;
9727 if (!IsNewerThan(*ptxOld))
9728 return false;
9729 for (int i = 0; i < vin.size(); i++)
9730 {
9731 COutPoint outpoint = vin[i].prevout;
9732 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
9733 return false;
9734 }
9735 break;
9736 }
9737 }
9738
9739 if (fCheckInputs)
9740 {
9741 // Check against previous transactions
9742 map<uint256, CTxIndex> mapUnused;
9743 int64 nFees = 0;
9744 bool fInvalid = false;
9745 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, 0, fInvalid))
9746 {
9747 if (fInvalid)
9748 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
9749 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
9750 }
9751
9752 // Don't accept it if it can't get into a block
9753 if (nFees < GetMinFee(1000, true, true))
9754 return error("AcceptToMemoryPool() : not enough fees");
9755
9756 // Continuously rate-limit free transactions
9757 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
9758 // be annoying or make other's transactions take longer to confirm.
9759 if (nFees < MIN_RELAY_TX_FEE)
9760 {
9761 static CCriticalSection cs;
9762 static double dFreeCount;
9763 static int64 nLastTime;
9764 int64 nNow = GetTime();
9765
9766 CRITICAL_BLOCK(cs)
9767 {
9768 // Use an exponentially decaying ~10-minute window:
9769 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
9770 nLastTime = nNow;
9771 // -limitfreerelay unit is thousand-bytes-per-minute
9772 // At default rate it would take over a month to fill 1GB
9773 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
9774 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
9775 if (fDebug)
9776 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
9777 dFreeCount += nSize;
9778 }
9779 }
9780 }
9781
9782 // Store transaction in memory
9783 CRITICAL_BLOCK(cs_mapTransactions)
9784 {
9785 if (ptxOld)
9786 {
9787 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
9788 ptxOld->RemoveFromMemoryPool();
9789 }
9790 AddToMemoryPoolUnchecked();
9791 }
9792
9793 ///// are we sure this is ok when loading transactions or restoring block txes
9794 // If updated, erase old tx from wallet
9795 if (ptxOld)
9796 EraseFromWallets(ptxOld->GetHash());
9797
9798 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
9799 return true;
9800 }
9801
9802 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
9803 {
9804 CTxDB txdb("r");
9805 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
9806 }
9807
9808 bool CTransaction::AddToMemoryPoolUnchecked()
9809 {
9810 // Add to memory pool without checking anything. Don't call this directly,
9811 // call AcceptToMemoryPool to properly check the transaction first.
9812 CRITICAL_BLOCK(cs_mapTransactions)
9813 {
9814 uint256 hash = GetHash();
9815 mapTransactions[hash] = *this;
9816 for (int i = 0; i < vin.size(); i++)
9817 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
9818 nTransactionsUpdated++;
9819 }
9820 return true;
9821 }
9822
9823
9824 bool CTransaction::RemoveFromMemoryPool()
9825 {
9826 // Remove transaction from memory pool
9827 CRITICAL_BLOCK(cs_mapTransactions)
9828 {
9829 BOOST_FOREACH(const CTxIn& txin, vin)
9830 mapNextTx.erase(txin.prevout);
9831 mapTransactions.erase(GetHash());
9832 nTransactionsUpdated++;
9833 }
9834 return true;
9835 }
9836
9837
9838
9839
9840
9841
9842 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
9843 {
9844 if (hashBlock == 0 || nIndex == -1)
9845 return 0;
9846
9847 // Find the block it claims to be in
9848 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
9849 if (mi == mapBlockIndex.end())
9850 return 0;
9851 CBlockIndex* pindex = (*mi).second;
9852 if (!pindex || !pindex->IsInMainChain())
9853 return 0;
9854
9855 // Make sure the merkle branch connects to this block
9856 if (!fMerkleVerified)
9857 {
9858 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
9859 return 0;
9860 fMerkleVerified = true;
9861 }
9862
9863 nHeightRet = pindex->nHeight;
9864 return pindexBest->nHeight - pindex->nHeight + 1;
9865 }
9866
9867
9868 int CMerkleTx::GetBlocksToMaturity() const
9869 {
9870 if (!IsCoinBase())
9871 return 0;
9872 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
9873 }
9874
9875
9876 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
9877 {
9878 if (fClient)
9879 {
9880 if (!IsInMainChain() && !ClientConnectInputs())
9881 return false;
9882 return CTransaction::AcceptToMemoryPool(txdb, false);
9883 }
9884 else
9885 {
9886 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
9887 }
9888 }
9889
9890 bool CMerkleTx::AcceptToMemoryPool()
9891 {
9892 CTxDB txdb("r");
9893 return AcceptToMemoryPool(txdb);
9894 }
9895
9896
9897
9898 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
9899 {
9900 CRITICAL_BLOCK(cs_mapTransactions)
9901 {
9902 // Add previous supporting transactions first
9903 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
9904 {
9905 if (!tx.IsCoinBase())
9906 {
9907 uint256 hash = tx.GetHash();
9908 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
9909 tx.AcceptToMemoryPool(txdb, fCheckInputs);
9910 }
9911 }
9912 return AcceptToMemoryPool(txdb, fCheckInputs);
9913 }
9914 return false;
9915 }
9916
9917 bool CWalletTx::AcceptWalletTransaction()
9918 {
9919 CTxDB txdb("r");
9920 return AcceptWalletTransaction(txdb);
9921 }
9922
9923 int CTxIndex::GetDepthInMainChain() const
9924 {
9925 // Read block header
9926 CBlock block;
9927 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
9928 return 0;
9929 // Find the block in the index
9930 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
9931 if (mi == mapBlockIndex.end())
9932 return 0;
9933 CBlockIndex* pindex = (*mi).second;
9934 if (!pindex || !pindex->IsInMainChain())
9935 return 0;
9936 return 1 + nBestHeight - pindex->nHeight;
9937 }
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948 //////////////////////////////////////////////////////////////////////////////
9949 //
9950 // CBlock and CBlockIndex
9951 //
9952
9953 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
9954 {
9955 if (!fReadTransactions)
9956 {
9957 *this = pindex->GetBlockHeader();
9958 return true;
9959 }
9960 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
9961 return false;
9962 if (GetHash() != pindex->GetBlockHash())
9963 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
9964 return true;
9965 }
9966
9967 uint256 static GetOrphanRoot(const CBlock* pblock)
9968 {
9969 // Work back to the first block in the orphan chain
9970 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
9971 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
9972 return pblock->GetHash();
9973 }
9974
9975 int64 static GetBlockValue(int nHeight, int64 nFees)
9976 {
9977 int64 nSubsidy = 50 * COIN;
9978
9979 // Subsidy is cut in half every 4 years
9980 nSubsidy >>= (nHeight / 210000);
9981
9982 return nSubsidy + nFees;
9983 }
9984
9985 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
9986 static const int64 nTargetSpacing = 10 * 60;
9987 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
9988
9989 //
9990 // minimum amount of work that could possibly be required nTime after
9991 // minimum work required was nBase
9992 //
9993 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
9994 {
9995 // Testnet has min-difficulty blocks
9996 // after nTargetSpacing*2 time between blocks:
9997 if (fTestNet && nTime > nTargetSpacing*2)
9998 return bnProofOfWorkLimit.GetCompact();
9999
10000 CBigNum bnResult;
10001 bnResult.SetCompact(nBase);
10002 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
10003 {
10004 // Maximum 400% adjustment...
10005 bnResult *= 4;
10006 // ... in best-case exactly 4-times-normal target time
10007 nTime -= nTargetTimespan*4;
10008 }
10009 if (bnResult > bnProofOfWorkLimit)
10010 bnResult = bnProofOfWorkLimit;
10011 return bnResult.GetCompact();
10012 }
10013
10014 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
10015 {
10016 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
10017
10018 // Genesis block
10019 if (pindexLast == NULL)
10020 return nProofOfWorkLimit;
10021
10022 // Only change once per interval
10023 if ((pindexLast->nHeight+1) % nInterval != 0)
10024 {
10025 // Special rules for testnet after 15 Feb 2012:
10026 if (fTestNet && pblock->nTime > 1329264000)
10027 {
10028 // If the new block's timestamp is more than 2* 10 minutes
10029 // then allow mining of a min-difficulty block.
10030 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
10031 return nProofOfWorkLimit;
10032 else
10033 {
10034 // Return the last non-special-min-difficulty-rules-block
10035 const CBlockIndex* pindex = pindexLast;
10036 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
10037 pindex = pindex->pprev;
10038 return pindex->nBits;
10039 }
10040 }
10041
10042 return pindexLast->nBits;
10043 }
10044
10045 // Go back by what we want to be 14 days worth of blocks
10046 const CBlockIndex* pindexFirst = pindexLast;
10047 for (int i = 0; pindexFirst && i < nInterval-1; i++)
10048 pindexFirst = pindexFirst->pprev;
10049 assert(pindexFirst);
10050
10051 // Limit adjustment step
10052 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
10053 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
10054 if (nActualTimespan < nTargetTimespan/4)
10055 nActualTimespan = nTargetTimespan/4;
10056 if (nActualTimespan > nTargetTimespan*4)
10057 nActualTimespan = nTargetTimespan*4;
10058
10059 // Retarget
10060 CBigNum bnNew;
10061 bnNew.SetCompact(pindexLast->nBits);
10062 bnNew *= nActualTimespan;
10063 bnNew /= nTargetTimespan;
10064
10065 if (bnNew > bnProofOfWorkLimit)
10066 bnNew = bnProofOfWorkLimit;
10067
10068 /// debug print
10069 printf("GetNextWorkRequired RETARGET\n");
10070 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
10071 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
10072 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
10073
10074 return bnNew.GetCompact();
10075 }
10076
10077 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
10078 {
10079 CBigNum bnTarget;
10080 bnTarget.SetCompact(nBits);
10081
10082 // Check range
10083 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
10084 return error("CheckProofOfWork() : nBits below minimum work");
10085
10086 // Check proof of work matches claimed amount
10087 if (hash > bnTarget.getuint256())
10088 return error("CheckProofOfWork() : hash doesn't match nBits");
10089
10090 return true;
10091 }
10092
10093 // Return maximum amount of blocks that other nodes claim to have
10094 int GetNumBlocksOfPeers()
10095 {
10096 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
10097 }
10098
10099 bool IsInitialBlockDownload()
10100 {
10101 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
10102 return true;
10103 static int64 nLastUpdate;
10104 static CBlockIndex* pindexLastBest;
10105 if (pindexBest != pindexLastBest)
10106 {
10107 pindexLastBest = pindexBest;
10108 nLastUpdate = GetTime();
10109 }
10110 return (GetTime() - nLastUpdate < 10 &&
10111 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
10112 }
10113
10114 void static InvalidChainFound(CBlockIndex* pindexNew)
10115 {
10116 if (pindexNew->bnChainWork > bnBestInvalidWork)
10117 {
10118 bnBestInvalidWork = pindexNew->bnChainWork;
10119 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
10120 MainFrameRepaint();
10121 }
10122 printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
10123 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
10124 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
10125 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
10126 }
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138 bool CTransaction::DisconnectInputs(CTxDB& txdb)
10139 {
10140 // Relinquish previous transactions' spent pointers
10141 if (!IsCoinBase())
10142 {
10143 BOOST_FOREACH(const CTxIn& txin, vin)
10144 {
10145 COutPoint prevout = txin.prevout;
10146
10147 // Get prev txindex from disk
10148 CTxIndex txindex;
10149 if (!txdb.ReadTxIndex(prevout.hash, txindex))
10150 return error("DisconnectInputs() : ReadTxIndex failed");
10151
10152 if (prevout.n >= txindex.vSpent.size())
10153 return error("DisconnectInputs() : prevout.n out of range");
10154
10155 // Mark outpoint as not spent
10156 txindex.vSpent[prevout.n].SetNull();
10157
10158 // Write back
10159 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
10160 return error("DisconnectInputs() : UpdateTxIndex failed");
10161 }
10162 }
10163
10164 // Remove transaction from index
10165 // This can fail if a duplicate of this transaction was in a chain that got
10166 // reorganized away. This is only possible if this transaction was completely
10167 // spent, so erasing it would be a no-op anway.
10168 txdb.EraseTxIndex(*this);
10169
10170 return true;
10171 }
10172
10173
10174 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
10175 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
10176 bool& fInvalid)
10177 {
10178 // FetchInputs can return false either because we just haven't seen some inputs
10179 // (in which case the transaction should be stored as an orphan)
10180 // or because the transaction is malformed (in which case the transaction should
10181 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
10182 fInvalid = false;
10183
10184 // Take over previous transactions' spent pointers
10185 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
10186 // fMiner is true when called from the internal bitcoin miner
10187 // ... both are false when called from CTransaction::AcceptToMemoryPool
10188 if (!IsCoinBase())
10189 {
10190 int64 nValueIn = 0;
10191 for (int i = 0; i < vin.size(); i++)
10192 {
10193 COutPoint prevout = vin[i].prevout;
10194
10195 // Read txindex
10196 CTxIndex txindex;
10197 bool fFound = true;
10198 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
10199 {
10200 // Get txindex from current proposed changes
10201 txindex = mapTestPool[prevout.hash];
10202 }
10203 else
10204 {
10205 // Read txindex from txdb
10206 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
10207 }
10208 if (!fFound && (fBlock || fMiner))
10209 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
10210
10211 // Read txPrev
10212 CTransaction txPrev;
10213 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
10214 {
10215 // Get prev tx from single transactions in memory
10216 CRITICAL_BLOCK(cs_mapTransactions)
10217 {
10218 if (!mapTransactions.count(prevout.hash))
10219 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
10220 txPrev = mapTransactions[prevout.hash];
10221 }
10222 if (!fFound)
10223 txindex.vSpent.resize(txPrev.vout.size());
10224 }
10225 else
10226 {
10227 // Get prev tx from disk
10228 if (!txPrev.ReadFromDisk(txindex.pos))
10229 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
10230 }
10231
10232 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
10233 {
10234 // Revisit this if/when transaction replacement is implemented and allows
10235 // adding inputs:
10236 fInvalid = true;
10237 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
10238 }
10239
10240 // If prev is coinbase, check that it's matured
10241 if (txPrev.IsCoinBase())
10242 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
10243 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
10244 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
10245
10246 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
10247 // before the last blockchain checkpoint. This is safe because block merkle hashes are
10248 // still computed and checked, and any change will be caught at the next checkpoint.
10249 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
10250 // Verify signature
10251 if (!VerifySignature(txPrev, *this, i))
10252 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
10253
10254 // Check for conflicts (double-spend)
10255 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
10256 // for an attacker to attempt to split the network.
10257 if (!txindex.vSpent[prevout.n].IsNull())
10258 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
10259
10260 // Check for negative or overflow input values
10261 nValueIn += txPrev.vout[prevout.n].nValue;
10262 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
10263 return DoS(100, error("ConnectInputs() : txin values out of range"));
10264
10265 // Mark outpoints as spent
10266 txindex.vSpent[prevout.n] = posThisTx;
10267
10268 // Write back
10269 if (fBlock || fMiner)
10270 {
10271 mapTestPool[prevout.hash] = txindex;
10272 }
10273 }
10274
10275 if (nValueIn < GetValueOut())
10276 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
10277
10278 // Tally transaction fees
10279 int64 nTxFee = nValueIn - GetValueOut();
10280 if (nTxFee < 0)
10281 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
10282 if (nTxFee < nMinFee)
10283 return false;
10284 nFees += nTxFee;
10285 if (!MoneyRange(nFees))
10286 return DoS(100, error("ConnectInputs() : nFees out of range"));
10287 }
10288
10289 if (fBlock)
10290 {
10291 // Add transaction to changes
10292 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
10293 }
10294 else if (fMiner)
10295 {
10296 // Add transaction to test pool
10297 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
10298 }
10299
10300 return true;
10301 }
10302
10303
10304 bool CTransaction::ClientConnectInputs()
10305 {
10306 if (IsCoinBase())
10307 return false;
10308
10309 // Take over previous transactions' spent pointers
10310 CRITICAL_BLOCK(cs_mapTransactions)
10311 {
10312 int64 nValueIn = 0;
10313 for (int i = 0; i < vin.size(); i++)
10314 {
10315 // Get prev tx from single transactions in memory
10316 COutPoint prevout = vin[i].prevout;
10317 if (!mapTransactions.count(prevout.hash))
10318 return false;
10319 CTransaction& txPrev = mapTransactions[prevout.hash];
10320
10321 if (prevout.n >= txPrev.vout.size())
10322 return false;
10323
10324 // Verify signature
10325 if (!VerifySignature(txPrev, *this, i))
10326 return error("ConnectInputs() : VerifySignature failed");
10327
10328 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
10329 ///// this has to go away now that posNext is gone
10330 // // Check for conflicts
10331 // if (!txPrev.vout[prevout.n].posNext.IsNull())
10332 // return error("ConnectInputs() : prev tx already used");
10333 //
10334 // // Flag outpoints as used
10335 // txPrev.vout[prevout.n].posNext = posThisTx;
10336
10337 nValueIn += txPrev.vout[prevout.n].nValue;
10338
10339 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
10340 return error("ClientConnectInputs() : txin values out of range");
10341 }
10342 if (GetValueOut() > nValueIn)
10343 return false;
10344 }
10345
10346 return true;
10347 }
10348
10349
10350
10351
10352 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
10353 {
10354 // Disconnect in reverse order
10355 for (int i = vtx.size()-1; i >= 0; i--)
10356 if (!vtx[i].DisconnectInputs(txdb))
10357 return false;
10358
10359 // Update block index on disk without changing it in memory.
10360 // The memory index structure will be changed after the db commits.
10361 if (pindex->pprev)
10362 {
10363 CDiskBlockIndex blockindexPrev(pindex->pprev);
10364 blockindexPrev.hashNext = 0;
10365 if (!txdb.WriteBlockIndex(blockindexPrev))
10366 return error("DisconnectBlock() : WriteBlockIndex failed");
10367 }
10368
10369 return true;
10370 }
10371
10372 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
10373 {
10374 // Check it again in case a previous version let a bad block in
10375 if (!CheckBlock())
10376 return false;
10377
10378 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
10379 // unless those are already completely spent.
10380 // If such overwrites are allowed, coinbases and transactions depending upon those
10381 // can be duplicated to remove the ability to spend the first instance -- even after
10382 // being sent to another address.
10383 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
10384 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
10385 // already refuses previously-known transaction id's entirely.
10386 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
10387 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
10388 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
10389 BOOST_FOREACH(CTransaction& tx, vtx)
10390 {
10391 CTxIndex txindexOld;
10392 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
10393 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
10394 if (pos.IsNull())
10395 return false;
10396 }
10397
10398 //// issue here: it doesn't know the version
10399 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
10400
10401 map<uint256, CTxIndex> mapQueuedChanges;
10402 int64 nFees = 0;
10403 BOOST_FOREACH(CTransaction& tx, vtx)
10404 {
10405 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
10406 nTxPos += ::GetSerializeSize(tx, SER_DISK);
10407
10408 bool fInvalid;
10409 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, 0, fInvalid))
10410 return false;
10411 }
10412 // Write queued txindex changes
10413 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
10414 {
10415 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
10416 return error("ConnectBlock() : UpdateTxIndex failed");
10417 }
10418
10419 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
10420 return false;
10421
10422 // Update block index on disk without changing it in memory.
10423 // The memory index structure will be changed after the db commits.
10424 if (pindex->pprev)
10425 {
10426 CDiskBlockIndex blockindexPrev(pindex->pprev);
10427 blockindexPrev.hashNext = pindex->GetBlockHash();
10428 if (!txdb.WriteBlockIndex(blockindexPrev))
10429 return error("ConnectBlock() : WriteBlockIndex failed");
10430 }
10431
10432 // Watch for transactions paying to me
10433 BOOST_FOREACH(CTransaction& tx, vtx)
10434 SyncWithWallets(tx, this, true);
10435
10436 return true;
10437 }
10438
10439 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
10440 {
10441 printf("REORGANIZE\n");
10442
10443 // Find the fork
10444 CBlockIndex* pfork = pindexBest;
10445 CBlockIndex* plonger = pindexNew;
10446 while (pfork != plonger)
10447 {
10448 while (plonger->nHeight > pfork->nHeight)
10449 if (!(plonger = plonger->pprev))
10450 return error("Reorganize() : plonger->pprev is null");
10451 if (pfork == plonger)
10452 break;
10453 if (!(pfork = pfork->pprev))
10454 return error("Reorganize() : pfork->pprev is null");
10455 }
10456
10457 // List of what to disconnect
10458 vector<CBlockIndex*> vDisconnect;
10459 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
10460 vDisconnect.push_back(pindex);
10461
10462 // List of what to connect
10463 vector<CBlockIndex*> vConnect;
10464 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
10465 vConnect.push_back(pindex);
10466 reverse(vConnect.begin(), vConnect.end());
10467
10468 // Disconnect shorter branch
10469 vector<CTransaction> vResurrect;
10470 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
10471 {
10472 CBlock block;
10473 if (!block.ReadFromDisk(pindex))
10474 return error("Reorganize() : ReadFromDisk for disconnect failed");
10475 if (!block.DisconnectBlock(txdb, pindex))
10476 return error("Reorganize() : DisconnectBlock failed");
10477
10478 // Queue memory transactions to resurrect
10479 BOOST_FOREACH(const CTransaction& tx, block.vtx)
10480 if (!tx.IsCoinBase())
10481 vResurrect.push_back(tx);
10482 }
10483
10484 // Connect longer branch
10485 vector<CTransaction> vDelete;
10486 for (int i = 0; i < vConnect.size(); i++)
10487 {
10488 CBlockIndex* pindex = vConnect[i];
10489 CBlock block;
10490 if (!block.ReadFromDisk(pindex))
10491 return error("Reorganize() : ReadFromDisk for connect failed");
10492 if (!block.ConnectBlock(txdb, pindex))
10493 {
10494 // Invalid block
10495 txdb.TxnAbort();
10496 return error("Reorganize() : ConnectBlock failed");
10497 }
10498
10499 // Queue memory transactions to delete
10500 BOOST_FOREACH(const CTransaction& tx, block.vtx)
10501 vDelete.push_back(tx);
10502 }
10503 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
10504 return error("Reorganize() : WriteHashBestChain failed");
10505
10506 // Make sure it's successfully written to disk before changing memory structure
10507 if (!txdb.TxnCommit())
10508 return error("Reorganize() : TxnCommit failed");
10509
10510 // Disconnect shorter branch
10511 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
10512 if (pindex->pprev)
10513 pindex->pprev->pnext = NULL;
10514
10515 // Connect longer branch
10516 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
10517 if (pindex->pprev)
10518 pindex->pprev->pnext = pindex;
10519
10520 // Resurrect memory transactions that were in the disconnected branch
10521 BOOST_FOREACH(CTransaction& tx, vResurrect)
10522 tx.AcceptToMemoryPool(txdb, false);
10523
10524 // Delete redundant memory transactions that are in the connected branch
10525 BOOST_FOREACH(CTransaction& tx, vDelete)
10526 tx.RemoveFromMemoryPool();
10527
10528 return true;
10529 }
10530
10531
10532 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
10533 {
10534 uint256 hash = GetHash();
10535
10536 txdb.TxnBegin();
10537 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
10538 {
10539 txdb.WriteHashBestChain(hash);
10540 if (!txdb.TxnCommit())
10541 return error("SetBestChain() : TxnCommit failed");
10542 pindexGenesisBlock = pindexNew;
10543 }
10544 else if (hashPrevBlock == hashBestChain)
10545 {
10546 // Adding to current best branch
10547 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
10548 {
10549 txdb.TxnAbort();
10550 InvalidChainFound(pindexNew);
10551 return error("SetBestChain() : ConnectBlock failed");
10552 }
10553 if (!txdb.TxnCommit())
10554 return error("SetBestChain() : TxnCommit failed");
10555
10556 // Add to current best branch
10557 pindexNew->pprev->pnext = pindexNew;
10558
10559 // Delete redundant memory transactions
10560 BOOST_FOREACH(CTransaction& tx, vtx)
10561 tx.RemoveFromMemoryPool();
10562 }
10563 else
10564 {
10565 // New best branch
10566 if (!Reorganize(txdb, pindexNew))
10567 {
10568 txdb.TxnAbort();
10569 InvalidChainFound(pindexNew);
10570 return error("SetBestChain() : Reorganize failed");
10571 }
10572 }
10573
10574 // Update best block in wallet (so we can detect restored wallets)
10575 if (!IsInitialBlockDownload())
10576 {
10577 const CBlockLocator locator(pindexNew);
10578 ::SetBestChain(locator);
10579 }
10580
10581 // New best block
10582 hashBestChain = hash;
10583 pindexBest = pindexNew;
10584 nBestHeight = pindexBest->nHeight;
10585 bnBestChainWork = pindexNew->bnChainWork;
10586 nTimeBestReceived = GetTime();
10587 nTransactionsUpdated++;
10588 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
10589
10590 return true;
10591 }
10592
10593
10594 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
10595 {
10596 // Check for duplicate
10597 uint256 hash = GetHash();
10598 if (mapBlockIndex.count(hash))
10599 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
10600
10601 // Construct new block index object
10602 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
10603 if (!pindexNew)
10604 return error("AddToBlockIndex() : new CBlockIndex failed");
10605 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
10606 pindexNew->phashBlock = &((*mi).first);
10607 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
10608 if (miPrev != mapBlockIndex.end())
10609 {
10610 pindexNew->pprev = (*miPrev).second;
10611 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
10612 }
10613 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
10614
10615 CTxDB txdb;
10616 txdb.TxnBegin();
10617 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
10618 if (!txdb.TxnCommit())
10619 return false;
10620
10621 // New best
10622 if (pindexNew->bnChainWork > bnBestChainWork)
10623 if (!SetBestChain(txdb, pindexNew))
10624 return false;
10625
10626 txdb.Close();
10627
10628 if (pindexNew == pindexBest)
10629 {
10630 // Notify UI to display prev block's coinbase if it was ours
10631 static uint256 hashPrevBestCoinBase;
10632 UpdatedTransaction(hashPrevBestCoinBase);
10633 hashPrevBestCoinBase = vtx[0].GetHash();
10634 }
10635
10636 MainFrameRepaint();
10637 return true;
10638 }
10639
10640
10641
10642
10643 bool CBlock::CheckBlock() const
10644 {
10645 // These are checks that are independent of context
10646 // that can be verified before saving an orphan block.
10647
10648 // Size limits
10649 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
10650 return DoS(100, error("CheckBlock() : size limits failed"));
10651
10652 // Check proof of work matches claimed amount
10653 if (!CheckProofOfWork(GetHash(), nBits))
10654 return DoS(50, error("CheckBlock() : proof of work failed"));
10655
10656 // Check timestamp
10657 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
10658 return error("CheckBlock() : block timestamp too far in the future");
10659
10660 // First transaction must be coinbase, the rest must not be
10661 if (vtx.empty() || !vtx[0].IsCoinBase())
10662 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
10663 for (int i = 1; i < vtx.size(); i++)
10664 if (vtx[i].IsCoinBase())
10665 return DoS(100, error("CheckBlock() : more than one coinbase"));
10666
10667 // Check transactions
10668 BOOST_FOREACH(const CTransaction& tx, vtx)
10669 if (!tx.CheckTransaction())
10670 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
10671
10672 // Check that it's not full of nonstandard transactions
10673 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
10674 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
10675
10676 // Check merkleroot
10677 if (hashMerkleRoot != BuildMerkleTree())
10678 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
10679
10680 return true;
10681 }
10682
10683 bool CBlock::AcceptBlock()
10684 {
10685 // Check for duplicate
10686 uint256 hash = GetHash();
10687 if (mapBlockIndex.count(hash))
10688 return error("AcceptBlock() : block already in mapBlockIndex");
10689
10690 // Get prev block index
10691 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
10692 if (mi == mapBlockIndex.end())
10693 return DoS(10, error("AcceptBlock() : prev block not found"));
10694 CBlockIndex* pindexPrev = (*mi).second;
10695 int nHeight = pindexPrev->nHeight+1;
10696
10697 // Check proof of work
10698 if (nBits != GetNextWorkRequired(pindexPrev, this))
10699 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
10700
10701 // Check timestamp against prev
10702 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
10703 return error("AcceptBlock() : block's timestamp is too early");
10704
10705 // Check that all transactions are finalized
10706 BOOST_FOREACH(const CTransaction& tx, vtx)
10707 if (!tx.IsFinal(nHeight, GetBlockTime()))
10708 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
10709
10710 // Check that the block chain matches the known block chain up to a checkpoint
10711 if (!Checkpoints::CheckBlock(nHeight, hash))
10712 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
10713
10714 // Write block to history file
10715 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
10716 return error("AcceptBlock() : out of disk space");
10717 unsigned int nFile = -1;
10718 unsigned int nBlockPos = 0;
10719 if (!WriteToDisk(nFile, nBlockPos))
10720 return error("AcceptBlock() : WriteToDisk failed");
10721 if (!AddToBlockIndex(nFile, nBlockPos))
10722 return error("AcceptBlock() : AddToBlockIndex failed");
10723
10724 // Relay inventory, but don't relay old inventory during initial block download
10725 if (hashBestChain == hash)
10726 CRITICAL_BLOCK(cs_vNodes)
10727 BOOST_FOREACH(CNode* pnode, vNodes)
10728 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
10729 pnode->PushInventory(CInv(MSG_BLOCK, hash));
10730
10731 return true;
10732 }
10733
10734 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
10735 {
10736 // Check for duplicate
10737 uint256 hash = pblock->GetHash();
10738 if (mapBlockIndex.count(hash))
10739 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
10740 if (mapOrphanBlocks.count(hash))
10741 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
10742
10743 // Preliminary checks
10744 if (!pblock->CheckBlock())
10745 return error("ProcessBlock() : CheckBlock FAILED");
10746
10747 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
10748 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
10749 {
10750 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
10751 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
10752 if (deltaTime < 0)
10753 {
10754 if (pfrom)
10755 pfrom->Misbehaving(100);
10756 return error("ProcessBlock() : block with timestamp before last checkpoint");
10757 }
10758 CBigNum bnNewBlock;
10759 bnNewBlock.SetCompact(pblock->nBits);
10760 CBigNum bnRequired;
10761 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
10762 if (bnNewBlock > bnRequired)
10763 {
10764 if (pfrom)
10765 pfrom->Misbehaving(100);
10766 return error("ProcessBlock() : block with too little proof-of-work");
10767 }
10768 }
10769
10770
10771 // If don't already have its previous block, shunt it off to holding area until we get it
10772 if (!mapBlockIndex.count(pblock->hashPrevBlock))
10773 {
10774 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
10775 CBlock* pblock2 = new CBlock(*pblock);
10776 mapOrphanBlocks.insert(make_pair(hash, pblock2));
10777 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
10778
10779 // Ask this guy to fill in what we're missing
10780 if (pfrom)
10781 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
10782 return true;
10783 }
10784
10785 // Store to disk
10786 if (!pblock->AcceptBlock())
10787 return error("ProcessBlock() : AcceptBlock FAILED");
10788
10789 // Recursively process any orphan blocks that depended on this one
10790 vector<uint256> vWorkQueue;
10791 vWorkQueue.push_back(hash);
10792 for (int i = 0; i < vWorkQueue.size(); i++)
10793 {
10794 uint256 hashPrev = vWorkQueue[i];
10795 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
10796 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
10797 ++mi)
10798 {
10799 CBlock* pblockOrphan = (*mi).second;
10800 if (pblockOrphan->AcceptBlock())
10801 vWorkQueue.push_back(pblockOrphan->GetHash());
10802 mapOrphanBlocks.erase(pblockOrphan->GetHash());
10803 delete pblockOrphan;
10804 }
10805 mapOrphanBlocksByPrev.erase(hashPrev);
10806 }
10807
10808 printf("ProcessBlock: ACCEPTED\n");
10809 return true;
10810 }
10811
10812
10813
10814
10815
10816
10817
10818
10819 bool CheckDiskSpace(uint64 nAdditionalBytes)
10820 {
10821 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
10822
10823 // Check for 15MB because database could create another 10MB log file at any time
10824 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
10825 {
10826 fShutdown = true;
10827 string strMessage = _("Warning: Disk space is low ");
10828 strMiscWarning = strMessage;
10829 printf("*** %s\n", strMessage.c_str());
10830 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
10831 CreateThread(Shutdown, NULL);
10832 return false;
10833 }
10834 return true;
10835 }
10836
10837 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
10838 {
10839 if (nFile == -1)
10840 return NULL;
10841 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
10842 if (!file)
10843 return NULL;
10844 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
10845 {
10846 if (fseek(file, nBlockPos, SEEK_SET) != 0)
10847 {
10848 fclose(file);
10849 return NULL;
10850 }
10851 }
10852 return file;
10853 }
10854
10855 static unsigned int nCurrentBlockFile = 1;
10856
10857 FILE* AppendBlockFile(unsigned int& nFileRet)
10858 {
10859 nFileRet = 0;
10860 loop
10861 {
10862 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
10863 if (!file)
10864 return NULL;
10865 if (fseek(file, 0, SEEK_END) != 0)
10866 return NULL;
10867 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
10868 if (ftell(file) < 0x7F000000 - MAX_SIZE)
10869 {
10870 nFileRet = nCurrentBlockFile;
10871 return file;
10872 }
10873 fclose(file);
10874 nCurrentBlockFile++;
10875 }
10876 }
10877
10878 bool LoadBlockIndex(bool fAllowNew)
10879 {
10880 if (fTestNet)
10881 {
10882 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
10883 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
10884 pchMessageStart[0] = 0xfa;
10885 pchMessageStart[1] = 0xbf;
10886 pchMessageStart[2] = 0xb5;
10887 pchMessageStart[3] = 0xda;
10888 }
10889
10890 //
10891 // Load block index
10892 //
10893 CTxDB txdb("cr");
10894 if (!txdb.LoadBlockIndex())
10895 return false;
10896 txdb.Close();
10897
10898 //
10899 // Init with genesis block
10900 //
10901 if (mapBlockIndex.empty())
10902 {
10903 if (!fAllowNew)
10904 return false;
10905
10906 // Genesis Block:
10907 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
10908 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
10909 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
10910 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
10911 // vMerkleTree: 4a5e1e
10912
10913 // Genesis block
10914 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
10915 CTransaction txNew;
10916 txNew.vin.resize(1);
10917 txNew.vout.resize(1);
10918 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
10919 txNew.vout[0].nValue = 50 * COIN;
10920 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
10921 CBlock block;
10922 block.vtx.push_back(txNew);
10923 block.hashPrevBlock = 0;
10924 block.hashMerkleRoot = block.BuildMerkleTree();
10925 block.nVersion = 1;
10926 block.nTime = 1231006505;
10927 block.nBits = 0x1d00ffff;
10928 block.nNonce = 2083236893;
10929
10930 if (fTestNet)
10931 {
10932 block.nTime = 1296688602;
10933 block.nBits = 0x1d07fff8;
10934 block.nNonce = 384568319;
10935 }
10936
10937 //// debug print
10938 printf("%s\n", block.GetHash().ToString().c_str());
10939 printf("%s\n", hashGenesisBlock.ToString().c_str());
10940 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
10941 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
10942 block.print();
10943 assert(block.GetHash() == hashGenesisBlock);
10944
10945 // Start new block file
10946 unsigned int nFile;
10947 unsigned int nBlockPos;
10948 if (!block.WriteToDisk(nFile, nBlockPos))
10949 return error("LoadBlockIndex() : writing genesis block to disk failed");
10950 if (!block.AddToBlockIndex(nFile, nBlockPos))
10951 return error("LoadBlockIndex() : genesis block not accepted");
10952 }
10953
10954 return true;
10955 }
10956
10957
10958
10959 void PrintBlockTree()
10960 {
10961 // precompute tree structure
10962 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
10963 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
10964 {
10965 CBlockIndex* pindex = (*mi).second;
10966 mapNext[pindex->pprev].push_back(pindex);
10967 // test
10968 //while (rand() % 3 == 0)
10969 // mapNext[pindex->pprev].push_back(pindex);
10970 }
10971
10972 vector<pair<int, CBlockIndex*> > vStack;
10973 vStack.push_back(make_pair(0, pindexGenesisBlock));
10974
10975 int nPrevCol = 0;
10976 while (!vStack.empty())
10977 {
10978 int nCol = vStack.back().first;
10979 CBlockIndex* pindex = vStack.back().second;
10980 vStack.pop_back();
10981
10982 // print split or gap
10983 if (nCol > nPrevCol)
10984 {
10985 for (int i = 0; i < nCol-1; i++)
10986 printf("| ");
10987 printf("|\\\n");
10988 }
10989 else if (nCol < nPrevCol)
10990 {
10991 for (int i = 0; i < nCol; i++)
10992 printf("| ");
10993 printf("|\n");
10994 }
10995 nPrevCol = nCol;
10996
10997 // print columns
10998 for (int i = 0; i < nCol; i++)
10999 printf("| ");
11000
11001 // print item
11002 CBlock block;
11003 block.ReadFromDisk(pindex);
11004 printf("%d (%u,%u) %s %s tx %d",
11005 pindex->nHeight,
11006 pindex->nFile,
11007 pindex->nBlockPos,
11008 block.GetHash().ToString().substr(0,20).c_str(),
11009 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
11010 block.vtx.size());
11011
11012 PrintWallets(block);
11013
11014 // put the main timechain first
11015 vector<CBlockIndex*>& vNext = mapNext[pindex];
11016 for (int i = 0; i < vNext.size(); i++)
11017 {
11018 if (vNext[i]->pnext)
11019 {
11020 swap(vNext[0], vNext[i]);
11021 break;
11022 }
11023 }
11024
11025 // iterate children
11026 for (int i = 0; i < vNext.size(); i++)
11027 vStack.push_back(make_pair(nCol+i, vNext[i]));
11028 }
11029 }
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040 //////////////////////////////////////////////////////////////////////////////
11041 //
11042 // CAlert
11043 //
11044
11045 map<uint256, CAlert> mapAlerts;
11046 CCriticalSection cs_mapAlerts;
11047
11048 string GetWarnings(string strFor)
11049 {
11050 int nPriority = 0;
11051 string strStatusBar;
11052 string strRPC;
11053 if (GetBoolArg("-testsafemode"))
11054 strRPC = "test";
11055
11056 // Misc warnings like out of disk space and clock is wrong
11057 if (strMiscWarning != "")
11058 {
11059 nPriority = 1000;
11060 strStatusBar = strMiscWarning;
11061 }
11062
11063 // Longer invalid proof-of-work chain
11064 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
11065 {
11066 nPriority = 2000;
11067 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
11068 }
11069
11070 // Alerts
11071 CRITICAL_BLOCK(cs_mapAlerts)
11072 {
11073 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
11074 {
11075 const CAlert& alert = item.second;
11076 if (alert.AppliesToMe() && alert.nPriority > nPriority)
11077 {
11078 nPriority = alert.nPriority;
11079 strStatusBar = alert.strStatusBar;
11080 }
11081 }
11082 }
11083
11084 if (strFor == "statusbar")
11085 return strStatusBar;
11086 else if (strFor == "rpc")
11087 return strRPC;
11088 assert(!"GetWarnings() : invalid parameter");
11089 return "error";
11090 }
11091
11092 bool CAlert::ProcessAlert()
11093 {
11094 if (!CheckSignature())
11095 return false;
11096 if (!IsInEffect())
11097 return false;
11098
11099 CRITICAL_BLOCK(cs_mapAlerts)
11100 {
11101 // Cancel previous alerts
11102 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
11103 {
11104 const CAlert& alert = (*mi).second;
11105 if (Cancels(alert))
11106 {
11107 printf("cancelling alert %d\n", alert.nID);
11108 mapAlerts.erase(mi++);
11109 }
11110 else if (!alert.IsInEffect())
11111 {
11112 printf("expiring alert %d\n", alert.nID);
11113 mapAlerts.erase(mi++);
11114 }
11115 else
11116 mi++;
11117 }
11118
11119 // Check if this alert has been cancelled
11120 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
11121 {
11122 const CAlert& alert = item.second;
11123 if (alert.Cancels(*this))
11124 {
11125 printf("alert already cancelled by %d\n", alert.nID);
11126 return false;
11127 }
11128 }
11129
11130 // Add to mapAlerts
11131 mapAlerts.insert(make_pair(GetHash(), *this));
11132 }
11133
11134 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
11135 MainFrameRepaint();
11136 return true;
11137 }
11138
11139
11140
11141
11142
11143
11144
11145
11146 //////////////////////////////////////////////////////////////////////////////
11147 //
11148 // Messages
11149 //
11150
11151
11152 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
11153 {
11154 switch (inv.type)
11155 {
11156 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
11157 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
11158 }
11159 // Don't know what it is, just say we already got one
11160 return true;
11161 }
11162
11163
11164
11165
11166 // The message start string is designed to be unlikely to occur in normal data.
11167 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
11168 // a large 4-byte int at any alignment.
11169 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
11170
11171
11172 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
11173 {
11174 static map<unsigned int, vector<unsigned char> > mapReuseKey;
11175 RandAddSeedPerfmon();
11176 if (fDebug) {
11177 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
11178 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
11179 }
11180 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
11181 {
11182 printf("dropmessagestest DROPPING RECV MESSAGE\n");
11183 return true;
11184 }
11185
11186
11187
11188
11189
11190 if (strCommand == "version")
11191 {
11192 // Each connection can only send one version message
11193 if (pfrom->nVersion != 0)
11194 {
11195 pfrom->Misbehaving(1);
11196 return false;
11197 }
11198
11199 int64 nTime;
11200 CAddress addrMe;
11201 CAddress addrFrom;
11202 uint64 nNonce = 1;
11203 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
11204 if (pfrom->nVersion == 10300)
11205 pfrom->nVersion = 300;
11206 if (pfrom->nVersion >= 106 && !vRecv.empty())
11207 vRecv >> addrFrom >> nNonce;
11208 if (pfrom->nVersion >= 106 && !vRecv.empty())
11209 vRecv >> pfrom->strSubVer;
11210 if (pfrom->nVersion >= 209 && !vRecv.empty())
11211 vRecv >> pfrom->nStartingHeight;
11212
11213 if (pfrom->nVersion == 0)
11214 return false;
11215
11216 // Disconnect if we connected to ourself
11217 if (nNonce == nLocalHostNonce && nNonce > 1)
11218 {
11219 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
11220 pfrom->fDisconnect = true;
11221 return true;
11222 }
11223
11224 // Be shy and don't send version until we hear
11225 if (pfrom->fInbound)
11226 pfrom->PushVersion();
11227
11228 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
11229
11230 AddTimeData(pfrom->addr.ip, nTime);
11231
11232 // Change version
11233 if (pfrom->nVersion >= 209)
11234 pfrom->PushMessage("verack");
11235 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
11236 if (pfrom->nVersion < 209)
11237 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
11238
11239 if (!pfrom->fInbound)
11240 {
11241 // Advertise our address
11242 if (addrLocalHost.IsRoutable() && !fUseProxy)
11243 {
11244 CAddress addr(addrLocalHost);
11245 addr.nTime = GetAdjustedTime();
11246 pfrom->PushAddress(addr);
11247 }
11248
11249 // Get recent addresses
11250 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
11251 {
11252 pfrom->PushMessage("getaddr");
11253 pfrom->fGetAddr = true;
11254 }
11255 }
11256
11257 // Ask the first connected node for block updates
11258 static int nAskedForBlocks;
11259 if (!pfrom->fClient &&
11260 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
11261 (nAskedForBlocks < 1 || vNodes.size() <= 1))
11262 {
11263 nAskedForBlocks++;
11264 pfrom->PushGetBlocks(pindexBest, uint256(0));
11265 }
11266
11267 // Relay alerts
11268 CRITICAL_BLOCK(cs_mapAlerts)
11269 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
11270 item.second.RelayTo(pfrom);
11271
11272 pfrom->fSuccessfullyConnected = true;
11273
11274 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
11275
11276 cPeerBlockCounts.input(pfrom->nStartingHeight);
11277 }
11278
11279
11280 else if (pfrom->nVersion == 0)
11281 {
11282 // Must have a version message before anything else
11283 pfrom->Misbehaving(1);
11284 return false;
11285 }
11286
11287
11288 else if (strCommand == "verack")
11289 {
11290 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
11291 }
11292
11293
11294 else if (strCommand == "addr")
11295 {
11296 vector<CAddress> vAddr;
11297 vRecv >> vAddr;
11298
11299 // Don't want addr from older versions unless seeding
11300 if (pfrom->nVersion < 209)
11301 return true;
11302 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
11303 return true;
11304 if (vAddr.size() > 1000)
11305 {
11306 pfrom->Misbehaving(20);
11307 return error("message addr size() = %d", vAddr.size());
11308 }
11309
11310 // Store the new addresses
11311 CAddrDB addrDB;
11312 addrDB.TxnBegin();
11313 int64 nNow = GetAdjustedTime();
11314 int64 nSince = nNow - 10 * 60;
11315 BOOST_FOREACH(CAddress& addr, vAddr)
11316 {
11317 if (fShutdown)
11318 return true;
11319 // ignore IPv6 for now, since it isn't implemented anyway
11320 if (!addr.IsIPv4())
11321 continue;
11322 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
11323 addr.nTime = nNow - 5 * 24 * 60 * 60;
11324 AddAddress(addr, 2 * 60 * 60, &addrDB);
11325 pfrom->AddAddressKnown(addr);
11326 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
11327 {
11328 // Relay to a limited number of other nodes
11329 CRITICAL_BLOCK(cs_vNodes)
11330 {
11331 // Use deterministic randomness to send to the same nodes for 24 hours
11332 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
11333 static uint256 hashSalt;
11334 if (hashSalt == 0)
11335 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
11336 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
11337 hashRand = Hash(BEGIN(hashRand), END(hashRand));
11338 multimap<uint256, CNode*> mapMix;
11339 BOOST_FOREACH(CNode* pnode, vNodes)
11340 {
11341 if (pnode->nVersion < 31402)
11342 continue;
11343 unsigned int nPointer;
11344 memcpy(&nPointer, &pnode, sizeof(nPointer));
11345 uint256 hashKey = hashRand ^ nPointer;
11346 hashKey = Hash(BEGIN(hashKey), END(hashKey));
11347 mapMix.insert(make_pair(hashKey, pnode));
11348 }
11349 int nRelayNodes = 2;
11350 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
11351 ((*mi).second)->PushAddress(addr);
11352 }
11353 }
11354 }
11355 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
11356 if (vAddr.size() < 1000)
11357 pfrom->fGetAddr = false;
11358 }
11359
11360
11361 else if (strCommand == "inv")
11362 {
11363 vector<CInv> vInv;
11364 vRecv >> vInv;
11365 if (vInv.size() > 50000)
11366 {
11367 pfrom->Misbehaving(20);
11368 return error("message inv size() = %d", vInv.size());
11369 }
11370
11371 CTxDB txdb("r");
11372 BOOST_FOREACH(const CInv& inv, vInv)
11373 {
11374 if (fShutdown)
11375 return true;
11376 pfrom->AddInventoryKnown(inv);
11377
11378 bool fAlreadyHave = AlreadyHave(txdb, inv);
11379 if (fDebug)
11380 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
11381
11382 if (!fAlreadyHave)
11383 pfrom->AskFor(inv);
11384 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
11385 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
11386
11387 // Track requests for our stuff
11388 Inventory(inv.hash);
11389 }
11390 }
11391
11392
11393 else if (strCommand == "getdata")
11394 {
11395 vector<CInv> vInv;
11396 vRecv >> vInv;
11397 if (vInv.size() > 50000)
11398 {
11399 pfrom->Misbehaving(20);
11400 return error("message getdata size() = %d", vInv.size());
11401 }
11402
11403 BOOST_FOREACH(const CInv& inv, vInv)
11404 {
11405 if (fShutdown)
11406 return true;
11407 printf("received getdata for: %s\n", inv.ToString().c_str());
11408
11409 if (inv.type == MSG_BLOCK)
11410 {
11411 // Send block from disk
11412 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
11413 if (mi != mapBlockIndex.end())
11414 {
11415 CBlock block;
11416 block.ReadFromDisk((*mi).second);
11417 pfrom->PushMessage("block", block);
11418
11419 // Trigger them to send a getblocks request for the next batch of inventory
11420 if (inv.hash == pfrom->hashContinue)
11421 {
11422 // Bypass PushInventory, this must send even if redundant,
11423 // and we want it right after the last block so they don't
11424 // wait for other stuff first.
11425 vector<CInv> vInv;
11426 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
11427 pfrom->PushMessage("inv", vInv);
11428 pfrom->hashContinue = 0;
11429 }
11430 }
11431 }
11432 else if (inv.IsKnownType())
11433 {
11434 // Send stream from relay memory
11435 CRITICAL_BLOCK(cs_mapRelay)
11436 {
11437 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
11438 if (mi != mapRelay.end())
11439 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
11440 }
11441 }
11442
11443 // Track requests for our stuff
11444 Inventory(inv.hash);
11445 }
11446 }
11447
11448
11449 else if (strCommand == "getblocks")
11450 {
11451 CBlockLocator locator;
11452 uint256 hashStop;
11453 vRecv >> locator >> hashStop;
11454
11455 // Find the last block the caller has in the main chain
11456 CBlockIndex* pindex = locator.GetBlockIndex();
11457
11458 // Send the rest of the chain
11459 if (pindex)
11460 pindex = pindex->pnext;
11461 int nLimit = 500 + locator.GetDistanceBack();
11462 unsigned int nBytes = 0;
11463 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
11464 for (; pindex; pindex = pindex->pnext)
11465 {
11466 if (pindex->GetBlockHash() == hashStop)
11467 {
11468 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
11469 break;
11470 }
11471 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
11472 CBlock block;
11473 block.ReadFromDisk(pindex, true);
11474 nBytes += block.GetSerializeSize(SER_NETWORK);
11475 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
11476 {
11477 // When this block is requested, we'll send an inv that'll make them
11478 // getblocks the next batch of inventory.
11479 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
11480 pfrom->hashContinue = pindex->GetBlockHash();
11481 break;
11482 }
11483 }
11484 }
11485
11486
11487 else if (strCommand == "getheaders")
11488 {
11489 CBlockLocator locator;
11490 uint256 hashStop;
11491 vRecv >> locator >> hashStop;
11492
11493 CBlockIndex* pindex = NULL;
11494 if (locator.IsNull())
11495 {
11496 // If locator is null, return the hashStop block
11497 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
11498 if (mi == mapBlockIndex.end())
11499 return true;
11500 pindex = (*mi).second;
11501 }
11502 else
11503 {
11504 // Find the last block the caller has in the main chain
11505 pindex = locator.GetBlockIndex();
11506 if (pindex)
11507 pindex = pindex->pnext;
11508 }
11509
11510 vector<CBlock> vHeaders;
11511 int nLimit = 2000 + locator.GetDistanceBack();
11512 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
11513 for (; pindex; pindex = pindex->pnext)
11514 {
11515 vHeaders.push_back(pindex->GetBlockHeader());
11516 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
11517 break;
11518 }
11519 pfrom->PushMessage("headers", vHeaders);
11520 }
11521
11522
11523 else if (strCommand == "tx")
11524 {
11525 vector<uint256> vWorkQueue;
11526 CDataStream vMsg(vRecv);
11527 CTransaction tx;
11528 vRecv >> tx;
11529
11530 CInv inv(MSG_TX, tx.GetHash());
11531 pfrom->AddInventoryKnown(inv);
11532
11533 bool fMissingInputs = false;
11534 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
11535 {
11536 SyncWithWallets(tx, NULL, true);
11537 RelayMessage(inv, vMsg);
11538 mapAlreadyAskedFor.erase(inv);
11539 vWorkQueue.push_back(inv.hash);
11540
11541 // Recursively process any orphan transactions that depended on this one
11542 for (int i = 0; i < vWorkQueue.size(); i++)
11543 {
11544 uint256 hashPrev = vWorkQueue[i];
11545 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
11546 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
11547 ++mi)
11548 {
11549 const CDataStream& vMsg = *((*mi).second);
11550 CTransaction tx;
11551 CDataStream(vMsg) >> tx;
11552 CInv inv(MSG_TX, tx.GetHash());
11553
11554 if (tx.AcceptToMemoryPool(true))
11555 {
11556 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
11557 SyncWithWallets(tx, NULL, true);
11558 RelayMessage(inv, vMsg);
11559 mapAlreadyAskedFor.erase(inv);
11560 vWorkQueue.push_back(inv.hash);
11561 }
11562 }
11563 }
11564
11565 BOOST_FOREACH(uint256 hash, vWorkQueue)
11566 EraseOrphanTx(hash);
11567 }
11568 else if (fMissingInputs)
11569 {
11570 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
11571 AddOrphanTx(vMsg);
11572
11573 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
11574 int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
11575 if (nEvicted > 0)
11576 printf("mapOrphan overflow, removed %d tx\n", nEvicted);
11577 }
11578 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
11579 }
11580
11581
11582 else if (strCommand == "block")
11583 {
11584 CBlock block;
11585 vRecv >> block;
11586
11587 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
11588 // block.print();
11589
11590 CInv inv(MSG_BLOCK, block.GetHash());
11591 pfrom->AddInventoryKnown(inv);
11592
11593 if (ProcessBlock(pfrom, &block))
11594 mapAlreadyAskedFor.erase(inv);
11595 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
11596 }
11597
11598
11599 else if (strCommand == "getaddr")
11600 {
11601 // Nodes rebroadcast an addr every 24 hours
11602 pfrom->vAddrToSend.clear();
11603 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
11604 CRITICAL_BLOCK(cs_mapAddresses)
11605 {
11606 unsigned int nCount = 0;
11607 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
11608 {
11609 const CAddress& addr = item.second;
11610 if (addr.nTime > nSince)
11611 nCount++;
11612 }
11613 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
11614 {
11615 const CAddress& addr = item.second;
11616 if (addr.nTime > nSince && GetRand(nCount) < 2500)
11617 pfrom->PushAddress(addr);
11618 }
11619 }
11620 }
11621
11622
11623 else if (strCommand == "checkorder")
11624 {
11625 uint256 hashReply;
11626 vRecv >> hashReply;
11627
11628 if (!GetBoolArg("-allowreceivebyip"))
11629 {
11630 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
11631 return true;
11632 }
11633
11634 CWalletTx order;
11635 vRecv >> order;
11636
11637 /// we have a chance to check the order here
11638
11639 // Keep giving the same key to the same ip until they use it
11640 if (!mapReuseKey.count(pfrom->addr.ip))
11641 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
11642
11643 // Send back approval of order and pubkey to use
11644 CScript scriptPubKey;
11645 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
11646 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
11647 }
11648
11649
11650 else if (strCommand == "reply")
11651 {
11652 uint256 hashReply;
11653 vRecv >> hashReply;
11654
11655 CRequestTracker tracker;
11656 CRITICAL_BLOCK(pfrom->cs_mapRequests)
11657 {
11658 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
11659 if (mi != pfrom->mapRequests.end())
11660 {
11661 tracker = (*mi).second;
11662 pfrom->mapRequests.erase(mi);
11663 }
11664 }
11665 if (!tracker.IsNull())
11666 tracker.fn(tracker.param1, vRecv);
11667 }
11668
11669
11670 else if (strCommand == "ping")
11671 {
11672 }
11673
11674
11675 else if (strCommand == "alert")
11676 {
11677 CAlert alert;
11678 vRecv >> alert;
11679
11680 if (alert.ProcessAlert())
11681 {
11682 // Relay
11683 pfrom->setKnown.insert(alert.GetHash());
11684 CRITICAL_BLOCK(cs_vNodes)
11685 BOOST_FOREACH(CNode* pnode, vNodes)
11686 alert.RelayTo(pnode);
11687 }
11688 }
11689
11690
11691 else
11692 {
11693 // Ignore unknown commands for extensibility
11694 }
11695
11696
11697 // Update the last seen time for this node's address
11698 if (pfrom->fNetworkNode)
11699 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
11700 AddressCurrentlyConnected(pfrom->addr);
11701
11702
11703 return true;
11704 }
11705
11706 bool ProcessMessages(CNode* pfrom)
11707 {
11708 CDataStream& vRecv = pfrom->vRecv;
11709 if (vRecv.empty())
11710 return true;
11711 //if (fDebug)
11712 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
11713
11714 //
11715 // Message format
11716 // (4) message start
11717 // (12) command
11718 // (4) size
11719 // (4) checksum
11720 // (x) data
11721 //
11722
11723 loop
11724 {
11725 // Scan for message start
11726 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
11727 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
11728 if (vRecv.end() - pstart < nHeaderSize)
11729 {
11730 if (vRecv.size() > nHeaderSize)
11731 {
11732 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
11733 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
11734 }
11735 break;
11736 }
11737 if (pstart - vRecv.begin() > 0)
11738 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
11739 vRecv.erase(vRecv.begin(), pstart);
11740
11741 // Read header
11742 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
11743 CMessageHeader hdr;
11744 vRecv >> hdr;
11745 if (!hdr.IsValid())
11746 {
11747 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
11748 continue;
11749 }
11750 string strCommand = hdr.GetCommand();
11751
11752 // Message size
11753 unsigned int nMessageSize = hdr.nMessageSize;
11754 if (nMessageSize > MAX_SIZE)
11755 {
11756 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
11757 continue;
11758 }
11759 if (nMessageSize > vRecv.size())
11760 {
11761 // Rewind and wait for rest of message
11762 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
11763 break;
11764 }
11765
11766 // Checksum
11767 if (vRecv.GetVersion() >= 209)
11768 {
11769 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
11770 unsigned int nChecksum = 0;
11771 memcpy(&nChecksum, &hash, sizeof(nChecksum));
11772 if (nChecksum != hdr.nChecksum)
11773 {
11774 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
11775 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
11776 continue;
11777 }
11778 }
11779
11780 // Copy message to its own buffer
11781 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
11782 vRecv.ignore(nMessageSize);
11783
11784 // Process message
11785 bool fRet = false;
11786 try
11787 {
11788 CRITICAL_BLOCK(cs_main)
11789 fRet = ProcessMessage(pfrom, strCommand, vMsg);
11790 if (fShutdown)
11791 return true;
11792 }
11793 catch (std::ios_base::failure& e)
11794 {
11795 if (strstr(e.what(), "end of data"))
11796 {
11797 // Allow exceptions from underlength message on vRecv
11798 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
11799 }
11800 else if (strstr(e.what(), "size too large"))
11801 {
11802 // Allow exceptions from overlong size
11803 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
11804 }
11805 else
11806 {
11807 PrintExceptionContinue(&e, "ProcessMessage()");
11808 }
11809 }
11810 catch (std::exception& e) {
11811 PrintExceptionContinue(&e, "ProcessMessage()");
11812 } catch (...) {
11813 PrintExceptionContinue(NULL, "ProcessMessage()");
11814 }
11815
11816 if (!fRet)
11817 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
11818 }
11819
11820 vRecv.Compact();
11821 return true;
11822 }
11823
11824
11825 bool SendMessages(CNode* pto, bool fSendTrickle)
11826 {
11827 CRITICAL_BLOCK(cs_main)
11828 {
11829 // Don't send anything until we get their version message
11830 if (pto->nVersion == 0)
11831 return true;
11832
11833 // Keep-alive ping
11834 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
11835 pto->PushMessage("ping");
11836
11837 // Resend wallet transactions that haven't gotten in a block yet
11838 ResendWalletTransactions();
11839
11840 // Address refresh broadcast
11841 static int64 nLastRebroadcast;
11842 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
11843 {
11844 nLastRebroadcast = GetTime();
11845 CRITICAL_BLOCK(cs_vNodes)
11846 {
11847 BOOST_FOREACH(CNode* pnode, vNodes)
11848 {
11849 // Periodically clear setAddrKnown to allow refresh broadcasts
11850 pnode->setAddrKnown.clear();
11851
11852 // Rebroadcast our address
11853 if (addrLocalHost.IsRoutable() && !fUseProxy)
11854 {
11855 CAddress addr(addrLocalHost);
11856 addr.nTime = GetAdjustedTime();
11857 pnode->PushAddress(addr);
11858 }
11859 }
11860 }
11861 }
11862
11863 // Clear out old addresses periodically so it's not too much work at once
11864 static int64 nLastClear;
11865 if (nLastClear == 0)
11866 nLastClear = GetTime();
11867 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
11868 {
11869 nLastClear = GetTime();
11870 CRITICAL_BLOCK(cs_mapAddresses)
11871 {
11872 CAddrDB addrdb;
11873 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
11874 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
11875 mi != mapAddresses.end();)
11876 {
11877 const CAddress& addr = (*mi).second;
11878 if (addr.nTime < nSince)
11879 {
11880 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
11881 break;
11882 addrdb.EraseAddress(addr);
11883 mapAddresses.erase(mi++);
11884 }
11885 else
11886 mi++;
11887 }
11888 }
11889 }
11890
11891
11892 //
11893 // Message: addr
11894 //
11895 if (fSendTrickle)
11896 {
11897 vector<CAddress> vAddr;
11898 vAddr.reserve(pto->vAddrToSend.size());
11899 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
11900 {
11901 // returns true if wasn't already contained in the set
11902 if (pto->setAddrKnown.insert(addr).second)
11903 {
11904 vAddr.push_back(addr);
11905 // receiver rejects addr messages larger than 1000
11906 if (vAddr.size() >= 1000)
11907 {
11908 pto->PushMessage("addr", vAddr);
11909 vAddr.clear();
11910 }
11911 }
11912 }
11913 pto->vAddrToSend.clear();
11914 if (!vAddr.empty())
11915 pto->PushMessage("addr", vAddr);
11916 }
11917
11918
11919 //
11920 // Message: inventory
11921 //
11922 vector<CInv> vInv;
11923 vector<CInv> vInvWait;
11924 CRITICAL_BLOCK(pto->cs_inventory)
11925 {
11926 vInv.reserve(pto->vInventoryToSend.size());
11927 vInvWait.reserve(pto->vInventoryToSend.size());
11928 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
11929 {
11930 if (pto->setInventoryKnown.count(inv))
11931 continue;
11932
11933 // trickle out tx inv to protect privacy
11934 if (inv.type == MSG_TX && !fSendTrickle)
11935 {
11936 // 1/4 of tx invs blast to all immediately
11937 static uint256 hashSalt;
11938 if (hashSalt == 0)
11939 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
11940 uint256 hashRand = inv.hash ^ hashSalt;
11941 hashRand = Hash(BEGIN(hashRand), END(hashRand));
11942 bool fTrickleWait = ((hashRand & 3) != 0);
11943
11944 // always trickle our own transactions
11945 if (!fTrickleWait)
11946 {
11947 CWalletTx wtx;
11948 if (GetTransaction(inv.hash, wtx))
11949 if (wtx.fFromMe)
11950 fTrickleWait = true;
11951 }
11952
11953 if (fTrickleWait)
11954 {
11955 vInvWait.push_back(inv);
11956 continue;
11957 }
11958 }
11959
11960 // returns true if wasn't already contained in the set
11961 if (pto->setInventoryKnown.insert(inv).second)
11962 {
11963 vInv.push_back(inv);
11964 if (vInv.size() >= 1000)
11965 {
11966 pto->PushMessage("inv", vInv);
11967 vInv.clear();
11968 }
11969 }
11970 }
11971 pto->vInventoryToSend = vInvWait;
11972 }
11973 if (!vInv.empty())
11974 pto->PushMessage("inv", vInv);
11975
11976
11977 //
11978 // Message: getdata
11979 //
11980 vector<CInv> vGetData;
11981 int64 nNow = GetTime() * 1000000;
11982 CTxDB txdb("r");
11983 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
11984 {
11985 const CInv& inv = (*pto->mapAskFor.begin()).second;
11986 if (!AlreadyHave(txdb, inv))
11987 {
11988 printf("sending getdata: %s\n", inv.ToString().c_str());
11989 vGetData.push_back(inv);
11990 if (vGetData.size() >= 1000)
11991 {
11992 pto->PushMessage("getdata", vGetData);
11993 vGetData.clear();
11994 }
11995 }
11996 mapAlreadyAskedFor[inv] = nNow;
11997 pto->mapAskFor.erase(pto->mapAskFor.begin());
11998 }
11999 if (!vGetData.empty())
12000 pto->PushMessage("getdata", vGetData);
12001
12002 }
12003 return true;
12004 }
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019 //////////////////////////////////////////////////////////////////////////////
12020 //
12021 // BitcoinMiner
12022 //
12023
12024 int static FormatHashBlocks(void* pbuffer, unsigned int len)
12025 {
12026 unsigned char* pdata = (unsigned char*)pbuffer;
12027 unsigned int blocks = 1 + ((len + 8) / 64);
12028 unsigned char* pend = pdata + 64 * blocks;
12029 memset(pdata + len, 0, 64 * blocks - len);
12030 pdata[len] = 0x80;
12031 unsigned int bits = len * 8;
12032 pend[-1] = (bits >> 0) & 0xff;
12033 pend[-2] = (bits >> 8) & 0xff;
12034 pend[-3] = (bits >> 16) & 0xff;
12035 pend[-4] = (bits >> 24) & 0xff;
12036 return blocks;
12037 }
12038
12039 static const unsigned int pSHA256InitState[8] =
12040 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
12041
12042 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
12043 {
12044 SHA256_CTX ctx;
12045 unsigned char data[64];
12046
12047 SHA256_Init(&ctx);
12048
12049 for (int i = 0; i < 16; i++)
12050 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
12051
12052 for (int i = 0; i < 8; i++)
12053 ctx.h[i] = ((uint32_t*)pinit)[i];
12054
12055 SHA256_Update(&ctx, data, sizeof(data));
12056 for (int i = 0; i < 8; i++)
12057 ((uint32_t*)pstate)[i] = ctx.h[i];
12058 }
12059
12060 //
12061 // ScanHash scans nonces looking for a hash with at least some zero bits.
12062 // It operates on big endian data. Caller does the byte reversing.
12063 // All input buffers are 16-byte aligned. nNonce is usually preserved
12064 // between calls, but periodically or if nNonce is 0xffff0000 or above,
12065 // the block is rebuilt and nNonce starts over at zero.
12066 //
12067 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
12068 {
12069 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
12070 for (;;)
12071 {
12072 // Crypto++ SHA-256
12073 // Hash pdata using pmidstate as the starting state into
12074 // preformatted buffer phash1, then hash phash1 into phash
12075 nNonce++;
12076 SHA256Transform(phash1, pdata, pmidstate);
12077 SHA256Transform(phash, phash1, pSHA256InitState);
12078
12079 // Return the nonce if the hash has at least some zero bits,
12080 // caller will check if it has enough to reach the target
12081 if (((unsigned short*)phash)[14] == 0)
12082 return nNonce;
12083
12084 // If nothing found after trying for a while, return -1
12085 if ((nNonce & 0xffff) == 0)
12086 {
12087 nHashesDone = 0xffff+1;
12088 return -1;
12089 }
12090 }
12091 }
12092
12093 // Some explaining would be appreciated
12094 class COrphan
12095 {
12096 public:
12097 CTransaction* ptx;
12098 set<uint256> setDependsOn;
12099 double dPriority;
12100
12101 COrphan(CTransaction* ptxIn)
12102 {
12103 ptx = ptxIn;
12104 dPriority = 0;
12105 }
12106
12107 void print() const
12108 {
12109 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
12110 BOOST_FOREACH(uint256 hash, setDependsOn)
12111 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
12112 }
12113 };
12114
12115
12116 CBlock* CreateNewBlock(CReserveKey& reservekey)
12117 {
12118 CBlockIndex* pindexPrev = pindexBest;
12119
12120 // Create new block
12121 auto_ptr<CBlock> pblock(new CBlock());
12122 if (!pblock.get())
12123 return NULL;
12124
12125 // Create coinbase tx
12126 CTransaction txNew;
12127 txNew.vin.resize(1);
12128 txNew.vin[0].prevout.SetNull();
12129 txNew.vout.resize(1);
12130 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
12131
12132 // Add our coinbase tx as first transaction
12133 pblock->vtx.push_back(txNew);
12134
12135 // Collect memory pool transactions into the block
12136 int64 nFees = 0;
12137 CRITICAL_BLOCK(cs_main)
12138 CRITICAL_BLOCK(cs_mapTransactions)
12139 {
12140 CTxDB txdb("r");
12141
12142 // Priority order to process transactions
12143 list<COrphan> vOrphan; // list memory doesn't move
12144 map<uint256, vector<COrphan*> > mapDependers;
12145 multimap<double, CTransaction*> mapPriority;
12146 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
12147 {
12148 CTransaction& tx = (*mi).second;
12149 if (tx.IsCoinBase() || !tx.IsFinal())
12150 continue;
12151
12152 COrphan* porphan = NULL;
12153 double dPriority = 0;
12154 BOOST_FOREACH(const CTxIn& txin, tx.vin)
12155 {
12156 // Read prev transaction
12157 CTransaction txPrev;
12158 CTxIndex txindex;
12159 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
12160 {
12161 // Has to wait for dependencies
12162 if (!porphan)
12163 {
12164 // Use list for automatic deletion
12165 vOrphan.push_back(COrphan(&tx));
12166 porphan = &vOrphan.back();
12167 }
12168 mapDependers[txin.prevout.hash].push_back(porphan);
12169 porphan->setDependsOn.insert(txin.prevout.hash);
12170 continue;
12171 }
12172 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
12173
12174 // Read block header
12175 int nConf = txindex.GetDepthInMainChain();
12176
12177 dPriority += (double)nValueIn * nConf;
12178
12179 if (fDebug && GetBoolArg("-printpriority"))
12180 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
12181 }
12182
12183 // Priority is sum(valuein * age) / txsize
12184 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
12185
12186 if (porphan)
12187 porphan->dPriority = dPriority;
12188 else
12189 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
12190
12191 if (fDebug && GetBoolArg("-printpriority"))
12192 {
12193 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
12194 if (porphan)
12195 porphan->print();
12196 printf("\n");
12197 }
12198 }
12199
12200 // Collect transactions into block
12201 map<uint256, CTxIndex> mapTestPool;
12202 uint64 nBlockSize = 1000;
12203 int nBlockSigOps = 100;
12204 while (!mapPriority.empty())
12205 {
12206 // Take highest priority transaction off priority queue
12207 double dPriority = -(*mapPriority.begin()).first;
12208 CTransaction& tx = *(*mapPriority.begin()).second;
12209 mapPriority.erase(mapPriority.begin());
12210
12211 // Size limits
12212 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
12213 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
12214 continue;
12215 int nTxSigOps = tx.GetSigOpCount();
12216 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
12217 continue;
12218
12219 // Transaction fee required depends on block size
12220 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
12221 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
12222
12223 // Connecting shouldn't fail due to dependency on other memory pool transactions
12224 // because we're already processing them in order of dependency
12225 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
12226 bool fInvalid;
12227 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee, fInvalid))
12228 continue;
12229 swap(mapTestPool, mapTestPoolTmp);
12230
12231 // Added
12232 pblock->vtx.push_back(tx);
12233 nBlockSize += nTxSize;
12234 nBlockSigOps += nTxSigOps;
12235
12236 // Add transactions that depend on this one to the priority queue
12237 uint256 hash = tx.GetHash();
12238 if (mapDependers.count(hash))
12239 {
12240 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
12241 {
12242 if (!porphan->setDependsOn.empty())
12243 {
12244 porphan->setDependsOn.erase(hash);
12245 if (porphan->setDependsOn.empty())
12246 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
12247 }
12248 }
12249 }
12250 }
12251 }
12252 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
12253
12254 // Fill in header
12255 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
12256 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
12257 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
12258 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
12259 pblock->nNonce = 0;
12260
12261 return pblock.release();
12262 }
12263
12264
12265 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
12266 {
12267 // Update nExtraNonce
12268 static uint256 hashPrevBlock;
12269 if (hashPrevBlock != pblock->hashPrevBlock)
12270 {
12271 nExtraNonce = 0;
12272 hashPrevBlock = pblock->hashPrevBlock;
12273 }
12274 ++nExtraNonce;
12275 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
12276 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
12277 }
12278
12279
12280 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
12281 {
12282 //
12283 // Prebuild hash buffers
12284 //
12285 struct
12286 {
12287 struct unnamed2
12288 {
12289 int nVersion;
12290 uint256 hashPrevBlock;
12291 uint256 hashMerkleRoot;
12292 unsigned int nTime;
12293 unsigned int nBits;
12294 unsigned int nNonce;
12295 }
12296 block;
12297 unsigned char pchPadding0[64];
12298 uint256 hash1;
12299 unsigned char pchPadding1[64];
12300 }
12301 tmp;
12302 memset(&tmp, 0, sizeof(tmp));
12303
12304 tmp.block.nVersion = pblock->nVersion;
12305 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
12306 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
12307 tmp.block.nTime = pblock->nTime;
12308 tmp.block.nBits = pblock->nBits;
12309 tmp.block.nNonce = pblock->nNonce;
12310
12311 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
12312 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
12313
12314 // Byte swap all the input buffer
12315 for (int i = 0; i < sizeof(tmp)/4; i++)
12316 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
12317
12318 // Precalc the first half of the first hash, which stays constant
12319 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
12320
12321 memcpy(pdata, &tmp.block, 128);
12322 memcpy(phash1, &tmp.hash1, 64);
12323 }
12324
12325
12326 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
12327 {
12328 uint256 hash = pblock->GetHash();
12329 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
12330
12331 if (hash > hashTarget)
12332 return false;
12333
12334 //// debug print
12335 printf("BitcoinMiner:\n");
12336 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
12337 pblock->print();
12338 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
12339 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
12340
12341 // Found a solution
12342 CRITICAL_BLOCK(cs_main)
12343 {
12344 if (pblock->hashPrevBlock != hashBestChain)
12345 return error("BitcoinMiner : generated block is stale");
12346
12347 // Remove key from key pool
12348 reservekey.KeepKey();
12349
12350 // Track how many getdata requests this block gets
12351 CRITICAL_BLOCK(wallet.cs_wallet)
12352 wallet.mapRequestCount[pblock->GetHash()] = 0;
12353
12354 // Process this block the same as if we had received it from another node
12355 if (!ProcessBlock(NULL, pblock))
12356 return error("BitcoinMiner : ProcessBlock, block not accepted");
12357 }
12358
12359 return true;
12360 }
12361
12362 void static ThreadBitcoinMiner(void* parg);
12363
12364 void static BitcoinMiner(CWallet *pwallet)
12365 {
12366 printf("BitcoinMiner started\n");
12367 SetThreadPriority(THREAD_PRIORITY_LOWEST);
12368
12369 // Each thread has its own key and counter
12370 CReserveKey reservekey(pwallet);
12371 unsigned int nExtraNonce = 0;
12372
12373 while (fGenerateBitcoins)
12374 {
12375 if (AffinityBugWorkaround(ThreadBitcoinMiner))
12376 return;
12377 if (fShutdown)
12378 return;
12379 while (vNodes.empty() || IsInitialBlockDownload())
12380 {
12381 Sleep(1000);
12382 if (fShutdown)
12383 return;
12384 if (!fGenerateBitcoins)
12385 return;
12386 }
12387
12388
12389 //
12390 // Create new block
12391 //
12392 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
12393 CBlockIndex* pindexPrev = pindexBest;
12394
12395 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
12396 if (!pblock.get())
12397 return;
12398 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
12399
12400 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
12401
12402
12403 //
12404 // Prebuild hash buffers
12405 //
12406 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
12407 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
12408 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
12409
12410 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
12411
12412 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
12413 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
12414
12415
12416 //
12417 // Search
12418 //
12419 int64 nStart = GetTime();
12420 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
12421 uint256 hashbuf[2];
12422 uint256& hash = *alignup<16>(hashbuf);
12423 loop
12424 {
12425 unsigned int nHashesDone = 0;
12426 unsigned int nNonceFound;
12427
12428 // Crypto++ SHA-256
12429 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
12430 (char*)&hash, nHashesDone);
12431
12432 // Check if something found
12433 if (nNonceFound != -1)
12434 {
12435 for (int i = 0; i < sizeof(hash)/4; i++)
12436 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
12437
12438 if (hash <= hashTarget)
12439 {
12440 // Found a solution
12441 pblock->nNonce = ByteReverse(nNonceFound);
12442 assert(hash == pblock->GetHash());
12443
12444 SetThreadPriority(THREAD_PRIORITY_NORMAL);
12445 CheckWork(pblock.get(), *pwalletMain, reservekey);
12446 SetThreadPriority(THREAD_PRIORITY_LOWEST);
12447 break;
12448 }
12449 }
12450
12451 // Meter hashes/sec
12452 static int64 nHashCounter;
12453 if (nHPSTimerStart == 0)
12454 {
12455 nHPSTimerStart = GetTimeMillis();
12456 nHashCounter = 0;
12457 }
12458 else
12459 nHashCounter += nHashesDone;
12460 if (GetTimeMillis() - nHPSTimerStart > 4000)
12461 {
12462 static CCriticalSection cs;
12463 CRITICAL_BLOCK(cs)
12464 {
12465 if (GetTimeMillis() - nHPSTimerStart > 4000)
12466 {
12467 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
12468 nHPSTimerStart = GetTimeMillis();
12469 nHashCounter = 0;
12470 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
12471 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
12472 static int64 nLogTime;
12473 if (GetTime() - nLogTime > 30 * 60)
12474 {
12475 nLogTime = GetTime();
12476 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
12477 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
12478 }
12479 }
12480 }
12481 }
12482
12483 // Check for stop or if block needs to be rebuilt
12484 if (fShutdown)
12485 return;
12486 if (!fGenerateBitcoins)
12487 return;
12488 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
12489 return;
12490 if (vNodes.empty())
12491 break;
12492 if (nBlockNonce >= 0xffff0000)
12493 break;
12494 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
12495 break;
12496 if (pindexPrev != pindexBest)
12497 break;
12498
12499 // Update nTime every few seconds
12500 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
12501 nBlockTime = ByteReverse(pblock->nTime);
12502 }
12503 }
12504 }
12505
12506 void static ThreadBitcoinMiner(void* parg)
12507 {
12508 CWallet* pwallet = (CWallet*)parg;
12509 try
12510 {
12511 vnThreadsRunning[3]++;
12512 BitcoinMiner(pwallet);
12513 vnThreadsRunning[3]--;
12514 }
12515 catch (std::exception& e) {
12516 vnThreadsRunning[3]--;
12517 PrintException(&e, "ThreadBitcoinMiner()");
12518 } catch (...) {
12519 vnThreadsRunning[3]--;
12520 PrintException(NULL, "ThreadBitcoinMiner()");
12521 }
12522 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
12523 nHPSTimerStart = 0;
12524 if (vnThreadsRunning[3] == 0)
12525 dHashesPerSec = 0;
12526 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
12527 }
12528
12529
12530 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
12531 {
12532 if (fGenerateBitcoins != fGenerate)
12533 {
12534 fGenerateBitcoins = fGenerate;
12535 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
12536 MainFrameRepaint();
12537 }
12538 if (fGenerateBitcoins)
12539 {
12540 int nProcessors = boost::thread::hardware_concurrency();
12541 printf("%d processors\n", nProcessors);
12542 if (nProcessors < 1)
12543 nProcessors = 1;
12544 if (fLimitProcessors && nProcessors > nLimitProcessors)
12545 nProcessors = nLimitProcessors;
12546 int nAddThreads = nProcessors - vnThreadsRunning[3];
12547 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
12548 for (int i = 0; i < nAddThreads; i++)
12549 {
12550 if (!CreateThread(ThreadBitcoinMiner, pwallet))
12551 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
12552 Sleep(10);
12553 }
12554 }
12555 }