-
+ 2A682FA7EA33A7F5485CF9F3026F8802BE6EB13CD23D0B7C855DC55D61941BA566B547996F15B2ECCCB6F0A15E3929E915EC02F60F29DE985C656EAB353EB9B9bitcoin/src/main.cpp(0 . 0)(1 . 3281)
10329 // /****************************\
10330 // * EXPERIMENTAL BRANCH. *
10331 // * FOR LABORATORY USE ONLY. *
10332 // ********************************
10333 // ************
10334 // **************
10335 // ****************
10336 // **** **** ****
10337 // *** *** ***
10338 // *** *** ***
10339 // *** * * **
10340 // ******** ********
10341 // ******* ******
10342 // *** **
10343 // * ******* **
10344 // ** * * * * *
10345 // ** * * ***
10346 // **** * * * * ****
10347 // **** *** * * ** ***
10348 // **** ********* ******
10349 // ******* ***** *******
10350 // ********* ****** **
10351 // ** ****** ******
10352 // ** ******* **
10353 // ** ******* ***
10354 // **** ******** ************
10355 // ************ ************
10356 // ******** *******
10357 // ****** ****
10358 // *** ***
10359 // ********************************
10360 // Copyright (c) 2009-2010 Satoshi Nakamoto
10361 // Copyright (c) 2009-2012 The Bitcoin developers
10362 // Distributed under the MIT/X11 software license, see the accompanying
10363 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10364 #include "headers.h"
10365 #include "checkpoints.h"
10366 #include "db.h"
10367 #include "net.h"
10368 #include "init.h"
10369 #include <boost/filesystem.hpp>
10370 #include <boost/filesystem/fstream.hpp>
10371
10372 using namespace std;
10373 using namespace boost;
10374
10375 //
10376 // Global state
10377 //
10378
10379 CCriticalSection cs_setpwalletRegistered;
10380 set<CWallet*> setpwalletRegistered;
10381
10382 CCriticalSection cs_main;
10383
10384 static map<uint256, CTransaction> mapTransactions;
10385 CCriticalSection cs_mapTransactions;
10386 unsigned int nTransactionsUpdated = 0;
10387 map<COutPoint, CInPoint> mapNextTx;
10388
10389 map<uint256, CBlockIndex*> mapBlockIndex;
10390 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
10391 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
10392 CBlockIndex* pindexGenesisBlock = NULL;
10393 int nBestHeight = -1;
10394 CBigNum bnBestChainWork = 0;
10395 CBigNum bnBestInvalidWork = 0;
10396 uint256 hashBestChain = 0;
10397 CBlockIndex* pindexBest = NULL;
10398 int64 nTimeBestReceived = 0;
10399
10400 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
10401
10402 map<uint256, CBlock*> mapOrphanBlocks;
10403 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
10404
10405 map<uint256, CDataStream*> mapOrphanTransactions;
10406 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
10407
10408
10409 double dHashesPerSec;
10410 int64 nHPSTimerStart;
10411
10412 // Settings
10413 int fGenerateBitcoins = false;
10414 int64 nTransactionFee = 0;
10415 int fLimitProcessors = false;
10416 int nLimitProcessors = 1;
10417 int fMinimizeToTray = true;
10418 int fMinimizeOnClose = true;
10419 #if USE_UPNP
10420 int fUseUPnP = true;
10421 #else
10422 int fUseUPnP = false;
10423 #endif
10424
10425
10426 //////////////////////////////////////////////////////////////////////////////
10427 //
10428 // dispatching functions
10429 //
10430
10431 // These functions dispatch to one or all registered wallets
10432
10433
10434 void RegisterWallet(CWallet* pwalletIn)
10435 {
10436 CRITICAL_BLOCK(cs_setpwalletRegistered)
10437 {
10438 setpwalletRegistered.insert(pwalletIn);
10439 }
10440 }
10441
10442 void UnregisterWallet(CWallet* pwalletIn)
10443 {
10444 CRITICAL_BLOCK(cs_setpwalletRegistered)
10445 {
10446 setpwalletRegistered.erase(pwalletIn);
10447 }
10448 }
10449
10450 // check whether the passed transaction is from us
10451 bool static IsFromMe(CTransaction& tx)
10452 {
10453 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10454 if (pwallet->IsFromMe(tx))
10455 return true;
10456 return false;
10457 }
10458
10459 // get the wallet transaction with the given hash (if it exists)
10460 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
10461 {
10462 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10463 if (pwallet->GetTransaction(hashTx,wtx))
10464 return true;
10465 return false;
10466 }
10467
10468 // erases transaction with the given hash from all wallets
10469 void static EraseFromWallets(uint256 hash)
10470 {
10471 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10472 pwallet->EraseFromWallet(hash);
10473 }
10474
10475 // make sure all wallets know about the given transaction, in the given block
10476 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
10477 {
10478 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10479 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
10480 }
10481
10482 // notify wallets about a new best chain
10483 void static SetBestChain(const CBlockLocator& loc)
10484 {
10485 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10486 pwallet->SetBestChain(loc);
10487 }
10488
10489 // notify wallets about an updated transaction
10490 void static UpdatedTransaction(const uint256& hashTx)
10491 {
10492 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10493 pwallet->UpdatedTransaction(hashTx);
10494 }
10495
10496 // dump all wallets
10497 void static PrintWallets(const CBlock& block)
10498 {
10499 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10500 pwallet->PrintWallet(block);
10501 }
10502
10503 // notify wallets about an incoming inventory (for request counts)
10504 void static Inventory(const uint256& hash)
10505 {
10506 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10507 pwallet->Inventory(hash);
10508 }
10509
10510 // ask wallets to resend their transactions
10511 void static ResendWalletTransactions()
10512 {
10513 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
10514 pwallet->ResendWalletTransactions();
10515 }
10516
10517
10518
10519
10520
10521
10522
10523 //////////////////////////////////////////////////////////////////////////////
10524 //
10525 // mapOrphanTransactions
10526 //
10527
10528 void AddOrphanTx(const CDataStream& vMsg)
10529 {
10530 CTransaction tx;
10531 CDataStream(vMsg) >> tx;
10532 uint256 hash = tx.GetHash();
10533 if (mapOrphanTransactions.count(hash))
10534 return;
10535
10536 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
10537 BOOST_FOREACH(const CTxIn& txin, tx.vin)
10538 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
10539 }
10540
10541 void static EraseOrphanTx(uint256 hash)
10542 {
10543 if (!mapOrphanTransactions.count(hash))
10544 return;
10545 const CDataStream* pvMsg = mapOrphanTransactions[hash];
10546 CTransaction tx;
10547 CDataStream(*pvMsg) >> tx;
10548 BOOST_FOREACH(const CTxIn& txin, tx.vin)
10549 {
10550 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
10551 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
10552 {
10553 if ((*mi).second == pvMsg)
10554 mapOrphanTransactionsByPrev.erase(mi++);
10555 else
10556 mi++;
10557 }
10558 }
10559 delete pvMsg;
10560 mapOrphanTransactions.erase(hash);
10561 }
10562
10563 int LimitOrphanTxSize(int nMaxOrphans)
10564 {
10565 int nEvicted = 0;
10566 while (mapOrphanTransactions.size() > nMaxOrphans)
10567 {
10568 // Evict a random orphan:
10569 std::vector<unsigned char> randbytes(32);
10570 RAND_bytes(&randbytes[0], 32);
10571 uint256 randomhash(randbytes);
10572 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
10573 if (it == mapOrphanTransactions.end())
10574 it = mapOrphanTransactions.begin();
10575 EraseOrphanTx(it->first);
10576 ++nEvicted;
10577 }
10578 return nEvicted;
10579 }
10580
10581
10582
10583
10584
10585
10586
10587 //////////////////////////////////////////////////////////////////////////////
10588 //
10589 // CTransaction and CTxIndex
10590 //
10591
10592 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
10593 {
10594 SetNull();
10595 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
10596 return false;
10597 if (!ReadFromDisk(txindexRet.pos))
10598 return false;
10599 if (prevout.n >= vout.size())
10600 {
10601 SetNull();
10602 return false;
10603 }
10604 return true;
10605 }
10606
10607 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
10608 {
10609 CTxIndex txindex;
10610 return ReadFromDisk(txdb, prevout, txindex);
10611 }
10612
10613 bool CTransaction::ReadFromDisk(COutPoint prevout)
10614 {
10615 CTxDB txdb("r");
10616 CTxIndex txindex;
10617 return ReadFromDisk(txdb, prevout, txindex);
10618 }
10619
10620
10621
10622 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
10623 {
10624 if (fClient)
10625 {
10626 if (hashBlock == 0)
10627 return 0;
10628 }
10629 else
10630 {
10631 CBlock blockTmp;
10632 if (pblock == NULL)
10633 {
10634 // Load the block this tx is in
10635 CTxIndex txindex;
10636 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
10637 return 0;
10638 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
10639 return 0;
10640 pblock = &blockTmp;
10641 }
10642
10643 // Update the tx's hashBlock
10644 hashBlock = pblock->GetHash();
10645
10646 // Locate the transaction
10647 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
10648 if (pblock->vtx[nIndex] == *(CTransaction*)this)
10649 break;
10650 if (nIndex == pblock->vtx.size())
10651 {
10652 vMerkleBranch.clear();
10653 nIndex = -1;
10654 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
10655 return 0;
10656 }
10657
10658 // Fill in merkle branch
10659 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
10660 }
10661
10662 // Is the tx in a block that's in the main chain
10663 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
10664 if (mi == mapBlockIndex.end())
10665 return 0;
10666 CBlockIndex* pindex = (*mi).second;
10667 if (!pindex || !pindex->IsInMainChain())
10668 return 0;
10669
10670 return pindexBest->nHeight - pindex->nHeight + 1;
10671 }
10672
10673
10674
10675
10676
10677
10678
10679 bool CTransaction::CheckTransaction() const
10680 {
10681 // Basic checks that don't depend on any context
10682 if (vin.empty())
10683 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
10684 if (vout.empty())
10685 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
10686 // Size limits
10687 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
10688 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
10689
10690 // Check for negative or overflow output values
10691 int64 nValueOut = 0;
10692 BOOST_FOREACH(const CTxOut& txout, vout)
10693 {
10694 if (txout.nValue < 0)
10695 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
10696 if (txout.nValue > MAX_MONEY)
10697 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
10698 nValueOut += txout.nValue;
10699 if (!MoneyRange(nValueOut))
10700 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
10701 }
10702
10703 // Check for duplicate inputs
10704 set<COutPoint> vInOutPoints;
10705 BOOST_FOREACH(const CTxIn& txin, vin)
10706 {
10707 if (vInOutPoints.count(txin.prevout))
10708 return false;
10709 vInOutPoints.insert(txin.prevout);
10710 }
10711
10712 if (IsCoinBase())
10713 {
10714 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
10715 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
10716 }
10717 else
10718 {
10719 BOOST_FOREACH(const CTxIn& txin, vin)
10720 if (txin.prevout.IsNull())
10721 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
10722 }
10723
10724 return true;
10725 }
10726
10727 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
10728 {
10729 if (pfMissingInputs)
10730 *pfMissingInputs = false;
10731
10732 if (!CheckTransaction())
10733 return error("AcceptToMemoryPool() : CheckTransaction failed");
10734
10735 // Coinbase is only valid in a block, not as a loose transaction
10736 if (IsCoinBase())
10737 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
10738
10739 // To help v0.1.5 clients who would see it as a negative number
10740 if ((int64)nLockTime > INT_MAX)
10741 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
10742
10743 // Safety limits
10744 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
10745 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
10746 // attacks disallow transactions with more than one SigOp per 34 bytes.
10747 // 34 bytes because a TxOut is:
10748 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
10749 if (GetSigOpCount() > nSize / 34 || nSize < 100)
10750 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
10751
10752 // Rather not work on nonstandard transactions (unless -testnet)
10753 if (!fTestNet && !IsStandard())
10754 return error("AcceptToMemoryPool() : nonstandard transaction type");
10755
10756 // Do we already have it?
10757 uint256 hash = GetHash();
10758 CRITICAL_BLOCK(cs_mapTransactions)
10759 if (mapTransactions.count(hash))
10760 return false;
10761 if (fCheckInputs)
10762 if (txdb.ContainsTx(hash))
10763 return false;
10764
10765 // Check for conflicts with in-memory transactions
10766 CTransaction* ptxOld = NULL;
10767 for (int i = 0; i < vin.size(); i++)
10768 {
10769 COutPoint outpoint = vin[i].prevout;
10770 if (mapNextTx.count(outpoint))
10771 {
10772 // Disable replacement feature for now
10773 return false;
10774
10775 // Allow replacing with a newer version of the same transaction
10776 if (i != 0)
10777 return false;
10778 ptxOld = mapNextTx[outpoint].ptx;
10779 if (ptxOld->IsFinal())
10780 return false;
10781 if (!IsNewerThan(*ptxOld))
10782 return false;
10783 for (int i = 0; i < vin.size(); i++)
10784 {
10785 COutPoint outpoint = vin[i].prevout;
10786 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
10787 return false;
10788 }
10789 break;
10790 }
10791 }
10792
10793 if (fCheckInputs)
10794 {
10795 // Check against previous transactions
10796 map<uint256, CTxIndex> mapUnused;
10797 int64 nFees = 0;
10798 bool fInvalid = false;
10799 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, 0, fInvalid))
10800 {
10801 if (fInvalid)
10802 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
10803 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
10804 }
10805
10806 // Don't accept it if it can't get into a block
10807 if (nFees < GetMinFee(1000, true, true))
10808 return error("AcceptToMemoryPool() : not enough fees");
10809
10810 // Continuously rate-limit free transactions
10811 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
10812 // be annoying or make other's transactions take longer to confirm.
10813 if (nFees < MIN_RELAY_TX_FEE)
10814 {
10815 static CCriticalSection cs;
10816 static double dFreeCount;
10817 static int64 nLastTime;
10818 int64 nNow = GetTime();
10819
10820 CRITICAL_BLOCK(cs)
10821 {
10822 // Use an exponentially decaying ~10-minute window:
10823 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
10824 nLastTime = nNow;
10825 // -limitfreerelay unit is thousand-bytes-per-minute
10826 // At default rate it would take over a month to fill 1GB
10827 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
10828 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
10829 if (fDebug)
10830 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
10831 dFreeCount += nSize;
10832 }
10833 }
10834 }
10835
10836 // Store transaction in memory
10837 CRITICAL_BLOCK(cs_mapTransactions)
10838 {
10839 if (ptxOld)
10840 {
10841 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
10842 ptxOld->RemoveFromMemoryPool();
10843 }
10844 AddToMemoryPoolUnchecked();
10845 }
10846
10847 ///// are we sure this is ok when loading transactions or restoring block txes
10848 // If updated, erase old tx from wallet
10849 if (ptxOld)
10850 EraseFromWallets(ptxOld->GetHash());
10851
10852 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
10853 return true;
10854 }
10855
10856 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
10857 {
10858 CTxDB txdb("r");
10859 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
10860 }
10861
10862 bool CTransaction::AddToMemoryPoolUnchecked()
10863 {
10864 // Add to memory pool without checking anything. Don't call this directly,
10865 // call AcceptToMemoryPool to properly check the transaction first.
10866 CRITICAL_BLOCK(cs_mapTransactions)
10867 {
10868 uint256 hash = GetHash();
10869 mapTransactions[hash] = *this;
10870 for (int i = 0; i < vin.size(); i++)
10871 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
10872 nTransactionsUpdated++;
10873 }
10874 return true;
10875 }
10876
10877
10878 bool CTransaction::RemoveFromMemoryPool()
10879 {
10880 // Remove transaction from memory pool
10881 CRITICAL_BLOCK(cs_mapTransactions)
10882 {
10883 BOOST_FOREACH(const CTxIn& txin, vin)
10884 mapNextTx.erase(txin.prevout);
10885 mapTransactions.erase(GetHash());
10886 nTransactionsUpdated++;
10887 }
10888 return true;
10889 }
10890
10891
10892
10893
10894
10895
10896 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
10897 {
10898 if (hashBlock == 0 || nIndex == -1)
10899 return 0;
10900
10901 // Find the block it claims to be in
10902 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
10903 if (mi == mapBlockIndex.end())
10904 return 0;
10905 CBlockIndex* pindex = (*mi).second;
10906 if (!pindex || !pindex->IsInMainChain())
10907 return 0;
10908
10909 // Make sure the merkle branch connects to this block
10910 if (!fMerkleVerified)
10911 {
10912 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
10913 return 0;
10914 fMerkleVerified = true;
10915 }
10916
10917 nHeightRet = pindex->nHeight;
10918 return pindexBest->nHeight - pindex->nHeight + 1;
10919 }
10920
10921
10922 int CMerkleTx::GetBlocksToMaturity() const
10923 {
10924 if (!IsCoinBase())
10925 return 0;
10926 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
10927 }
10928
10929
10930 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
10931 {
10932 if (fClient)
10933 {
10934 if (!IsInMainChain() && !ClientConnectInputs())
10935 return false;
10936 return CTransaction::AcceptToMemoryPool(txdb, false);
10937 }
10938 else
10939 {
10940 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
10941 }
10942 }
10943
10944 bool CMerkleTx::AcceptToMemoryPool()
10945 {
10946 CTxDB txdb("r");
10947 return AcceptToMemoryPool(txdb);
10948 }
10949
10950
10951
10952 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
10953 {
10954 CRITICAL_BLOCK(cs_mapTransactions)
10955 {
10956 // Add previous supporting transactions first
10957 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
10958 {
10959 if (!tx.IsCoinBase())
10960 {
10961 uint256 hash = tx.GetHash();
10962 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
10963 tx.AcceptToMemoryPool(txdb, fCheckInputs);
10964 }
10965 }
10966 return AcceptToMemoryPool(txdb, fCheckInputs);
10967 }
10968 return false;
10969 }
10970
10971 bool CWalletTx::AcceptWalletTransaction()
10972 {
10973 CTxDB txdb("r");
10974 return AcceptWalletTransaction(txdb);
10975 }
10976
10977 int CTxIndex::GetDepthInMainChain() const
10978 {
10979 // Read block header
10980 CBlock block;
10981 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
10982 return 0;
10983 // Find the block in the index
10984 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
10985 if (mi == mapBlockIndex.end())
10986 return 0;
10987 CBlockIndex* pindex = (*mi).second;
10988 if (!pindex || !pindex->IsInMainChain())
10989 return 0;
10990 return 1 + nBestHeight - pindex->nHeight;
10991 }
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002 //////////////////////////////////////////////////////////////////////////////
11003 //
11004 // CBlock and CBlockIndex
11005 //
11006
11007 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
11008 {
11009 if (!fReadTransactions)
11010 {
11011 *this = pindex->GetBlockHeader();
11012 return true;
11013 }
11014 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
11015 return false;
11016 if (GetHash() != pindex->GetBlockHash())
11017 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
11018 return true;
11019 }
11020
11021 uint256 static GetOrphanRoot(const CBlock* pblock)
11022 {
11023 // Work back to the first block in the orphan chain
11024 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
11025 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
11026 return pblock->GetHash();
11027 }
11028
11029 int64 static GetBlockValue(int nHeight, int64 nFees)
11030 {
11031 int64 nSubsidy = 50 * COIN;
11032
11033 // Subsidy is cut in half every 4 years
11034 nSubsidy >>= (nHeight / 210000);
11035
11036 return nSubsidy + nFees;
11037 }
11038
11039 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
11040 static const int64 nTargetSpacing = 10 * 60;
11041 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
11042
11043 //
11044 // minimum amount of work that could possibly be required nTime after
11045 // minimum work required was nBase
11046 //
11047 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
11048 {
11049 // Testnet has min-difficulty blocks
11050 // after nTargetSpacing*2 time between blocks:
11051 if (fTestNet && nTime > nTargetSpacing*2)
11052 return bnProofOfWorkLimit.GetCompact();
11053
11054 CBigNum bnResult;
11055 bnResult.SetCompact(nBase);
11056 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
11057 {
11058 // Maximum 400% adjustment...
11059 bnResult *= 4;
11060 // ... in best-case exactly 4-times-normal target time
11061 nTime -= nTargetTimespan*4;
11062 }
11063 if (bnResult > bnProofOfWorkLimit)
11064 bnResult = bnProofOfWorkLimit;
11065 return bnResult.GetCompact();
11066 }
11067
11068 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
11069 {
11070 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
11071
11072 // Genesis block
11073 if (pindexLast == NULL)
11074 return nProofOfWorkLimit;
11075
11076 // Only change once per interval
11077 if ((pindexLast->nHeight+1) % nInterval != 0)
11078 {
11079 // Special rules for testnet after 15 Feb 2012:
11080 if (fTestNet && pblock->nTime > 1329264000)
11081 {
11082 // If the new block's timestamp is more than 2* 10 minutes
11083 // then allow mining of a min-difficulty block.
11084 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
11085 return nProofOfWorkLimit;
11086 else
11087 {
11088 // Return the last non-special-min-difficulty-rules-block
11089 const CBlockIndex* pindex = pindexLast;
11090 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
11091 pindex = pindex->pprev;
11092 return pindex->nBits;
11093 }
11094 }
11095
11096 return pindexLast->nBits;
11097 }
11098
11099 // Go back by what we want to be 14 days worth of blocks
11100 const CBlockIndex* pindexFirst = pindexLast;
11101 for (int i = 0; pindexFirst && i < nInterval-1; i++)
11102 pindexFirst = pindexFirst->pprev;
11103 assert(pindexFirst);
11104
11105 // Limit adjustment step
11106 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
11107 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
11108 if (nActualTimespan < nTargetTimespan/4)
11109 nActualTimespan = nTargetTimespan/4;
11110 if (nActualTimespan > nTargetTimespan*4)
11111 nActualTimespan = nTargetTimespan*4;
11112
11113 // Retarget
11114 CBigNum bnNew;
11115 bnNew.SetCompact(pindexLast->nBits);
11116 bnNew *= nActualTimespan;
11117 bnNew /= nTargetTimespan;
11118
11119 if (bnNew > bnProofOfWorkLimit)
11120 bnNew = bnProofOfWorkLimit;
11121
11122 /// debug print
11123 printf("GetNextWorkRequired RETARGET\n");
11124 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
11125 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
11126 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
11127
11128 return bnNew.GetCompact();
11129 }
11130
11131 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
11132 {
11133 CBigNum bnTarget;
11134 bnTarget.SetCompact(nBits);
11135
11136 // Check range
11137 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
11138 return error("CheckProofOfWork() : nBits below minimum work");
11139
11140 // Check proof of work matches claimed amount
11141 if (hash > bnTarget.getuint256())
11142 return error("CheckProofOfWork() : hash doesn't match nBits");
11143
11144 return true;
11145 }
11146
11147 // Return maximum amount of blocks that other nodes claim to have
11148 int GetNumBlocksOfPeers()
11149 {
11150 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
11151 }
11152
11153 bool IsInitialBlockDownload()
11154 {
11155 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
11156 return true;
11157 static int64 nLastUpdate;
11158 static CBlockIndex* pindexLastBest;
11159 if (pindexBest != pindexLastBest)
11160 {
11161 pindexLastBest = pindexBest;
11162 nLastUpdate = GetTime();
11163 }
11164 return (GetTime() - nLastUpdate < 10 &&
11165 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
11166 }
11167
11168 void static InvalidChainFound(CBlockIndex* pindexNew)
11169 {
11170 if (pindexNew->bnChainWork > bnBestInvalidWork)
11171 {
11172 bnBestInvalidWork = pindexNew->bnChainWork;
11173 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
11174 MainFrameRepaint();
11175 }
11176 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());
11177 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
11178 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
11179 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
11180 }
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192 bool CTransaction::DisconnectInputs(CTxDB& txdb)
11193 {
11194 // Relinquish previous transactions' spent pointers
11195 if (!IsCoinBase())
11196 {
11197 BOOST_FOREACH(const CTxIn& txin, vin)
11198 {
11199 COutPoint prevout = txin.prevout;
11200
11201 // Get prev txindex from disk
11202 CTxIndex txindex;
11203 if (!txdb.ReadTxIndex(prevout.hash, txindex))
11204 return error("DisconnectInputs() : ReadTxIndex failed");
11205
11206 if (prevout.n >= txindex.vSpent.size())
11207 return error("DisconnectInputs() : prevout.n out of range");
11208
11209 // Mark outpoint as not spent
11210 txindex.vSpent[prevout.n].SetNull();
11211
11212 // Write back
11213 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
11214 return error("DisconnectInputs() : UpdateTxIndex failed");
11215 }
11216 }
11217
11218 // Remove transaction from index
11219 // This can fail if a duplicate of this transaction was in a chain that got
11220 // reorganized away. This is only possible if this transaction was completely
11221 // spent, so erasing it would be a no-op anway.
11222 txdb.EraseTxIndex(*this);
11223
11224 return true;
11225 }
11226
11227
11228 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
11229 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
11230 bool& fInvalid)
11231 {
11232 // FetchInputs can return false either because we just haven't seen some inputs
11233 // (in which case the transaction should be stored as an orphan)
11234 // or because the transaction is malformed (in which case the transaction should
11235 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
11236 fInvalid = false;
11237
11238 // Take over previous transactions' spent pointers
11239 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
11240 // fMiner is true when called from the internal bitcoin miner
11241 // ... both are false when called from CTransaction::AcceptToMemoryPool
11242 if (!IsCoinBase())
11243 {
11244 int64 nValueIn = 0;
11245 for (int i = 0; i < vin.size(); i++)
11246 {
11247 COutPoint prevout = vin[i].prevout;
11248
11249 // Read txindex
11250 CTxIndex txindex;
11251 bool fFound = true;
11252 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
11253 {
11254 // Get txindex from current proposed changes
11255 txindex = mapTestPool[prevout.hash];
11256 }
11257 else
11258 {
11259 // Read txindex from txdb
11260 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
11261 }
11262 if (!fFound && (fBlock || fMiner))
11263 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());
11264
11265 // Read txPrev
11266 CTransaction txPrev;
11267 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
11268 {
11269 // Get prev tx from single transactions in memory
11270 CRITICAL_BLOCK(cs_mapTransactions)
11271 {
11272 if (!mapTransactions.count(prevout.hash))
11273 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
11274 txPrev = mapTransactions[prevout.hash];
11275 }
11276 if (!fFound)
11277 txindex.vSpent.resize(txPrev.vout.size());
11278 }
11279 else
11280 {
11281 // Get prev tx from disk
11282 if (!txPrev.ReadFromDisk(txindex.pos))
11283 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
11284 }
11285
11286 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
11287 {
11288 // Revisit this if/when transaction replacement is implemented and allows
11289 // adding inputs:
11290 fInvalid = true;
11291 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()));
11292 }
11293
11294 // If prev is coinbase, check that it's matured
11295 if (txPrev.IsCoinBase())
11296 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
11297 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
11298 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
11299
11300 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
11301 // before the last blockchain checkpoint. This is safe because block merkle hashes are
11302 // still computed and checked, and any change will be caught at the next checkpoint.
11303 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
11304 // Verify signature
11305 if (!VerifySignature(txPrev, *this, i))
11306 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
11307
11308 // Check for conflicts (double-spend)
11309 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
11310 // for an attacker to attempt to split the network.
11311 if (!txindex.vSpent[prevout.n].IsNull())
11312 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());
11313
11314 // Check for negative or overflow input values
11315 nValueIn += txPrev.vout[prevout.n].nValue;
11316 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
11317 return DoS(100, error("ConnectInputs() : txin values out of range"));
11318
11319 // Mark outpoints as spent
11320 txindex.vSpent[prevout.n] = posThisTx;
11321
11322 // Write back
11323 if (fBlock || fMiner)
11324 {
11325 mapTestPool[prevout.hash] = txindex;
11326 }
11327 }
11328
11329 if (nValueIn < GetValueOut())
11330 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
11331
11332 // Tally transaction fees
11333 int64 nTxFee = nValueIn - GetValueOut();
11334 if (nTxFee < 0)
11335 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
11336 if (nTxFee < nMinFee)
11337 return false;
11338 nFees += nTxFee;
11339 if (!MoneyRange(nFees))
11340 return DoS(100, error("ConnectInputs() : nFees out of range"));
11341 }
11342
11343 if (fBlock)
11344 {
11345 // Add transaction to changes
11346 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
11347 }
11348 else if (fMiner)
11349 {
11350 // Add transaction to test pool
11351 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
11352 }
11353
11354 return true;
11355 }
11356
11357
11358 bool CTransaction::ClientConnectInputs()
11359 {
11360 if (IsCoinBase())
11361 return false;
11362
11363 // Take over previous transactions' spent pointers
11364 CRITICAL_BLOCK(cs_mapTransactions)
11365 {
11366 int64 nValueIn = 0;
11367 for (int i = 0; i < vin.size(); i++)
11368 {
11369 // Get prev tx from single transactions in memory
11370 COutPoint prevout = vin[i].prevout;
11371 if (!mapTransactions.count(prevout.hash))
11372 return false;
11373 CTransaction& txPrev = mapTransactions[prevout.hash];
11374
11375 if (prevout.n >= txPrev.vout.size())
11376 return false;
11377
11378 // Verify signature
11379 if (!VerifySignature(txPrev, *this, i))
11380 return error("ConnectInputs() : VerifySignature failed");
11381
11382 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
11383 ///// this has to go away now that posNext is gone
11384 // // Check for conflicts
11385 // if (!txPrev.vout[prevout.n].posNext.IsNull())
11386 // return error("ConnectInputs() : prev tx already used");
11387 //
11388 // // Flag outpoints as used
11389 // txPrev.vout[prevout.n].posNext = posThisTx;
11390
11391 nValueIn += txPrev.vout[prevout.n].nValue;
11392
11393 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
11394 return error("ClientConnectInputs() : txin values out of range");
11395 }
11396 if (GetValueOut() > nValueIn)
11397 return false;
11398 }
11399
11400 return true;
11401 }
11402
11403
11404
11405
11406 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
11407 {
11408 // Disconnect in reverse order
11409 for (int i = vtx.size()-1; i >= 0; i--)
11410 if (!vtx[i].DisconnectInputs(txdb))
11411 return false;
11412
11413 // Update block index on disk without changing it in memory.
11414 // The memory index structure will be changed after the db commits.
11415 if (pindex->pprev)
11416 {
11417 CDiskBlockIndex blockindexPrev(pindex->pprev);
11418 blockindexPrev.hashNext = 0;
11419 if (!txdb.WriteBlockIndex(blockindexPrev))
11420 return error("DisconnectBlock() : WriteBlockIndex failed");
11421 }
11422
11423 return true;
11424 }
11425
11426 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
11427 {
11428 // Check it again in case a previous version let a bad block in
11429 if (!CheckBlock())
11430 return false;
11431
11432 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
11433 // unless those are already completely spent.
11434 // If such overwrites are allowed, coinbases and transactions depending upon those
11435 // can be duplicated to remove the ability to spend the first instance -- even after
11436 // being sent to another address.
11437 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
11438 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
11439 // already refuses previously-known transaction id's entirely.
11440 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
11441 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
11442 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
11443 BOOST_FOREACH(CTransaction& tx, vtx)
11444 {
11445 CTxIndex txindexOld;
11446 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
11447 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
11448 if (pos.IsNull())
11449 return false;
11450 }
11451
11452 //// issue here: it doesn't know the version
11453 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
11454
11455 map<uint256, CTxIndex> mapQueuedChanges;
11456 int64 nFees = 0;
11457 BOOST_FOREACH(CTransaction& tx, vtx)
11458 {
11459 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
11460 nTxPos += ::GetSerializeSize(tx, SER_DISK);
11461
11462 bool fInvalid;
11463 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, 0, fInvalid))
11464 return false;
11465 }
11466 // Write queued txindex changes
11467 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
11468 {
11469 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
11470 return error("ConnectBlock() : UpdateTxIndex failed");
11471 }
11472
11473 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
11474 return false;
11475
11476 // Update block index on disk without changing it in memory.
11477 // The memory index structure will be changed after the db commits.
11478 if (pindex->pprev)
11479 {
11480 CDiskBlockIndex blockindexPrev(pindex->pprev);
11481 blockindexPrev.hashNext = pindex->GetBlockHash();
11482 if (!txdb.WriteBlockIndex(blockindexPrev))
11483 return error("ConnectBlock() : WriteBlockIndex failed");
11484 }
11485
11486 // Watch for transactions paying to me
11487 BOOST_FOREACH(CTransaction& tx, vtx)
11488 SyncWithWallets(tx, this, true);
11489
11490 return true;
11491 }
11492
11493 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
11494 {
11495 printf("REORGANIZE\n");
11496
11497 // Find the fork
11498 CBlockIndex* pfork = pindexBest;
11499 CBlockIndex* plonger = pindexNew;
11500 while (pfork != plonger)
11501 {
11502 while (plonger->nHeight > pfork->nHeight)
11503 if (!(plonger = plonger->pprev))
11504 return error("Reorganize() : plonger->pprev is null");
11505 if (pfork == plonger)
11506 break;
11507 if (!(pfork = pfork->pprev))
11508 return error("Reorganize() : pfork->pprev is null");
11509 }
11510
11511 // List of what to disconnect
11512 vector<CBlockIndex*> vDisconnect;
11513 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
11514 vDisconnect.push_back(pindex);
11515
11516 // List of what to connect
11517 vector<CBlockIndex*> vConnect;
11518 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
11519 vConnect.push_back(pindex);
11520 reverse(vConnect.begin(), vConnect.end());
11521
11522 // Disconnect shorter branch
11523 vector<CTransaction> vResurrect;
11524 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
11525 {
11526 CBlock block;
11527 if (!block.ReadFromDisk(pindex))
11528 return error("Reorganize() : ReadFromDisk for disconnect failed");
11529 if (!block.DisconnectBlock(txdb, pindex))
11530 return error("Reorganize() : DisconnectBlock failed");
11531
11532 // Queue memory transactions to resurrect
11533 BOOST_FOREACH(const CTransaction& tx, block.vtx)
11534 if (!tx.IsCoinBase())
11535 vResurrect.push_back(tx);
11536 }
11537
11538 // Connect longer branch
11539 vector<CTransaction> vDelete;
11540 for (int i = 0; i < vConnect.size(); i++)
11541 {
11542 CBlockIndex* pindex = vConnect[i];
11543 CBlock block;
11544 if (!block.ReadFromDisk(pindex))
11545 return error("Reorganize() : ReadFromDisk for connect failed");
11546 if (!block.ConnectBlock(txdb, pindex))
11547 {
11548 // Invalid block
11549 txdb.TxnAbort();
11550 return error("Reorganize() : ConnectBlock failed");
11551 }
11552
11553 // Queue memory transactions to delete
11554 BOOST_FOREACH(const CTransaction& tx, block.vtx)
11555 vDelete.push_back(tx);
11556 }
11557 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
11558 return error("Reorganize() : WriteHashBestChain failed");
11559
11560 // Make sure it's successfully written to disk before changing memory structure
11561 if (!txdb.TxnCommit())
11562 return error("Reorganize() : TxnCommit failed");
11563
11564 // Disconnect shorter branch
11565 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
11566 if (pindex->pprev)
11567 pindex->pprev->pnext = NULL;
11568
11569 // Connect longer branch
11570 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
11571 if (pindex->pprev)
11572 pindex->pprev->pnext = pindex;
11573
11574 // Resurrect memory transactions that were in the disconnected branch
11575 BOOST_FOREACH(CTransaction& tx, vResurrect)
11576 tx.AcceptToMemoryPool(txdb, false);
11577
11578 // Delete redundant memory transactions that are in the connected branch
11579 BOOST_FOREACH(CTransaction& tx, vDelete)
11580 tx.RemoveFromMemoryPool();
11581
11582 return true;
11583 }
11584
11585
11586 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
11587 {
11588 uint256 hash = GetHash();
11589
11590 txdb.TxnBegin();
11591 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
11592 {
11593 txdb.WriteHashBestChain(hash);
11594 if (!txdb.TxnCommit())
11595 return error("SetBestChain() : TxnCommit failed");
11596 pindexGenesisBlock = pindexNew;
11597 }
11598 else if (hashPrevBlock == hashBestChain)
11599 {
11600 // Adding to current best branch
11601 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
11602 {
11603 txdb.TxnAbort();
11604 InvalidChainFound(pindexNew);
11605 return error("SetBestChain() : ConnectBlock failed");
11606 }
11607 if (!txdb.TxnCommit())
11608 return error("SetBestChain() : TxnCommit failed");
11609
11610 // Add to current best branch
11611 pindexNew->pprev->pnext = pindexNew;
11612
11613 // Delete redundant memory transactions
11614 BOOST_FOREACH(CTransaction& tx, vtx)
11615 tx.RemoveFromMemoryPool();
11616 }
11617 else
11618 {
11619 // New best branch
11620 if (!Reorganize(txdb, pindexNew))
11621 {
11622 txdb.TxnAbort();
11623 InvalidChainFound(pindexNew);
11624 return error("SetBestChain() : Reorganize failed");
11625 }
11626 }
11627
11628 // Update best block in wallet (so we can detect restored wallets)
11629 if (!IsInitialBlockDownload())
11630 {
11631 const CBlockLocator locator(pindexNew);
11632 ::SetBestChain(locator);
11633 }
11634
11635 // New best block
11636 hashBestChain = hash;
11637 pindexBest = pindexNew;
11638 nBestHeight = pindexBest->nHeight;
11639 bnBestChainWork = pindexNew->bnChainWork;
11640 nTimeBestReceived = GetTime();
11641 nTransactionsUpdated++;
11642 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
11643
11644 return true;
11645 }
11646
11647
11648 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
11649 {
11650 // Check for duplicate
11651 uint256 hash = GetHash();
11652 if (mapBlockIndex.count(hash))
11653 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
11654
11655 // Construct new block index object
11656 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
11657 if (!pindexNew)
11658 return error("AddToBlockIndex() : new CBlockIndex failed");
11659 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
11660 pindexNew->phashBlock = &((*mi).first);
11661 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
11662 if (miPrev != mapBlockIndex.end())
11663 {
11664 pindexNew->pprev = (*miPrev).second;
11665 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
11666 }
11667 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
11668
11669 CTxDB txdb;
11670 txdb.TxnBegin();
11671 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
11672 if (!txdb.TxnCommit())
11673 return false;
11674
11675 // New best
11676 if (pindexNew->bnChainWork > bnBestChainWork)
11677 if (!SetBestChain(txdb, pindexNew))
11678 return false;
11679
11680 txdb.Close();
11681
11682 if (pindexNew == pindexBest)
11683 {
11684 // Notify UI to display prev block's coinbase if it was ours
11685 static uint256 hashPrevBestCoinBase;
11686 UpdatedTransaction(hashPrevBestCoinBase);
11687 hashPrevBestCoinBase = vtx[0].GetHash();
11688 }
11689
11690 MainFrameRepaint();
11691 return true;
11692 }
11693
11694
11695
11696
11697 bool CBlock::CheckBlock() const
11698 {
11699 // These are checks that are independent of context
11700 // that can be verified before saving an orphan block.
11701
11702 // Size limits
11703 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
11704 return DoS(100, error("CheckBlock() : size limits failed"));
11705
11706 // Check proof of work matches claimed amount
11707 if (!CheckProofOfWork(GetHash(), nBits))
11708 return DoS(50, error("CheckBlock() : proof of work failed"));
11709
11710 // Check timestamp
11711 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
11712 return error("CheckBlock() : block timestamp too far in the future");
11713
11714 // First transaction must be coinbase, the rest must not be
11715 if (vtx.empty() || !vtx[0].IsCoinBase())
11716 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
11717 for (int i = 1; i < vtx.size(); i++)
11718 if (vtx[i].IsCoinBase())
11719 return DoS(100, error("CheckBlock() : more than one coinbase"));
11720
11721 // Check transactions
11722 BOOST_FOREACH(const CTransaction& tx, vtx)
11723 if (!tx.CheckTransaction())
11724 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
11725
11726 // Check that it's not full of nonstandard transactions
11727 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
11728 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
11729
11730 // Check merkleroot
11731 if (hashMerkleRoot != BuildMerkleTree())
11732 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
11733
11734 return true;
11735 }
11736
11737 bool CBlock::AcceptBlock()
11738 {
11739 // Check for duplicate
11740 uint256 hash = GetHash();
11741 if (mapBlockIndex.count(hash))
11742 return error("AcceptBlock() : block already in mapBlockIndex");
11743
11744 // Get prev block index
11745 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
11746 if (mi == mapBlockIndex.end())
11747 return DoS(10, error("AcceptBlock() : prev block not found"));
11748 CBlockIndex* pindexPrev = (*mi).second;
11749 int nHeight = pindexPrev->nHeight+1;
11750
11751 // Check proof of work
11752 if (nBits != GetNextWorkRequired(pindexPrev, this))
11753 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
11754
11755 // Check timestamp against prev
11756 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
11757 return error("AcceptBlock() : block's timestamp is too early");
11758
11759 // Check that all transactions are finalized
11760 BOOST_FOREACH(const CTransaction& tx, vtx)
11761 if (!tx.IsFinal(nHeight, GetBlockTime()))
11762 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
11763
11764 // Check that the block chain matches the known block chain up to a checkpoint
11765 if (!Checkpoints::CheckBlock(nHeight, hash))
11766 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
11767
11768 // Write block to history file
11769 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
11770 return error("AcceptBlock() : out of disk space");
11771 unsigned int nFile = -1;
11772 unsigned int nBlockPos = 0;
11773 if (!WriteToDisk(nFile, nBlockPos))
11774 return error("AcceptBlock() : WriteToDisk failed");
11775 if (!AddToBlockIndex(nFile, nBlockPos))
11776 return error("AcceptBlock() : AddToBlockIndex failed");
11777
11778 // Relay inventory, but don't relay old inventory during initial block download
11779 if (hashBestChain == hash)
11780 CRITICAL_BLOCK(cs_vNodes)
11781 BOOST_FOREACH(CNode* pnode, vNodes)
11782 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
11783 pnode->PushInventory(CInv(MSG_BLOCK, hash));
11784
11785 return true;
11786 }
11787
11788 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
11789 {
11790 // Check for duplicate
11791 uint256 hash = pblock->GetHash();
11792 if (mapBlockIndex.count(hash))
11793 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
11794 if (mapOrphanBlocks.count(hash))
11795 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
11796
11797 // Preliminary checks
11798 if (!pblock->CheckBlock())
11799 return error("ProcessBlock() : CheckBlock FAILED");
11800
11801 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
11802 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
11803 {
11804 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
11805 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
11806 if (deltaTime < 0)
11807 {
11808 if (pfrom)
11809 pfrom->Misbehaving(100);
11810 return error("ProcessBlock() : block with timestamp before last checkpoint");
11811 }
11812 CBigNum bnNewBlock;
11813 bnNewBlock.SetCompact(pblock->nBits);
11814 CBigNum bnRequired;
11815 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
11816 if (bnNewBlock > bnRequired)
11817 {
11818 if (pfrom)
11819 pfrom->Misbehaving(100);
11820 return error("ProcessBlock() : block with too little proof-of-work");
11821 }
11822 }
11823
11824
11825 // If don't already have its previous block, shunt it off to holding area until we get it
11826 if (!mapBlockIndex.count(pblock->hashPrevBlock))
11827 {
11828 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
11829 CBlock* pblock2 = new CBlock(*pblock);
11830 mapOrphanBlocks.insert(make_pair(hash, pblock2));
11831 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
11832
11833 // Ask this guy to fill in what we're missing
11834 if (pfrom)
11835 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
11836 return true;
11837 }
11838
11839 // Store to disk
11840 if (!pblock->AcceptBlock())
11841 return error("ProcessBlock() : AcceptBlock FAILED");
11842
11843 // Recursively process any orphan blocks that depended on this one
11844 vector<uint256> vWorkQueue;
11845 vWorkQueue.push_back(hash);
11846 for (int i = 0; i < vWorkQueue.size(); i++)
11847 {
11848 uint256 hashPrev = vWorkQueue[i];
11849 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
11850 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
11851 ++mi)
11852 {
11853 CBlock* pblockOrphan = (*mi).second;
11854 if (pblockOrphan->AcceptBlock())
11855 vWorkQueue.push_back(pblockOrphan->GetHash());
11856 mapOrphanBlocks.erase(pblockOrphan->GetHash());
11857 delete pblockOrphan;
11858 }
11859 mapOrphanBlocksByPrev.erase(hashPrev);
11860 }
11861
11862 printf("ProcessBlock: ACCEPTED\n");
11863 return true;
11864 }
11865
11866
11867
11868
11869
11870
11871
11872
11873 bool CheckDiskSpace(uint64 nAdditionalBytes)
11874 {
11875 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
11876
11877 // Check for 15MB because database could create another 10MB log file at any time
11878 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
11879 {
11880 fShutdown = true;
11881 string strMessage = _("Warning: Disk space is low ");
11882 strMiscWarning = strMessage;
11883 printf("*** %s\n", strMessage.c_str());
11884 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
11885 CreateThread(Shutdown, NULL);
11886 return false;
11887 }
11888 return true;
11889 }
11890
11891 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
11892 {
11893 if (nFile == -1)
11894 return NULL;
11895 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
11896 if (!file)
11897 return NULL;
11898 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
11899 {
11900 if (fseek(file, nBlockPos, SEEK_SET) != 0)
11901 {
11902 fclose(file);
11903 return NULL;
11904 }
11905 }
11906 return file;
11907 }
11908
11909 static unsigned int nCurrentBlockFile = 1;
11910
11911 FILE* AppendBlockFile(unsigned int& nFileRet)
11912 {
11913 nFileRet = 0;
11914 loop
11915 {
11916 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
11917 if (!file)
11918 return NULL;
11919 if (fseek(file, 0, SEEK_END) != 0)
11920 return NULL;
11921 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
11922 if (ftell(file) < 0x7F000000 - MAX_SIZE)
11923 {
11924 nFileRet = nCurrentBlockFile;
11925 return file;
11926 }
11927 fclose(file);
11928 nCurrentBlockFile++;
11929 }
11930 }
11931
11932 bool LoadBlockIndex(bool fAllowNew)
11933 {
11934 if (fTestNet)
11935 {
11936 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
11937 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
11938 pchMessageStart[0] = 0xfa;
11939 pchMessageStart[1] = 0xbf;
11940 pchMessageStart[2] = 0xb5;
11941 pchMessageStart[3] = 0xda;
11942 }
11943
11944 //
11945 // Load block index
11946 //
11947 CTxDB txdb("cr");
11948 if (!txdb.LoadBlockIndex())
11949 return false;
11950 txdb.Close();
11951
11952 //
11953 // Init with genesis block
11954 //
11955 if (mapBlockIndex.empty())
11956 {
11957 if (!fAllowNew)
11958 return false;
11959
11960 // Genesis Block:
11961 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
11962 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
11963 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
11964 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
11965 // vMerkleTree: 4a5e1e
11966
11967 // Genesis block
11968 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
11969 CTransaction txNew;
11970 txNew.vin.resize(1);
11971 txNew.vout.resize(1);
11972 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
11973 txNew.vout[0].nValue = 50 * COIN;
11974 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
11975 CBlock block;
11976 block.vtx.push_back(txNew);
11977 block.hashPrevBlock = 0;
11978 block.hashMerkleRoot = block.BuildMerkleTree();
11979 block.nVersion = 1;
11980 block.nTime = 1231006505;
11981 block.nBits = 0x1d00ffff;
11982 block.nNonce = 2083236893;
11983
11984 if (fTestNet)
11985 {
11986 block.nTime = 1296688602;
11987 block.nBits = 0x1d07fff8;
11988 block.nNonce = 384568319;
11989 }
11990
11991 //// debug print
11992 printf("%s\n", block.GetHash().ToString().c_str());
11993 printf("%s\n", hashGenesisBlock.ToString().c_str());
11994 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
11995 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
11996 block.print();
11997 assert(block.GetHash() == hashGenesisBlock);
11998
11999 // Start new block file
12000 unsigned int nFile;
12001 unsigned int nBlockPos;
12002 if (!block.WriteToDisk(nFile, nBlockPos))
12003 return error("LoadBlockIndex() : writing genesis block to disk failed");
12004 if (!block.AddToBlockIndex(nFile, nBlockPos))
12005 return error("LoadBlockIndex() : genesis block not accepted");
12006 }
12007
12008 return true;
12009 }
12010
12011
12012
12013 void PrintBlockTree()
12014 {
12015 // precompute tree structure
12016 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
12017 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
12018 {
12019 CBlockIndex* pindex = (*mi).second;
12020 mapNext[pindex->pprev].push_back(pindex);
12021 // test
12022 //while (rand() % 3 == 0)
12023 // mapNext[pindex->pprev].push_back(pindex);
12024 }
12025
12026 vector<pair<int, CBlockIndex*> > vStack;
12027 vStack.push_back(make_pair(0, pindexGenesisBlock));
12028
12029 int nPrevCol = 0;
12030 while (!vStack.empty())
12031 {
12032 int nCol = vStack.back().first;
12033 CBlockIndex* pindex = vStack.back().second;
12034 vStack.pop_back();
12035
12036 // print split or gap
12037 if (nCol > nPrevCol)
12038 {
12039 for (int i = 0; i < nCol-1; i++)
12040 printf("| ");
12041 printf("|\\\n");
12042 }
12043 else if (nCol < nPrevCol)
12044 {
12045 for (int i = 0; i < nCol; i++)
12046 printf("| ");
12047 printf("|\n");
12048 }
12049 nPrevCol = nCol;
12050
12051 // print columns
12052 for (int i = 0; i < nCol; i++)
12053 printf("| ");
12054
12055 // print item
12056 CBlock block;
12057 block.ReadFromDisk(pindex);
12058 printf("%d (%u,%u) %s %s tx %d",
12059 pindex->nHeight,
12060 pindex->nFile,
12061 pindex->nBlockPos,
12062 block.GetHash().ToString().substr(0,20).c_str(),
12063 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
12064 block.vtx.size());
12065
12066 PrintWallets(block);
12067
12068 // put the main timechain first
12069 vector<CBlockIndex*>& vNext = mapNext[pindex];
12070 for (int i = 0; i < vNext.size(); i++)
12071 {
12072 if (vNext[i]->pnext)
12073 {
12074 swap(vNext[0], vNext[i]);
12075 break;
12076 }
12077 }
12078
12079 // iterate children
12080 for (int i = 0; i < vNext.size(); i++)
12081 vStack.push_back(make_pair(nCol+i, vNext[i]));
12082 }
12083 }
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094 //////////////////////////////////////////////////////////////////////////////
12095 //
12096 // CAlert
12097 //
12098
12099 map<uint256, CAlert> mapAlerts;
12100 CCriticalSection cs_mapAlerts;
12101
12102 string GetWarnings(string strFor)
12103 {
12104 int nPriority = 0;
12105 string strStatusBar;
12106 string strRPC;
12107 if (GetBoolArg("-testsafemode"))
12108 strRPC = "test";
12109
12110 // Misc warnings like out of disk space and clock is wrong
12111 if (strMiscWarning != "")
12112 {
12113 nPriority = 1000;
12114 strStatusBar = strMiscWarning;
12115 }
12116
12117 // Longer invalid proof-of-work chain
12118 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
12119 {
12120 nPriority = 2000;
12121 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
12122 }
12123
12124 // Alerts
12125 CRITICAL_BLOCK(cs_mapAlerts)
12126 {
12127 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
12128 {
12129 const CAlert& alert = item.second;
12130 if (alert.AppliesToMe() && alert.nPriority > nPriority)
12131 {
12132 nPriority = alert.nPriority;
12133 strStatusBar = alert.strStatusBar;
12134 }
12135 }
12136 }
12137
12138 if (strFor == "statusbar")
12139 return strStatusBar;
12140 else if (strFor == "rpc")
12141 return strRPC;
12142 assert(!"GetWarnings() : invalid parameter");
12143 return "error";
12144 }
12145
12146 bool CAlert::ProcessAlert()
12147 {
12148 if (!CheckSignature())
12149 return false;
12150 if (!IsInEffect())
12151 return false;
12152
12153 CRITICAL_BLOCK(cs_mapAlerts)
12154 {
12155 // Cancel previous alerts
12156 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
12157 {
12158 const CAlert& alert = (*mi).second;
12159 if (Cancels(alert))
12160 {
12161 printf("cancelling alert %d\n", alert.nID);
12162 mapAlerts.erase(mi++);
12163 }
12164 else if (!alert.IsInEffect())
12165 {
12166 printf("expiring alert %d\n", alert.nID);
12167 mapAlerts.erase(mi++);
12168 }
12169 else
12170 mi++;
12171 }
12172
12173 // Check if this alert has been cancelled
12174 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
12175 {
12176 const CAlert& alert = item.second;
12177 if (alert.Cancels(*this))
12178 {
12179 printf("alert already cancelled by %d\n", alert.nID);
12180 return false;
12181 }
12182 }
12183
12184 // Add to mapAlerts
12185 mapAlerts.insert(make_pair(GetHash(), *this));
12186 }
12187
12188 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
12189 MainFrameRepaint();
12190 return true;
12191 }
12192
12193
12194
12195
12196
12197
12198
12199
12200 //////////////////////////////////////////////////////////////////////////////
12201 //
12202 // Messages
12203 //
12204
12205
12206 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
12207 {
12208 switch (inv.type)
12209 {
12210 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
12211 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
12212 }
12213 // Don't know what it is, just say we already got one
12214 return true;
12215 }
12216
12217
12218
12219
12220 // The message start string is designed to be unlikely to occur in normal data.
12221 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
12222 // a large 4-byte int at any alignment.
12223 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
12224
12225
12226 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
12227 {
12228 static map<unsigned int, vector<unsigned char> > mapReuseKey;
12229 RandAddSeedPerfmon();
12230 if (fDebug) {
12231 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
12232 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
12233 }
12234 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
12235 {
12236 printf("dropmessagestest DROPPING RECV MESSAGE\n");
12237 return true;
12238 }
12239
12240
12241
12242
12243
12244 if (strCommand == "version")
12245 {
12246 // Each connection can only send one version message
12247 if (pfrom->nVersion != 0)
12248 {
12249 pfrom->Misbehaving(1);
12250 return false;
12251 }
12252
12253 int64 nTime;
12254 CAddress addrMe;
12255 CAddress addrFrom;
12256 uint64 nNonce = 1;
12257 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
12258 if (pfrom->nVersion == 10300)
12259 pfrom->nVersion = 300;
12260 if (pfrom->nVersion >= 106 && !vRecv.empty())
12261 vRecv >> addrFrom >> nNonce;
12262 if (pfrom->nVersion >= 106 && !vRecv.empty())
12263 vRecv >> pfrom->strSubVer;
12264 if (pfrom->nVersion >= 209 && !vRecv.empty())
12265 vRecv >> pfrom->nStartingHeight;
12266
12267 if (pfrom->nVersion == 0)
12268 return false;
12269
12270 // Disconnect if we connected to ourself
12271 if (nNonce == nLocalHostNonce && nNonce > 1)
12272 {
12273 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
12274 pfrom->fDisconnect = true;
12275 return true;
12276 }
12277
12278 // Be shy and don't send version until we hear
12279 if (pfrom->fInbound)
12280 pfrom->PushVersion();
12281
12282 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
12283
12284 AddTimeData(pfrom->addr.ip, nTime);
12285
12286 // Change version
12287 if (pfrom->nVersion >= 209)
12288 pfrom->PushMessage("verack");
12289 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
12290 if (pfrom->nVersion < 209)
12291 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
12292
12293 if (!pfrom->fInbound)
12294 {
12295 // Advertise our address
12296 if (addrLocalHost.IsRoutable() && !fUseProxy)
12297 {
12298 CAddress addr(addrLocalHost);
12299 addr.nTime = GetAdjustedTime();
12300 pfrom->PushAddress(addr);
12301 }
12302
12303 // Get recent addresses
12304 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
12305 {
12306 pfrom->PushMessage("getaddr");
12307 pfrom->fGetAddr = true;
12308 }
12309 }
12310
12311 // Ask the first connected node for block updates
12312 static int nAskedForBlocks;
12313 if (!pfrom->fClient &&
12314 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
12315 (nAskedForBlocks < 1 || vNodes.size() <= 1))
12316 {
12317 nAskedForBlocks++;
12318 pfrom->PushGetBlocks(pindexBest, uint256(0));
12319 }
12320
12321 // Relay alerts
12322 CRITICAL_BLOCK(cs_mapAlerts)
12323 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
12324 item.second.RelayTo(pfrom);
12325
12326 pfrom->fSuccessfullyConnected = true;
12327
12328 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
12329
12330 cPeerBlockCounts.input(pfrom->nStartingHeight);
12331 }
12332
12333
12334 else if (pfrom->nVersion == 0)
12335 {
12336 // Must have a version message before anything else
12337 pfrom->Misbehaving(1);
12338 return false;
12339 }
12340
12341
12342 else if (strCommand == "verack")
12343 {
12344 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
12345 }
12346
12347
12348 else if (strCommand == "addr")
12349 {
12350 vector<CAddress> vAddr;
12351 vRecv >> vAddr;
12352
12353 // Don't want addr from older versions unless seeding
12354 if (pfrom->nVersion < 209)
12355 return true;
12356 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
12357 return true;
12358 if (vAddr.size() > 1000)
12359 {
12360 pfrom->Misbehaving(20);
12361 return error("message addr size() = %d", vAddr.size());
12362 }
12363
12364 // Store the new addresses
12365 CAddrDB addrDB;
12366 addrDB.TxnBegin();
12367 int64 nNow = GetAdjustedTime();
12368 int64 nSince = nNow - 10 * 60;
12369 BOOST_FOREACH(CAddress& addr, vAddr)
12370 {
12371 if (fShutdown)
12372 return true;
12373 // ignore IPv6 for now, since it isn't implemented anyway
12374 if (!addr.IsIPv4())
12375 continue;
12376 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
12377 addr.nTime = nNow - 5 * 24 * 60 * 60;
12378 AddAddress(addr, 2 * 60 * 60, &addrDB);
12379 pfrom->AddAddressKnown(addr);
12380 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
12381 {
12382 // Relay to a limited number of other nodes
12383 CRITICAL_BLOCK(cs_vNodes)
12384 {
12385 // Use deterministic randomness to send to the same nodes for 24 hours
12386 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
12387 static uint256 hashSalt;
12388 if (hashSalt == 0)
12389 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
12390 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
12391 hashRand = Hash(BEGIN(hashRand), END(hashRand));
12392 multimap<uint256, CNode*> mapMix;
12393 BOOST_FOREACH(CNode* pnode, vNodes)
12394 {
12395 if (pnode->nVersion < 31402)
12396 continue;
12397 unsigned int nPointer;
12398 memcpy(&nPointer, &pnode, sizeof(nPointer));
12399 uint256 hashKey = hashRand ^ nPointer;
12400 hashKey = Hash(BEGIN(hashKey), END(hashKey));
12401 mapMix.insert(make_pair(hashKey, pnode));
12402 }
12403 int nRelayNodes = 2;
12404 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
12405 ((*mi).second)->PushAddress(addr);
12406 }
12407 }
12408 }
12409 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
12410 if (vAddr.size() < 1000)
12411 pfrom->fGetAddr = false;
12412 }
12413
12414
12415 else if (strCommand == "inv")
12416 {
12417 vector<CInv> vInv;
12418 vRecv >> vInv;
12419 if (vInv.size() > 50000)
12420 {
12421 pfrom->Misbehaving(20);
12422 return error("message inv size() = %d", vInv.size());
12423 }
12424
12425 CTxDB txdb("r");
12426 BOOST_FOREACH(const CInv& inv, vInv)
12427 {
12428 if (fShutdown)
12429 return true;
12430 pfrom->AddInventoryKnown(inv);
12431
12432 bool fAlreadyHave = AlreadyHave(txdb, inv);
12433 if (fDebug)
12434 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
12435
12436 if (!fAlreadyHave)
12437 pfrom->AskFor(inv);
12438 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
12439 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
12440
12441 // Track requests for our stuff
12442 Inventory(inv.hash);
12443 }
12444 }
12445
12446
12447 else if (strCommand == "getdata")
12448 {
12449 vector<CInv> vInv;
12450 vRecv >> vInv;
12451 if (vInv.size() > 50000)
12452 {
12453 pfrom->Misbehaving(20);
12454 return error("message getdata size() = %d", vInv.size());
12455 }
12456
12457 BOOST_FOREACH(const CInv& inv, vInv)
12458 {
12459 if (fShutdown)
12460 return true;
12461 printf("received getdata for: %s\n", inv.ToString().c_str());
12462
12463 if (inv.type == MSG_BLOCK)
12464 {
12465 // Send block from disk
12466 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
12467 if (mi != mapBlockIndex.end())
12468 {
12469 CBlock block;
12470 block.ReadFromDisk((*mi).second);
12471 pfrom->PushMessage("block", block);
12472
12473 // Trigger them to send a getblocks request for the next batch of inventory
12474 if (inv.hash == pfrom->hashContinue)
12475 {
12476 // Bypass PushInventory, this must send even if redundant,
12477 // and we want it right after the last block so they don't
12478 // wait for other stuff first.
12479 vector<CInv> vInv;
12480 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
12481 pfrom->PushMessage("inv", vInv);
12482 pfrom->hashContinue = 0;
12483 }
12484 }
12485 }
12486 else if (inv.IsKnownType())
12487 {
12488 // Send stream from relay memory
12489 CRITICAL_BLOCK(cs_mapRelay)
12490 {
12491 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
12492 if (mi != mapRelay.end())
12493 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
12494 }
12495 }
12496
12497 // Track requests for our stuff
12498 Inventory(inv.hash);
12499 }
12500 }
12501
12502
12503 else if (strCommand == "getblocks")
12504 {
12505 CBlockLocator locator;
12506 uint256 hashStop;
12507 vRecv >> locator >> hashStop;
12508
12509 // Find the last block the caller has in the main chain
12510 CBlockIndex* pindex = locator.GetBlockIndex();
12511
12512 // Send the rest of the chain
12513 if (pindex)
12514 pindex = pindex->pnext;
12515 int nLimit = 500 + locator.GetDistanceBack();
12516 unsigned int nBytes = 0;
12517 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
12518 for (; pindex; pindex = pindex->pnext)
12519 {
12520 if (pindex->GetBlockHash() == hashStop)
12521 {
12522 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
12523 break;
12524 }
12525 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
12526 CBlock block;
12527 block.ReadFromDisk(pindex, true);
12528 nBytes += block.GetSerializeSize(SER_NETWORK);
12529 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
12530 {
12531 // When this block is requested, we'll send an inv that'll make them
12532 // getblocks the next batch of inventory.
12533 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
12534 pfrom->hashContinue = pindex->GetBlockHash();
12535 break;
12536 }
12537 }
12538 }
12539
12540
12541 else if (strCommand == "getheaders")
12542 {
12543 CBlockLocator locator;
12544 uint256 hashStop;
12545 vRecv >> locator >> hashStop;
12546
12547 CBlockIndex* pindex = NULL;
12548 if (locator.IsNull())
12549 {
12550 // If locator is null, return the hashStop block
12551 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
12552 if (mi == mapBlockIndex.end())
12553 return true;
12554 pindex = (*mi).second;
12555 }
12556 else
12557 {
12558 // Find the last block the caller has in the main chain
12559 pindex = locator.GetBlockIndex();
12560 if (pindex)
12561 pindex = pindex->pnext;
12562 }
12563
12564 vector<CBlock> vHeaders;
12565 int nLimit = 2000 + locator.GetDistanceBack();
12566 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
12567 for (; pindex; pindex = pindex->pnext)
12568 {
12569 vHeaders.push_back(pindex->GetBlockHeader());
12570 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
12571 break;
12572 }
12573 pfrom->PushMessage("headers", vHeaders);
12574 }
12575
12576
12577 else if (strCommand == "tx")
12578 {
12579 vector<uint256> vWorkQueue;
12580 CDataStream vMsg(vRecv);
12581 CTransaction tx;
12582 vRecv >> tx;
12583
12584 CInv inv(MSG_TX, tx.GetHash());
12585 pfrom->AddInventoryKnown(inv);
12586
12587 bool fMissingInputs = false;
12588 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
12589 {
12590 SyncWithWallets(tx, NULL, true);
12591 RelayMessage(inv, vMsg);
12592 mapAlreadyAskedFor.erase(inv);
12593 vWorkQueue.push_back(inv.hash);
12594
12595 // Recursively process any orphan transactions that depended on this one
12596 for (int i = 0; i < vWorkQueue.size(); i++)
12597 {
12598 uint256 hashPrev = vWorkQueue[i];
12599 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
12600 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
12601 ++mi)
12602 {
12603 const CDataStream& vMsg = *((*mi).second);
12604 CTransaction tx;
12605 CDataStream(vMsg) >> tx;
12606 CInv inv(MSG_TX, tx.GetHash());
12607
12608 if (tx.AcceptToMemoryPool(true))
12609 {
12610 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
12611 SyncWithWallets(tx, NULL, true);
12612 RelayMessage(inv, vMsg);
12613 mapAlreadyAskedFor.erase(inv);
12614 vWorkQueue.push_back(inv.hash);
12615 }
12616 }
12617 }
12618
12619 BOOST_FOREACH(uint256 hash, vWorkQueue)
12620 EraseOrphanTx(hash);
12621 }
12622 else if (fMissingInputs)
12623 {
12624 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
12625 AddOrphanTx(vMsg);
12626
12627 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
12628 int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
12629 if (nEvicted > 0)
12630 printf("mapOrphan overflow, removed %d tx\n", nEvicted);
12631 }
12632 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
12633 }
12634
12635
12636 else if (strCommand == "block")
12637 {
12638 CBlock block;
12639 vRecv >> block;
12640
12641 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
12642 // block.print();
12643
12644 CInv inv(MSG_BLOCK, block.GetHash());
12645 pfrom->AddInventoryKnown(inv);
12646
12647 if (ProcessBlock(pfrom, &block))
12648 mapAlreadyAskedFor.erase(inv);
12649 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
12650 }
12651
12652
12653 else if (strCommand == "getaddr")
12654 {
12655 // Nodes rebroadcast an addr every 24 hours
12656 pfrom->vAddrToSend.clear();
12657 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
12658 CRITICAL_BLOCK(cs_mapAddresses)
12659 {
12660 unsigned int nCount = 0;
12661 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
12662 {
12663 const CAddress& addr = item.second;
12664 if (addr.nTime > nSince)
12665 nCount++;
12666 }
12667 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
12668 {
12669 const CAddress& addr = item.second;
12670 if (addr.nTime > nSince && GetRand(nCount) < 2500)
12671 pfrom->PushAddress(addr);
12672 }
12673 }
12674 }
12675
12676
12677 else if (strCommand == "checkorder")
12678 {
12679 uint256 hashReply;
12680 vRecv >> hashReply;
12681
12682 if (!GetBoolArg("-allowreceivebyip"))
12683 {
12684 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
12685 return true;
12686 }
12687
12688 CWalletTx order;
12689 vRecv >> order;
12690
12691 /// we have a chance to check the order here
12692
12693 // Keep giving the same key to the same ip until they use it
12694 if (!mapReuseKey.count(pfrom->addr.ip))
12695 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
12696
12697 // Send back approval of order and pubkey to use
12698 CScript scriptPubKey;
12699 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
12700 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
12701 }
12702
12703
12704 else if (strCommand == "reply")
12705 {
12706 uint256 hashReply;
12707 vRecv >> hashReply;
12708
12709 CRequestTracker tracker;
12710 CRITICAL_BLOCK(pfrom->cs_mapRequests)
12711 {
12712 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
12713 if (mi != pfrom->mapRequests.end())
12714 {
12715 tracker = (*mi).second;
12716 pfrom->mapRequests.erase(mi);
12717 }
12718 }
12719 if (!tracker.IsNull())
12720 tracker.fn(tracker.param1, vRecv);
12721 }
12722
12723
12724 else if (strCommand == "ping")
12725 {
12726 }
12727
12728
12729 else if (strCommand == "alert")
12730 {
12731 CAlert alert;
12732 vRecv >> alert;
12733
12734 if (alert.ProcessAlert())
12735 {
12736 // Relay
12737 pfrom->setKnown.insert(alert.GetHash());
12738 CRITICAL_BLOCK(cs_vNodes)
12739 BOOST_FOREACH(CNode* pnode, vNodes)
12740 alert.RelayTo(pnode);
12741 }
12742 }
12743
12744
12745 else
12746 {
12747 // Ignore unknown commands for extensibility
12748 }
12749
12750
12751 // Update the last seen time for this node's address
12752 if (pfrom->fNetworkNode)
12753 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
12754 AddressCurrentlyConnected(pfrom->addr);
12755
12756
12757 return true;
12758 }
12759
12760 bool ProcessMessages(CNode* pfrom)
12761 {
12762 CDataStream& vRecv = pfrom->vRecv;
12763 if (vRecv.empty())
12764 return true;
12765 //if (fDebug)
12766 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
12767
12768 //
12769 // Message format
12770 // (4) message start
12771 // (12) command
12772 // (4) size
12773 // (4) checksum
12774 // (x) data
12775 //
12776
12777 loop
12778 {
12779 // Scan for message start
12780 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
12781 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
12782 if (vRecv.end() - pstart < nHeaderSize)
12783 {
12784 if (vRecv.size() > nHeaderSize)
12785 {
12786 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
12787 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
12788 }
12789 break;
12790 }
12791 if (pstart - vRecv.begin() > 0)
12792 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
12793 vRecv.erase(vRecv.begin(), pstart);
12794
12795 // Read header
12796 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
12797 CMessageHeader hdr;
12798 vRecv >> hdr;
12799 if (!hdr.IsValid())
12800 {
12801 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
12802 continue;
12803 }
12804 string strCommand = hdr.GetCommand();
12805
12806 // Message size
12807 unsigned int nMessageSize = hdr.nMessageSize;
12808 if (nMessageSize > MAX_SIZE)
12809 {
12810 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
12811 continue;
12812 }
12813 if (nMessageSize > vRecv.size())
12814 {
12815 // Rewind and wait for rest of message
12816 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
12817 break;
12818 }
12819
12820 // Checksum
12821 if (vRecv.GetVersion() >= 209)
12822 {
12823 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
12824 unsigned int nChecksum = 0;
12825 memcpy(&nChecksum, &hash, sizeof(nChecksum));
12826 if (nChecksum != hdr.nChecksum)
12827 {
12828 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
12829 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
12830 continue;
12831 }
12832 }
12833
12834 // Copy message to its own buffer
12835 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
12836 vRecv.ignore(nMessageSize);
12837
12838 // Process message
12839 bool fRet = false;
12840 try
12841 {
12842 CRITICAL_BLOCK(cs_main)
12843 fRet = ProcessMessage(pfrom, strCommand, vMsg);
12844 if (fShutdown)
12845 return true;
12846 }
12847 catch (std::ios_base::failure& e)
12848 {
12849 if (strstr(e.what(), "end of data"))
12850 {
12851 // Allow exceptions from underlength message on vRecv
12852 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());
12853 }
12854 else if (strstr(e.what(), "size too large"))
12855 {
12856 // Allow exceptions from overlong size
12857 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
12858 }
12859 else
12860 {
12861 PrintExceptionContinue(&e, "ProcessMessage()");
12862 }
12863 }
12864 catch (std::exception& e) {
12865 PrintExceptionContinue(&e, "ProcessMessage()");
12866 } catch (...) {
12867 PrintExceptionContinue(NULL, "ProcessMessage()");
12868 }
12869
12870 if (!fRet)
12871 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
12872 }
12873
12874 vRecv.Compact();
12875 return true;
12876 }
12877
12878
12879 bool SendMessages(CNode* pto, bool fSendTrickle)
12880 {
12881 CRITICAL_BLOCK(cs_main)
12882 {
12883 // Don't send anything until we get their version message
12884 if (pto->nVersion == 0)
12885 return true;
12886
12887 // Keep-alive ping
12888 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
12889 pto->PushMessage("ping");
12890
12891 // Resend wallet transactions that haven't gotten in a block yet
12892 ResendWalletTransactions();
12893
12894 // Address refresh broadcast
12895 static int64 nLastRebroadcast;
12896 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
12897 {
12898 nLastRebroadcast = GetTime();
12899 CRITICAL_BLOCK(cs_vNodes)
12900 {
12901 BOOST_FOREACH(CNode* pnode, vNodes)
12902 {
12903 // Periodically clear setAddrKnown to allow refresh broadcasts
12904 pnode->setAddrKnown.clear();
12905
12906 // Rebroadcast our address
12907 if (addrLocalHost.IsRoutable() && !fUseProxy)
12908 {
12909 CAddress addr(addrLocalHost);
12910 addr.nTime = GetAdjustedTime();
12911 pnode->PushAddress(addr);
12912 }
12913 }
12914 }
12915 }
12916
12917 // Clear out old addresses periodically so it's not too much work at once
12918 static int64 nLastClear;
12919 if (nLastClear == 0)
12920 nLastClear = GetTime();
12921 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
12922 {
12923 nLastClear = GetTime();
12924 CRITICAL_BLOCK(cs_mapAddresses)
12925 {
12926 CAddrDB addrdb;
12927 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
12928 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
12929 mi != mapAddresses.end();)
12930 {
12931 const CAddress& addr = (*mi).second;
12932 if (addr.nTime < nSince)
12933 {
12934 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
12935 break;
12936 addrdb.EraseAddress(addr);
12937 mapAddresses.erase(mi++);
12938 }
12939 else
12940 mi++;
12941 }
12942 }
12943 }
12944
12945
12946 //
12947 // Message: addr
12948 //
12949 if (fSendTrickle)
12950 {
12951 vector<CAddress> vAddr;
12952 vAddr.reserve(pto->vAddrToSend.size());
12953 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
12954 {
12955 // returns true if wasn't already contained in the set
12956 if (pto->setAddrKnown.insert(addr).second)
12957 {
12958 vAddr.push_back(addr);
12959 // receiver rejects addr messages larger than 1000
12960 if (vAddr.size() >= 1000)
12961 {
12962 pto->PushMessage("addr", vAddr);
12963 vAddr.clear();
12964 }
12965 }
12966 }
12967 pto->vAddrToSend.clear();
12968 if (!vAddr.empty())
12969 pto->PushMessage("addr", vAddr);
12970 }
12971
12972
12973 //
12974 // Message: inventory
12975 //
12976 vector<CInv> vInv;
12977 vector<CInv> vInvWait;
12978 CRITICAL_BLOCK(pto->cs_inventory)
12979 {
12980 vInv.reserve(pto->vInventoryToSend.size());
12981 vInvWait.reserve(pto->vInventoryToSend.size());
12982 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
12983 {
12984 if (pto->setInventoryKnown.count(inv))
12985 continue;
12986
12987 // trickle out tx inv to protect privacy
12988 if (inv.type == MSG_TX && !fSendTrickle)
12989 {
12990 // 1/4 of tx invs blast to all immediately
12991 static uint256 hashSalt;
12992 if (hashSalt == 0)
12993 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
12994 uint256 hashRand = inv.hash ^ hashSalt;
12995 hashRand = Hash(BEGIN(hashRand), END(hashRand));
12996 bool fTrickleWait = ((hashRand & 3) != 0);
12997
12998 // always trickle our own transactions
12999 if (!fTrickleWait)
13000 {
13001 CWalletTx wtx;
13002 if (GetTransaction(inv.hash, wtx))
13003 if (wtx.fFromMe)
13004 fTrickleWait = true;
13005 }
13006
13007 if (fTrickleWait)
13008 {
13009 vInvWait.push_back(inv);
13010 continue;
13011 }
13012 }
13013
13014 // returns true if wasn't already contained in the set
13015 if (pto->setInventoryKnown.insert(inv).second)
13016 {
13017 vInv.push_back(inv);
13018 if (vInv.size() >= 1000)
13019 {
13020 pto->PushMessage("inv", vInv);
13021 vInv.clear();
13022 }
13023 }
13024 }
13025 pto->vInventoryToSend = vInvWait;
13026 }
13027 if (!vInv.empty())
13028 pto->PushMessage("inv", vInv);
13029
13030
13031 //
13032 // Message: getdata
13033 //
13034 vector<CInv> vGetData;
13035 int64 nNow = GetTime() * 1000000;
13036 CTxDB txdb("r");
13037 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
13038 {
13039 const CInv& inv = (*pto->mapAskFor.begin()).second;
13040 if (!AlreadyHave(txdb, inv))
13041 {
13042 printf("sending getdata: %s\n", inv.ToString().c_str());
13043 vGetData.push_back(inv);
13044 if (vGetData.size() >= 1000)
13045 {
13046 pto->PushMessage("getdata", vGetData);
13047 vGetData.clear();
13048 }
13049 }
13050 mapAlreadyAskedFor[inv] = nNow;
13051 pto->mapAskFor.erase(pto->mapAskFor.begin());
13052 }
13053 if (!vGetData.empty())
13054 pto->PushMessage("getdata", vGetData);
13055
13056 }
13057 return true;
13058 }
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073 //////////////////////////////////////////////////////////////////////////////
13074 //
13075 // BitcoinMiner
13076 //
13077
13078 int static FormatHashBlocks(void* pbuffer, unsigned int len)
13079 {
13080 unsigned char* pdata = (unsigned char*)pbuffer;
13081 unsigned int blocks = 1 + ((len + 8) / 64);
13082 unsigned char* pend = pdata + 64 * blocks;
13083 memset(pdata + len, 0, 64 * blocks - len);
13084 pdata[len] = 0x80;
13085 unsigned int bits = len * 8;
13086 pend[-1] = (bits >> 0) & 0xff;
13087 pend[-2] = (bits >> 8) & 0xff;
13088 pend[-3] = (bits >> 16) & 0xff;
13089 pend[-4] = (bits >> 24) & 0xff;
13090 return blocks;
13091 }
13092
13093 static const unsigned int pSHA256InitState[8] =
13094 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
13095
13096 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
13097 {
13098 SHA256_CTX ctx;
13099 unsigned char data[64];
13100
13101 SHA256_Init(&ctx);
13102
13103 for (int i = 0; i < 16; i++)
13104 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
13105
13106 for (int i = 0; i < 8; i++)
13107 ctx.h[i] = ((uint32_t*)pinit)[i];
13108
13109 SHA256_Update(&ctx, data, sizeof(data));
13110 for (int i = 0; i < 8; i++)
13111 ((uint32_t*)pstate)[i] = ctx.h[i];
13112 }
13113
13114 //
13115 // ScanHash scans nonces looking for a hash with at least some zero bits.
13116 // It operates on big endian data. Caller does the byte reversing.
13117 // All input buffers are 16-byte aligned. nNonce is usually preserved
13118 // between calls, but periodically or if nNonce is 0xffff0000 or above,
13119 // the block is rebuilt and nNonce starts over at zero.
13120 //
13121 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
13122 {
13123 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
13124 for (;;)
13125 {
13126 // Crypto++ SHA-256
13127 // Hash pdata using pmidstate as the starting state into
13128 // preformatted buffer phash1, then hash phash1 into phash
13129 nNonce++;
13130 SHA256Transform(phash1, pdata, pmidstate);
13131 SHA256Transform(phash, phash1, pSHA256InitState);
13132
13133 // Return the nonce if the hash has at least some zero bits,
13134 // caller will check if it has enough to reach the target
13135 if (((unsigned short*)phash)[14] == 0)
13136 return nNonce;
13137
13138 // If nothing found after trying for a while, return -1
13139 if ((nNonce & 0xffff) == 0)
13140 {
13141 nHashesDone = 0xffff+1;
13142 return -1;
13143 }
13144 }
13145 }
13146
13147 // Some explaining would be appreciated
13148 class COrphan
13149 {
13150 public:
13151 CTransaction* ptx;
13152 set<uint256> setDependsOn;
13153 double dPriority;
13154
13155 COrphan(CTransaction* ptxIn)
13156 {
13157 ptx = ptxIn;
13158 dPriority = 0;
13159 }
13160
13161 void print() const
13162 {
13163 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
13164 BOOST_FOREACH(uint256 hash, setDependsOn)
13165 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
13166 }
13167 };
13168
13169
13170 CBlock* CreateNewBlock(CReserveKey& reservekey)
13171 {
13172 CBlockIndex* pindexPrev = pindexBest;
13173
13174 // Create new block
13175 auto_ptr<CBlock> pblock(new CBlock());
13176 if (!pblock.get())
13177 return NULL;
13178
13179 // Create coinbase tx
13180 CTransaction txNew;
13181 txNew.vin.resize(1);
13182 txNew.vin[0].prevout.SetNull();
13183 txNew.vout.resize(1);
13184 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
13185
13186 // Add our coinbase tx as first transaction
13187 pblock->vtx.push_back(txNew);
13188
13189 // Collect memory pool transactions into the block
13190 int64 nFees = 0;
13191 CRITICAL_BLOCK(cs_main)
13192 CRITICAL_BLOCK(cs_mapTransactions)
13193 {
13194 CTxDB txdb("r");
13195
13196 // Priority order to process transactions
13197 list<COrphan> vOrphan; // list memory doesn't move
13198 map<uint256, vector<COrphan*> > mapDependers;
13199 multimap<double, CTransaction*> mapPriority;
13200 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
13201 {
13202 CTransaction& tx = (*mi).second;
13203 if (tx.IsCoinBase() || !tx.IsFinal())
13204 continue;
13205
13206 COrphan* porphan = NULL;
13207 double dPriority = 0;
13208 BOOST_FOREACH(const CTxIn& txin, tx.vin)
13209 {
13210 // Read prev transaction
13211 CTransaction txPrev;
13212 CTxIndex txindex;
13213 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
13214 {
13215 // Has to wait for dependencies
13216 if (!porphan)
13217 {
13218 // Use list for automatic deletion
13219 vOrphan.push_back(COrphan(&tx));
13220 porphan = &vOrphan.back();
13221 }
13222 mapDependers[txin.prevout.hash].push_back(porphan);
13223 porphan->setDependsOn.insert(txin.prevout.hash);
13224 continue;
13225 }
13226 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
13227
13228 // Read block header
13229 int nConf = txindex.GetDepthInMainChain();
13230
13231 dPriority += (double)nValueIn * nConf;
13232
13233 if (fDebug && GetBoolArg("-printpriority"))
13234 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
13235 }
13236
13237 // Priority is sum(valuein * age) / txsize
13238 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
13239
13240 if (porphan)
13241 porphan->dPriority = dPriority;
13242 else
13243 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
13244
13245 if (fDebug && GetBoolArg("-printpriority"))
13246 {
13247 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
13248 if (porphan)
13249 porphan->print();
13250 printf("\n");
13251 }
13252 }
13253
13254 // Collect transactions into block
13255 map<uint256, CTxIndex> mapTestPool;
13256 uint64 nBlockSize = 1000;
13257 int nBlockSigOps = 100;
13258 while (!mapPriority.empty())
13259 {
13260 // Take highest priority transaction off priority queue
13261 double dPriority = -(*mapPriority.begin()).first;
13262 CTransaction& tx = *(*mapPriority.begin()).second;
13263 mapPriority.erase(mapPriority.begin());
13264
13265 // Size limits
13266 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
13267 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
13268 continue;
13269 int nTxSigOps = tx.GetSigOpCount();
13270 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
13271 continue;
13272
13273 // Transaction fee required depends on block size
13274 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
13275 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
13276
13277 // Connecting shouldn't fail due to dependency on other memory pool transactions
13278 // because we're already processing them in order of dependency
13279 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
13280 bool fInvalid;
13281 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee, fInvalid))
13282 continue;
13283 swap(mapTestPool, mapTestPoolTmp);
13284
13285 // Added
13286 pblock->vtx.push_back(tx);
13287 nBlockSize += nTxSize;
13288 nBlockSigOps += nTxSigOps;
13289
13290 // Add transactions that depend on this one to the priority queue
13291 uint256 hash = tx.GetHash();
13292 if (mapDependers.count(hash))
13293 {
13294 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
13295 {
13296 if (!porphan->setDependsOn.empty())
13297 {
13298 porphan->setDependsOn.erase(hash);
13299 if (porphan->setDependsOn.empty())
13300 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
13301 }
13302 }
13303 }
13304 }
13305 }
13306 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
13307
13308 // Fill in header
13309 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
13310 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
13311 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
13312 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
13313 pblock->nNonce = 0;
13314
13315 return pblock.release();
13316 }
13317
13318
13319 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
13320 {
13321 // Update nExtraNonce
13322 static uint256 hashPrevBlock;
13323 if (hashPrevBlock != pblock->hashPrevBlock)
13324 {
13325 nExtraNonce = 0;
13326 hashPrevBlock = pblock->hashPrevBlock;
13327 }
13328 ++nExtraNonce;
13329 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
13330 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
13331 }
13332
13333
13334 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
13335 {
13336 //
13337 // Prebuild hash buffers
13338 //
13339 struct
13340 {
13341 struct unnamed2
13342 {
13343 int nVersion;
13344 uint256 hashPrevBlock;
13345 uint256 hashMerkleRoot;
13346 unsigned int nTime;
13347 unsigned int nBits;
13348 unsigned int nNonce;
13349 }
13350 block;
13351 unsigned char pchPadding0[64];
13352 uint256 hash1;
13353 unsigned char pchPadding1[64];
13354 }
13355 tmp;
13356 memset(&tmp, 0, sizeof(tmp));
13357
13358 tmp.block.nVersion = pblock->nVersion;
13359 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
13360 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
13361 tmp.block.nTime = pblock->nTime;
13362 tmp.block.nBits = pblock->nBits;
13363 tmp.block.nNonce = pblock->nNonce;
13364
13365 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
13366 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
13367
13368 // Byte swap all the input buffer
13369 for (int i = 0; i < sizeof(tmp)/4; i++)
13370 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
13371
13372 // Precalc the first half of the first hash, which stays constant
13373 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
13374
13375 memcpy(pdata, &tmp.block, 128);
13376 memcpy(phash1, &tmp.hash1, 64);
13377 }
13378
13379
13380 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
13381 {
13382 uint256 hash = pblock->GetHash();
13383 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
13384
13385 if (hash > hashTarget)
13386 return false;
13387
13388 //// debug print
13389 printf("BitcoinMiner:\n");
13390 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
13391 pblock->print();
13392 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
13393 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
13394
13395 // Found a solution
13396 CRITICAL_BLOCK(cs_main)
13397 {
13398 if (pblock->hashPrevBlock != hashBestChain)
13399 return error("BitcoinMiner : generated block is stale");
13400
13401 // Remove key from key pool
13402 reservekey.KeepKey();
13403
13404 // Track how many getdata requests this block gets
13405 CRITICAL_BLOCK(wallet.cs_wallet)
13406 wallet.mapRequestCount[pblock->GetHash()] = 0;
13407
13408 // Process this block the same as if we had received it from another node
13409 if (!ProcessBlock(NULL, pblock))
13410 return error("BitcoinMiner : ProcessBlock, block not accepted");
13411 }
13412
13413 return true;
13414 }
13415
13416 void static ThreadBitcoinMiner(void* parg);
13417
13418 void static BitcoinMiner(CWallet *pwallet)
13419 {
13420 printf("BitcoinMiner started\n");
13421 SetThreadPriority(THREAD_PRIORITY_LOWEST);
13422
13423 // Each thread has its own key and counter
13424 CReserveKey reservekey(pwallet);
13425 unsigned int nExtraNonce = 0;
13426
13427 while (fGenerateBitcoins)
13428 {
13429 if (AffinityBugWorkaround(ThreadBitcoinMiner))
13430 return;
13431 if (fShutdown)
13432 return;
13433 while (vNodes.empty() || IsInitialBlockDownload())
13434 {
13435 Sleep(1000);
13436 if (fShutdown)
13437 return;
13438 if (!fGenerateBitcoins)
13439 return;
13440 }
13441
13442
13443 //
13444 // Create new block
13445 //
13446 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
13447 CBlockIndex* pindexPrev = pindexBest;
13448
13449 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
13450 if (!pblock.get())
13451 return;
13452 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
13453
13454 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
13455
13456
13457 //
13458 // Prebuild hash buffers
13459 //
13460 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
13461 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
13462 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
13463
13464 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
13465
13466 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
13467 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
13468
13469
13470 //
13471 // Search
13472 //
13473 int64 nStart = GetTime();
13474 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
13475 uint256 hashbuf[2];
13476 uint256& hash = *alignup<16>(hashbuf);
13477 loop
13478 {
13479 unsigned int nHashesDone = 0;
13480 unsigned int nNonceFound;
13481
13482 // Crypto++ SHA-256
13483 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
13484 (char*)&hash, nHashesDone);
13485
13486 // Check if something found
13487 if (nNonceFound != -1)
13488 {
13489 for (int i = 0; i < sizeof(hash)/4; i++)
13490 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
13491
13492 if (hash <= hashTarget)
13493 {
13494 // Found a solution
13495 pblock->nNonce = ByteReverse(nNonceFound);
13496 assert(hash == pblock->GetHash());
13497
13498 SetThreadPriority(THREAD_PRIORITY_NORMAL);
13499 CheckWork(pblock.get(), *pwalletMain, reservekey);
13500 SetThreadPriority(THREAD_PRIORITY_LOWEST);
13501 break;
13502 }
13503 }
13504
13505 // Meter hashes/sec
13506 static int64 nHashCounter;
13507 if (nHPSTimerStart == 0)
13508 {
13509 nHPSTimerStart = GetTimeMillis();
13510 nHashCounter = 0;
13511 }
13512 else
13513 nHashCounter += nHashesDone;
13514 if (GetTimeMillis() - nHPSTimerStart > 4000)
13515 {
13516 static CCriticalSection cs;
13517 CRITICAL_BLOCK(cs)
13518 {
13519 if (GetTimeMillis() - nHPSTimerStart > 4000)
13520 {
13521 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
13522 nHPSTimerStart = GetTimeMillis();
13523 nHashCounter = 0;
13524 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
13525 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
13526 static int64 nLogTime;
13527 if (GetTime() - nLogTime > 30 * 60)
13528 {
13529 nLogTime = GetTime();
13530 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
13531 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
13532 }
13533 }
13534 }
13535 }
13536
13537 // Check for stop or if block needs to be rebuilt
13538 if (fShutdown)
13539 return;
13540 if (!fGenerateBitcoins)
13541 return;
13542 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
13543 return;
13544 if (vNodes.empty())
13545 break;
13546 if (nBlockNonce >= 0xffff0000)
13547 break;
13548 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
13549 break;
13550 if (pindexPrev != pindexBest)
13551 break;
13552
13553 // Update nTime every few seconds
13554 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
13555 nBlockTime = ByteReverse(pblock->nTime);
13556 }
13557 }
13558 }
13559
13560 void static ThreadBitcoinMiner(void* parg)
13561 {
13562 CWallet* pwallet = (CWallet*)parg;
13563 try
13564 {
13565 vnThreadsRunning[3]++;
13566 BitcoinMiner(pwallet);
13567 vnThreadsRunning[3]--;
13568 }
13569 catch (std::exception& e) {
13570 vnThreadsRunning[3]--;
13571 PrintException(&e, "ThreadBitcoinMiner()");
13572 } catch (...) {
13573 vnThreadsRunning[3]--;
13574 PrintException(NULL, "ThreadBitcoinMiner()");
13575 }
13576 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
13577 nHPSTimerStart = 0;
13578 if (vnThreadsRunning[3] == 0)
13579 dHashesPerSec = 0;
13580 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
13581 }
13582
13583
13584 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
13585 {
13586 if (fGenerateBitcoins != fGenerate)
13587 {
13588 fGenerateBitcoins = fGenerate;
13589 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
13590 MainFrameRepaint();
13591 }
13592 if (fGenerateBitcoins)
13593 {
13594 int nProcessors = boost::thread::hardware_concurrency();
13595 printf("%d processors\n", nProcessors);
13596 if (nProcessors < 1)
13597 nProcessors = 1;
13598 if (fLimitProcessors && nProcessors > nLimitProcessors)
13599 nProcessors = nLimitProcessors;
13600 int nAddThreads = nProcessors - vnThreadsRunning[3];
13601 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
13602 for (int i = 0; i < nAddThreads; i++)
13603 {
13604 if (!CreateThread(ThreadBitcoinMiner, pwallet))
13605 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
13606 Sleep(10);
13607 }
13608 }
13609 }