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