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