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#ifndef BITCOIN_MAIN_H
   6#define BITCOIN_MAIN_H
   7
   8#include "bignum.h"
   9#include "net.h"
  10#include "key.h"
  11#include "script.h"
  12#include "db.h"
  13
  14#include <list>
  15
  16class CBlock;
  17class CBlockIndex;
  18class CWalletTx;
  19class CWallet;
  20class CKeyItem;
  21class CReserveKey;
  22class CWalletDB;
  23
  24class CAddress;
  25class CInv;
  26class CRequestTracker;
  27class CNode;
  28class CBlockIndex;
  29
  30static const unsigned int MAX_BLOCK_SIZE = 1000000;
  31static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
  32static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
  33static const int64 COIN = 100000000;
  34static const int64 CENT = 1000000;
  35static const int64 MIN_TX_FEE = 50000;
  36static const int64 MIN_RELAY_TX_FEE = 10000;
  37static const int64 MAX_MONEY = 21000000 * COIN;
  38inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
  39static const int COINBASE_MATURITY = 100;
  40// Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
  41static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
  42
  43
  44
  45
  46
  47
  48extern CCriticalSection cs_main;
  49extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  50extern uint256 hashGenesisBlock;
  51extern CBlockIndex* pindexGenesisBlock;
  52extern int nBestHeight;
  53extern CBigNum bnBestChainWork;
  54extern CBigNum bnBestInvalidWork;
  55extern uint256 hashBestChain;
  56extern CBlockIndex* pindexBest;
  57extern unsigned int nTransactionsUpdated;
  58extern double dHashesPerSec;
  59extern int64 nHPSTimerStart;
  60extern int64 nTimeBestReceived;
  61extern CCriticalSection cs_setpwalletRegistered;
  62extern std::set<CWallet*> setpwalletRegistered;
  63
  64// Settings
  65extern int fGenerateBitcoins;
  66extern int64 nTransactionFee;
  67extern int fLimitProcessors;
  68extern int nLimitProcessors;
  69extern int fMinimizeToTray;
  70extern int fMinimizeOnClose;
  71
  72
  73
  74
  75
  76class CReserveKey;
  77class CTxDB;
  78class CTxIndex;
  79
  80void RegisterWallet(CWallet* pwalletIn);
  81void UnregisterWallet(CWallet* pwalletIn);
  82bool ProcessBlock(CNode* pfrom, CBlock* pblock);
  83bool CheckDiskSpace(uint64 nAdditionalBytes=0);
  84FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
  85FILE* AppendBlockFile(unsigned int& nFileRet);
  86bool LoadBlockIndex(bool fAllowNew=true);
  87void PrintBlockTree();
  88bool ProcessMessages(CNode* pfrom);
  89bool SendMessages(CNode* pto, bool fSendTrickle);
  90void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
  91CBlock* CreateNewBlock(CReserveKey& reservekey);
  92void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
  93void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
  94bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
  95bool CheckProofOfWork(uint256 hash, unsigned int nBits);
  96unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
  97int GetNumBlocksOfPeers();
  98bool IsInitialBlockDownload();
  99std::string GetWarnings(std::string strFor);
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
 113
 114template<typename T>
 115bool WriteSetting(const std::string& strKey, const T& value)
 116{
 117    bool fOk = false;
 118    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
 119    {
 120        std::string strWalletFile;
 121        if (!GetWalletFile(pwallet, strWalletFile))
 122            continue;
 123        fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
 124    }
 125    return fOk;
 126}
 127
 128
 129class CDiskTxPos
 130{
 131public:
 132    unsigned int nFile;
 133    unsigned int nBlockPos;
 134    unsigned int nTxPos;
 135
 136    CDiskTxPos()
 137    {
 138        SetNull();
 139    }
 140
 141    CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
 142    {
 143        nFile = nFileIn;
 144        nBlockPos = nBlockPosIn;
 145        nTxPos = nTxPosIn;
 146    }
 147
 148    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
 149    void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
 150    bool IsNull() const { return (nFile == -1); }
 151
 152    friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
 153    {
 154        return (a.nFile     == b.nFile &&
 155                a.nBlockPos == b.nBlockPos &&
 156                a.nTxPos    == b.nTxPos);
 157    }
 158
 159    friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
 160    {
 161        return !(a == b);
 162    }
 163
 164    std::string ToString() const
 165    {
 166        if (IsNull())
 167            return strprintf("null");
 168        else
 169            return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
 170    }
 171
 172    void print() const
 173    {
 174        printf("%s", ToString().c_str());
 175    }
 176};
 177
 178
 179
 180
 181class CInPoint
 182{
 183public:
 184    CTransaction* ptx;
 185    unsigned int n;
 186
 187    CInPoint() { SetNull(); }
 188    CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
 189    void SetNull() { ptx = NULL; n = -1; }
 190    bool IsNull() const { return (ptx == NULL && n == -1); }
 191};
 192
 193
 194
 195
 196class COutPoint
 197{
 198public:
 199    uint256 hash;
 200    unsigned int n;
 201
 202    COutPoint() { SetNull(); }
 203    COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
 204    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
 205    void SetNull() { hash = 0; n = -1; }
 206    bool IsNull() const { return (hash == 0 && n == -1); }
 207
 208    friend bool operator<(const COutPoint& a, const COutPoint& b)
 209    {
 210        return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
 211    }
 212
 213    friend bool operator==(const COutPoint& a, const COutPoint& b)
 214    {
 215        return (a.hash == b.hash && a.n == b.n);
 216    }
 217
 218    friend bool operator!=(const COutPoint& a, const COutPoint& b)
 219    {
 220        return !(a == b);
 221    }
 222
 223    std::string ToString() const
 224    {
 225        return strprintf("COutPoint(%s, %d)", hash.ToString().c_str(), n);
 226    }
 227
 228    void print() const
 229    {
 230        printf("%s\n", ToString().c_str());
 231    }
 232};
 233
 234
 235
 236
 237//
 238// An input of a transaction.  It contains the location of the previous
 239// transaction's output that it claims and a signature that matches the
 240// output's public key.
 241//
 242class CTxIn
 243{
 244public:
 245    COutPoint prevout;
 246    CScript scriptSig;
 247    unsigned int nSequence;
 248
 249    CTxIn()
 250    {
 251        nSequence = UINT_MAX;
 252    }
 253
 254    explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
 255    {
 256        prevout = prevoutIn;
 257        scriptSig = scriptSigIn;
 258        nSequence = nSequenceIn;
 259    }
 260
 261    CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
 262    {
 263        prevout = COutPoint(hashPrevTx, nOut);
 264        scriptSig = scriptSigIn;
 265        nSequence = nSequenceIn;
 266    }
 267
 268    IMPLEMENT_SERIALIZE
 269    (
 270        READWRITE(prevout);
 271        READWRITE(scriptSig);
 272        READWRITE(nSequence);
 273    )
 274
 275    bool IsFinal() const
 276    {
 277        return (nSequence == UINT_MAX);
 278    }
 279
 280    friend bool operator==(const CTxIn& a, const CTxIn& b)
 281    {
 282        return (a.prevout   == b.prevout &&
 283                a.scriptSig == b.scriptSig &&
 284                a.nSequence == b.nSequence);
 285    }
 286
 287    friend bool operator!=(const CTxIn& a, const CTxIn& b)
 288    {
 289        return !(a == b);
 290    }
 291
 292    std::string ToString() const
 293    {
 294        std::string str;
 295        str += strprintf("CTxIn(");
 296        str += prevout.ToString();
 297        if (prevout.IsNull())
 298            str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
 299        else
 300            str += strprintf(", scriptSig=%s", scriptSig.ToString().c_str());
 301        if (nSequence != UINT_MAX)
 302            str += strprintf(", nSequence=%u", nSequence);
 303        str += ")";
 304        return str;
 305    }
 306
 307    void print() const
 308    {
 309        printf("%s\n", ToString().c_str());
 310    }
 311};
 312
 313
 314
 315
 316//
 317// An output of a transaction.  It contains the public key that the next input
 318// must be able to sign with to claim it.
 319//
 320class CTxOut
 321{
 322public:
 323    int64 nValue;
 324    CScript scriptPubKey;
 325
 326    CTxOut()
 327    {
 328        SetNull();
 329    }
 330
 331    CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
 332    {
 333        nValue = nValueIn;
 334        scriptPubKey = scriptPubKeyIn;
 335    }
 336
 337    IMPLEMENT_SERIALIZE
 338    (
 339        READWRITE(nValue);
 340        READWRITE(scriptPubKey);
 341    )
 342
 343    void SetNull()
 344    {
 345        nValue = -1;
 346        scriptPubKey.clear();
 347    }
 348
 349    bool IsNull()
 350    {
 351        return (nValue == -1);
 352    }
 353
 354    uint256 GetHash() const
 355    {
 356        return SerializeHash(*this);
 357    }
 358
 359    friend bool operator==(const CTxOut& a, const CTxOut& b)
 360    {
 361        return (a.nValue       == b.nValue &&
 362                a.scriptPubKey == b.scriptPubKey);
 363    }
 364
 365    friend bool operator!=(const CTxOut& a, const CTxOut& b)
 366    {
 367        return !(a == b);
 368    }
 369
 370    std::string ToString() const
 371    {
 372        if (scriptPubKey.size() < 6)
 373            return "CTxOut(error)";
 374        return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().c_str());
 375    }
 376
 377    void print() const
 378    {
 379        printf("%s\n", ToString().c_str());
 380    }
 381};
 382
 383
 384
 385
 386//
 387// The basic transaction that is broadcasted on the network and contained in
 388// blocks.  A transaction can contain multiple inputs and outputs.
 389//
 390class CTransaction
 391{
 392public:
 393    int nVersion;
 394    std::vector<CTxIn> vin;
 395    std::vector<CTxOut> vout;
 396    unsigned int nLockTime;
 397
 398    // Denial-of-service detection:
 399    mutable int nDoS;
 400    bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
 401
 402    CTransaction()
 403    {
 404        SetNull();
 405    }
 406
 407    IMPLEMENT_SERIALIZE
 408    (
 409        READWRITE(this->nVersion);
 410        nVersion = this->nVersion;
 411        READWRITE(vin);
 412        READWRITE(vout);
 413        READWRITE(nLockTime);
 414    )
 415
 416    void SetNull()
 417    {
 418        nVersion = 1;
 419        vin.clear();
 420        vout.clear();
 421        nLockTime = 0;
 422        nDoS = 0;  // Denial-of-service prevention
 423    }
 424
 425    bool IsNull() const
 426    {
 427        return (vin.empty() && vout.empty());
 428    }
 429
 430    uint256 GetHash() const
 431    {
 432        return SerializeHash(*this);
 433    }
 434
 435    bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
 436    {
 437        // Time based nLockTime implemented in 0.1.6
 438        if (nLockTime == 0)
 439            return true;
 440        if (nBlockHeight == 0)
 441            nBlockHeight = nBestHeight;
 442        if (nBlockTime == 0)
 443            nBlockTime = GetAdjustedTime();
 444        if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
 445            return true;
 446        BOOST_FOREACH(const CTxIn& txin, vin)
 447            if (!txin.IsFinal())
 448                return false;
 449        return true;
 450    }
 451
 452    bool IsNewerThan(const CTransaction& old) const
 453    {
 454        if (vin.size() != old.vin.size())
 455            return false;
 456        for (int i = 0; i < vin.size(); i++)
 457            if (vin[i].prevout != old.vin[i].prevout)
 458                return false;
 459
 460        bool fNewer = false;
 461        unsigned int nLowest = UINT_MAX;
 462        for (int i = 0; i < vin.size(); i++)
 463        {
 464            if (vin[i].nSequence != old.vin[i].nSequence)
 465            {
 466                if (vin[i].nSequence <= nLowest)
 467                {
 468                    fNewer = false;
 469                    nLowest = vin[i].nSequence;
 470                }
 471                if (old.vin[i].nSequence < nLowest)
 472                {
 473                    fNewer = true;
 474                    nLowest = old.vin[i].nSequence;
 475                }
 476            }
 477        }
 478        return fNewer;
 479    }
 480
 481    bool IsCoinBase() const
 482    {
 483        return (vin.size() == 1 && vin[0].prevout.IsNull());
 484    }
 485
 486    int GetSigOpCount() const
 487    {
 488        int n = 0;
 489        BOOST_FOREACH(const CTxIn& txin, vin)
 490            n += txin.scriptSig.GetSigOpCount();
 491        BOOST_FOREACH(const CTxOut& txout, vout)
 492            n += txout.scriptPubKey.GetSigOpCount();
 493        return n;
 494    }
 495
 496    bool IsStandard() const
 497    {
 498        BOOST_FOREACH(const CTxIn& txin, vin)
 499            if (!txin.scriptSig.IsPushOnly())
 500                return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
 501        BOOST_FOREACH(const CTxOut& txout, vout)
 502            if (!::IsStandard(txout.scriptPubKey))
 503                return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
 504        return true;
 505    }
 506
 507    int64 GetValueOut() const
 508    {
 509        int64 nValueOut = 0;
 510        BOOST_FOREACH(const CTxOut& txout, vout)
 511        {
 512            nValueOut += txout.nValue;
 513            if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
 514                throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
 515        }
 516        return nValueOut;
 517    }
 518
 519    static bool AllowFree(double dPriority)
 520    {
 521        // Large (in bytes) low-priority (new, small-coin) transactions
 522        // need a fee.
 523        return dPriority > COIN * 144 / 250;
 524    }
 525
 526    int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
 527    {
 528        // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
 529        int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
 530
 531        unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
 532        unsigned int nNewBlockSize = nBlockSize + nBytes;
 533        int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
 534
 535        if (fAllowFree)
 536        {
 537            if (nBlockSize == 1)
 538            {
 539                // Transactions under 10K are free
 540                // (about 4500bc if made of 50bc inputs)
 541                if (nBytes < 10000)
 542                    nMinFee = 0;
 543            }
 544            else
 545            {
 546                // Free transaction area
 547                if (nNewBlockSize < 27000)
 548                    nMinFee = 0;
 549            }
 550        }
 551
 552        // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
 553        if (nMinFee < nBaseFee)
 554            BOOST_FOREACH(const CTxOut& txout, vout)
 555                if (txout.nValue < CENT)
 556                    nMinFee = nBaseFee;
 557
 558        // Raise the price as the block approaches full
 559        if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
 560        {
 561            if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
 562                return MAX_MONEY;
 563            nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
 564        }
 565
 566        if (!MoneyRange(nMinFee))
 567            nMinFee = MAX_MONEY;
 568        return nMinFee;
 569    }
 570
 571
 572    bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
 573    {
 574        CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
 575        if (!filein)
 576            return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
 577
 578        // Read transaction
 579        if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
 580            return error("CTransaction::ReadFromDisk() : fseek failed");
 581        filein >> *this;
 582
 583        // Return file pointer
 584        if (pfileRet)
 585        {
 586            if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
 587                return error("CTransaction::ReadFromDisk() : second fseek failed");
 588            *pfileRet = filein.release();
 589        }
 590        return true;
 591    }
 592
 593    friend bool operator==(const CTransaction& a, const CTransaction& b)
 594    {
 595        return (a.nVersion  == b.nVersion &&
 596                a.vin       == b.vin &&
 597                a.vout      == b.vout &&
 598                a.nLockTime == b.nLockTime);
 599    }
 600
 601    friend bool operator!=(const CTransaction& a, const CTransaction& b)
 602    {
 603        return !(a == b);
 604    }
 605
 606
 607    std::string ToString() const
 608    {
 609        std::string str;
 610        str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
 611            GetHash().ToString().c_str(),
 612            nVersion,
 613            vin.size(),
 614            vout.size(),
 615            nLockTime);
 616        for (int i = 0; i < vin.size(); i++)
 617            str += "    " + vin[i].ToString() + "\n";
 618        for (int i = 0; i < vout.size(); i++)
 619            str += "    " + vout[i].ToString() + "\n";
 620        return str;
 621    }
 622
 623    void print() const
 624    {
 625        printf("%s", ToString().c_str());
 626    }
 627
 628
 629    bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
 630    bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
 631    bool ReadFromDisk(COutPoint prevout);
 632    bool DisconnectInputs(CTxDB& txdb);
 633    bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
 634                       CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
 635                       bool& fInvalid);
 636    bool ClientConnectInputs();
 637    bool CheckTransaction() const;
 638    bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
 639    bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
 640protected:
 641    bool AddToMemoryPoolUnchecked();
 642public:
 643    bool RemoveFromMemoryPool();
 644};
 645
 646
 647
 648
 649
 650//
 651// A transaction with a merkle branch linking it to the block chain
 652//
 653class CMerkleTx : public CTransaction
 654{
 655public:
 656    uint256 hashBlock;
 657    std::vector<uint256> vMerkleBranch;
 658    int nIndex;
 659
 660    // memory only
 661    mutable char fMerkleVerified;
 662
 663
 664    CMerkleTx()
 665    {
 666        Init();
 667    }
 668
 669    CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
 670    {
 671        Init();
 672    }
 673
 674    void Init()
 675    {
 676        hashBlock = 0;
 677        nIndex = -1;
 678        fMerkleVerified = false;
 679    }
 680
 681
 682    IMPLEMENT_SERIALIZE
 683    (
 684        nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
 685        nVersion = this->nVersion;
 686        READWRITE(hashBlock);
 687        READWRITE(vMerkleBranch);
 688        READWRITE(nIndex);
 689    )
 690
 691
 692    int SetMerkleBranch(const CBlock* pblock=NULL);
 693    int GetDepthInMainChain(int& nHeightRet) const;
 694    int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
 695    bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
 696    int GetBlocksToMaturity() const;
 697    bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
 698    bool AcceptToMemoryPool();
 699};
 700
 701
 702
 703
 704//
 705// A txdb record that contains the disk location of a transaction and the
 706// locations of transactions that spend its outputs.  vSpent is really only
 707// used as a flag, but having the location is very helpful for debugging.
 708//
 709class CTxIndex
 710{
 711public:
 712    CDiskTxPos pos;
 713    std::vector<CDiskTxPos> vSpent;
 714
 715    CTxIndex()
 716    {
 717        SetNull();
 718    }
 719
 720    CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
 721    {
 722        pos = posIn;
 723        vSpent.resize(nOutputs);
 724    }
 725
 726    IMPLEMENT_SERIALIZE
 727    (
 728        if (!(nType & SER_GETHASH))
 729            READWRITE(nVersion);
 730        READWRITE(pos);
 731        READWRITE(vSpent);
 732    )
 733
 734    void SetNull()
 735    {
 736        pos.SetNull();
 737        vSpent.clear();
 738    }
 739
 740    bool IsNull()
 741    {
 742        return pos.IsNull();
 743    }
 744
 745    friend bool operator==(const CTxIndex& a, const CTxIndex& b)
 746    {
 747        return (a.pos    == b.pos &&
 748                a.vSpent == b.vSpent);
 749    }
 750
 751    friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
 752    {
 753        return !(a == b);
 754    }
 755    int GetDepthInMainChain() const;
 756};
 757
 758
 759
 760
 761
 762//
 763// Nodes collect new transactions into a block, hash them into a hash tree,
 764// and scan through nonce values to make the block's hash satisfy proof-of-work
 765// requirements.  When they solve the proof-of-work, they broadcast the block
 766// to everyone and the block is added to the block chain.  The first transaction
 767// in the block is a special one that creates a new coin owned by the creator
 768// of the block.
 769//
 770// Blocks are appended to blk0001.dat files on disk.  Their location on disk
 771// is indexed by CBlockIndex objects in memory.
 772//
 773class CBlock
 774{
 775public:
 776    // header
 777    int nVersion;
 778    uint256 hashPrevBlock;
 779    uint256 hashMerkleRoot;
 780    unsigned int nTime;
 781    unsigned int nBits;
 782    unsigned int nNonce;
 783
 784    // network and disk
 785    std::vector<CTransaction> vtx;
 786
 787    // memory only
 788    mutable std::vector<uint256> vMerkleTree;
 789
 790    // Denial-of-service detection:
 791    mutable int nDoS;
 792    bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
 793
 794    CBlock()
 795    {
 796        SetNull();
 797    }
 798
 799    IMPLEMENT_SERIALIZE
 800    (
 801        READWRITE(this->nVersion);
 802        nVersion = this->nVersion;
 803        READWRITE(hashPrevBlock);
 804        READWRITE(hashMerkleRoot);
 805        READWRITE(nTime);
 806        READWRITE(nBits);
 807        READWRITE(nNonce);
 808
 809        // ConnectBlock depends on vtx being last so it can calculate offset
 810        if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
 811            READWRITE(vtx);
 812        else if (fRead)
 813            const_cast<CBlock*>(this)->vtx.clear();
 814    )
 815
 816    void SetNull()
 817    {
 818        nVersion = 1;
 819        hashPrevBlock = 0;
 820        hashMerkleRoot = 0;
 821        nTime = 0;
 822        nBits = 0;
 823        nNonce = 0;
 824        vtx.clear();
 825        vMerkleTree.clear();
 826        nDoS = 0;
 827    }
 828
 829    bool IsNull() const
 830    {
 831        return (nBits == 0);
 832    }
 833
 834    uint256 GetHash() const
 835    {
 836        return Hash(BEGIN(nVersion), END(nNonce));
 837    }
 838
 839    int64 GetBlockTime() const
 840    {
 841        return (int64)nTime;
 842    }
 843
 844    int GetSigOpCount() const
 845    {
 846        int n = 0;
 847        BOOST_FOREACH(const CTransaction& tx, vtx)
 848            n += tx.GetSigOpCount();
 849        return n;
 850    }
 851
 852
 853    uint256 BuildMerkleTree() const
 854    {
 855        vMerkleTree.clear();
 856        BOOST_FOREACH(const CTransaction& tx, vtx)
 857            vMerkleTree.push_back(tx.GetHash());
 858        int j = 0;
 859        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
 860        {
 861            for (int i = 0; i < nSize; i += 2)
 862            {
 863                int i2 = std::min(i+1, nSize-1);
 864                vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
 865                                           BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
 866            }
 867            j += nSize;
 868        }
 869        return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
 870    }
 871
 872    std::vector<uint256> GetMerkleBranch(int nIndex) const
 873    {
 874        if (vMerkleTree.empty())
 875            BuildMerkleTree();
 876        std::vector<uint256> vMerkleBranch;
 877        int j = 0;
 878        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
 879        {
 880            int i = std::min(nIndex^1, nSize-1);
 881            vMerkleBranch.push_back(vMerkleTree[j+i]);
 882            nIndex >>= 1;
 883            j += nSize;
 884        }
 885        return vMerkleBranch;
 886    }
 887
 888    static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
 889    {
 890        if (nIndex == -1)
 891            return 0;
 892        BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
 893        {
 894            if (nIndex & 1)
 895                hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
 896            else
 897                hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
 898            nIndex >>= 1;
 899        }
 900        return hash;
 901    }
 902
 903
 904    bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
 905    {
 906        // Open history file to append
 907        CAutoFile fileout = AppendBlockFile(nFileRet);
 908        if (!fileout)
 909            return error("CBlock::WriteToDisk() : AppendBlockFile failed");
 910
 911        // Write index header
 912        unsigned int nSize = fileout.GetSerializeSize(*this);
 913        fileout << FLATDATA(pchMessageStart) << nSize;
 914
 915        // Write block
 916        nBlockPosRet = ftell(fileout);
 917        if (nBlockPosRet == -1)
 918            return error("CBlock::WriteToDisk() : ftell failed");
 919        fileout << *this;
 920
 921        // Flush stdio buffers and commit to disk before returning
 922        fflush(fileout);
 923        if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
 924        {
 925            fsync(fileno(fileout));
 926        }
 927
 928        return true;
 929    }
 930
 931    bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
 932    {
 933        SetNull();
 934
 935        // Open history file to read
 936        CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
 937        if (!filein)
 938            return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
 939        if (!fReadTransactions)
 940            filein.nType |= SER_BLOCKHEADERONLY;
 941
 942        // Read block
 943        filein >> *this;
 944
 945        // Check the header
 946        if (!CheckProofOfWork(GetHash(), nBits))
 947            return error("CBlock::ReadFromDisk() : errors in block header");
 948
 949        return true;
 950    }
 951
 952
 953
 954    void print() const
 955    {
 956        printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
 957            GetHash().ToString().c_str(),
 958            nVersion,
 959            hashPrevBlock.ToString().c_str(),
 960            hashMerkleRoot.ToString().c_str(),
 961            nTime, nBits, nNonce,
 962            vtx.size());
 963        for (int i = 0; i < vtx.size(); i++)
 964        {
 965            printf("  ");
 966            vtx[i].print();
 967        }
 968        printf("  vMerkleTree: ");
 969        for (int i = 0; i < vMerkleTree.size(); i++)
 970            printf("%s ", vMerkleTree[i].ToString().c_str());
 971        printf("\n");
 972    }
 973
 974
 975    bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
 976    bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
 977    bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
 978    bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
 979    bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
 980    bool CheckBlock() const;
 981    bool AcceptBlock();
 982};
 983
 984
 985
 986
 987
 988
 989//
 990// The block chain is a tree shaped structure starting with the
 991// genesis block at the root, with each block potentially having multiple
 992// candidates to be the next block.  pprev and pnext link a path through the
 993// main/longest chain.  A blockindex may have multiple pprev pointing back
 994// to it, but pnext will only point forward to the longest branch, or will
 995// be null if the block is not part of the longest chain.
 996//
 997class CBlockIndex
 998{
 999public:
1000    const uint256* phashBlock;
1001    CBlockIndex* pprev;
1002    CBlockIndex* pnext;
1003    unsigned int nFile;
1004    unsigned int nBlockPos;
1005    int nHeight;
1006    CBigNum bnChainWork;
1007
1008    // block header
1009    int nVersion;
1010    uint256 hashMerkleRoot;
1011    unsigned int nTime;
1012    unsigned int nBits;
1013    unsigned int nNonce;
1014
1015
1016    CBlockIndex()
1017    {
1018        phashBlock = NULL;
1019        pprev = NULL;
1020        pnext = NULL;
1021        nFile = 0;
1022        nBlockPos = 0;
1023        nHeight = 0;
1024        bnChainWork = 0;
1025
1026        nVersion       = 0;
1027        hashMerkleRoot = 0;
1028        nTime          = 0;
1029        nBits          = 0;
1030        nNonce         = 0;
1031    }
1032
1033    CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1034    {
1035        phashBlock = NULL;
1036        pprev = NULL;
1037        pnext = NULL;
1038        nFile = nFileIn;
1039        nBlockPos = nBlockPosIn;
1040        nHeight = 0;
1041        bnChainWork = 0;
1042
1043        nVersion       = block.nVersion;
1044        hashMerkleRoot = block.hashMerkleRoot;
1045        nTime          = block.nTime;
1046        nBits          = block.nBits;
1047        nNonce         = block.nNonce;
1048    }
1049
1050    CBlock GetBlockHeader() const
1051    {
1052        CBlock block;
1053        block.nVersion       = nVersion;
1054        if (pprev)
1055            block.hashPrevBlock = pprev->GetBlockHash();
1056        block.hashMerkleRoot = hashMerkleRoot;
1057        block.nTime          = nTime;
1058        block.nBits          = nBits;
1059        block.nNonce         = nNonce;
1060        return block;
1061    }
1062
1063    uint256 GetBlockHash() const
1064    {
1065        return *phashBlock;
1066    }
1067
1068    int64 GetBlockTime() const
1069    {
1070        return (int64)nTime;
1071    }
1072
1073    CBigNum GetBlockWork() const
1074    {
1075        CBigNum bnTarget;
1076        bnTarget.SetCompact(nBits);
1077        if (bnTarget <= 0)
1078            return 0;
1079        return (CBigNum(1)<<256) / (bnTarget+1);
1080    }
1081
1082    bool IsInMainChain() const
1083    {
1084        return (pnext || this == pindexBest);
1085    }
1086
1087    bool CheckIndex() const
1088    {
1089        return CheckProofOfWork(GetBlockHash(), nBits);
1090    }
1091
1092    bool EraseBlockFromDisk()
1093    {
1094        // Open history file
1095        CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1096        if (!fileout)
1097            return false;
1098
1099        // Overwrite with empty null block
1100        CBlock block;
1101        block.SetNull();
1102        fileout << block;
1103
1104        return true;
1105    }
1106
1107    enum { nMedianTimeSpan=11 };
1108
1109    int64 GetMedianTimePast() const
1110    {
1111        int64 pmedian[nMedianTimeSpan];
1112        int64* pbegin = &pmedian[nMedianTimeSpan];
1113        int64* pend = &pmedian[nMedianTimeSpan];
1114
1115        const CBlockIndex* pindex = this;
1116        for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1117            *(--pbegin) = pindex->GetBlockTime();
1118
1119        std::sort(pbegin, pend);
1120        return pbegin[(pend - pbegin)/2];
1121    }
1122
1123    int64 GetMedianTime() const
1124    {
1125        const CBlockIndex* pindex = this;
1126        for (int i = 0; i < nMedianTimeSpan/2; i++)
1127        {
1128            if (!pindex->pnext)
1129                return GetBlockTime();
1130            pindex = pindex->pnext;
1131        }
1132        return pindex->GetMedianTimePast();
1133    }
1134
1135
1136
1137    std::string ToString() const
1138    {
1139        return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1140            pprev, pnext, nFile, nBlockPos, nHeight,
1141            hashMerkleRoot.ToString().c_str(),
1142            GetBlockHash().ToString().c_str());
1143    }
1144
1145    void print() const
1146    {
1147        printf("%s\n", ToString().c_str());
1148    }
1149};
1150
1151
1152
1153//
1154// Used to marshal pointers into hashes for db storage.
1155//
1156class CDiskBlockIndex : public CBlockIndex
1157{
1158public:
1159    uint256 hashPrev;
1160    uint256 hashNext;
1161
1162    CDiskBlockIndex()
1163    {
1164        hashPrev = 0;
1165        hashNext = 0;
1166    }
1167
1168    explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1169    {
1170        hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1171        hashNext = (pnext ? pnext->GetBlockHash() : 0);
1172    }
1173
1174    IMPLEMENT_SERIALIZE
1175    (
1176        if (!(nType & SER_GETHASH))
1177            READWRITE(nVersion);
1178
1179        READWRITE(hashNext);
1180        READWRITE(nFile);
1181        READWRITE(nBlockPos);
1182        READWRITE(nHeight);
1183
1184        // block header
1185        READWRITE(this->nVersion);
1186        READWRITE(hashPrev);
1187        READWRITE(hashMerkleRoot);
1188        READWRITE(nTime);
1189        READWRITE(nBits);
1190        READWRITE(nNonce);
1191    )
1192
1193    uint256 GetBlockHash() const
1194    {
1195        CBlock block;
1196        block.nVersion        = nVersion;
1197        block.hashPrevBlock   = hashPrev;
1198        block.hashMerkleRoot  = hashMerkleRoot;
1199        block.nTime           = nTime;
1200        block.nBits           = nBits;
1201        block.nNonce          = nNonce;
1202        return block.GetHash();
1203    }
1204
1205
1206    std::string ToString() const
1207    {
1208        std::string str = "CDiskBlockIndex(";
1209        str += CBlockIndex::ToString();
1210        str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1211            GetBlockHash().ToString().c_str(),
1212            hashPrev.ToString().c_str(),
1213            hashNext.ToString().c_str());
1214        return str;
1215    }
1216
1217    void print() const
1218    {
1219        printf("%s\n", ToString().c_str());
1220    }
1221};
1222
1223
1224
1225
1226
1227
1228
1229
1230//
1231// Describes a place in the block chain to another node such that if the
1232// other node doesn't have the same branch, it can find a recent common trunk.
1233// The further back it is, the further before the fork it may be.
1234//
1235class CBlockLocator
1236{
1237protected:
1238    std::vector<uint256> vHave;
1239public:
1240
1241    CBlockLocator()
1242    {
1243    }
1244
1245    explicit CBlockLocator(const CBlockIndex* pindex)
1246    {
1247        Set(pindex);
1248    }
1249
1250    explicit CBlockLocator(uint256 hashBlock)
1251    {
1252        std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1253        if (mi != mapBlockIndex.end())
1254            Set((*mi).second);
1255    }
1256
1257    IMPLEMENT_SERIALIZE
1258    (
1259        if (!(nType & SER_GETHASH))
1260            READWRITE(nVersion);
1261        READWRITE(vHave);
1262    )
1263
1264    void SetNull()
1265    {
1266        vHave.clear();
1267    }
1268
1269    bool IsNull()
1270    {
1271        return vHave.empty();
1272    }
1273
1274    void Set(const CBlockIndex* pindex)
1275    {
1276        vHave.clear();
1277        int nStep = 1;
1278        while (pindex)
1279        {
1280            vHave.push_back(pindex->GetBlockHash());
1281
1282            // Exponentially larger steps back
1283            for (int i = 0; pindex && i < nStep; i++)
1284                pindex = pindex->pprev;
1285            if (vHave.size() > 10)
1286                nStep *= 2;
1287        }
1288        vHave.push_back(hashGenesisBlock);
1289    }
1290
1291    int GetDistanceBack()
1292    {
1293        // Retrace how far back it was in the sender's branch
1294        int nDistance = 0;
1295        int nStep = 1;
1296        BOOST_FOREACH(const uint256& hash, vHave)
1297        {
1298            std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1299            if (mi != mapBlockIndex.end())
1300            {
1301                CBlockIndex* pindex = (*mi).second;
1302                if (pindex->IsInMainChain())
1303                    return nDistance;
1304            }
1305            nDistance += nStep;
1306            if (nDistance > 10)
1307                nStep *= 2;
1308        }
1309        return nDistance;
1310    }
1311
1312    CBlockIndex* GetBlockIndex()
1313    {
1314        // Find the first block the caller has in the main chain
1315        BOOST_FOREACH(const uint256& hash, vHave)
1316        {
1317            std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1318            if (mi != mapBlockIndex.end())
1319            {
1320                CBlockIndex* pindex = (*mi).second;
1321                if (pindex->IsInMainChain())
1322                    return pindex;
1323            }
1324        }
1325        return pindexGenesisBlock;
1326    }
1327
1328    uint256 GetBlockHash()
1329    {
1330        // Find the first block the caller has in the main chain
1331        BOOST_FOREACH(const uint256& hash, vHave)
1332        {
1333            std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1334            if (mi != mapBlockIndex.end())
1335            {
1336                CBlockIndex* pindex = (*mi).second;
1337                if (pindex->IsInMainChain())
1338                    return hash;
1339            }
1340        }
1341        return hashGenesisBlock;
1342    }
1343
1344    int GetHeight()
1345    {
1346        CBlockIndex* pindex = GetBlockIndex();
1347        if (!pindex)
1348            return 0;
1349        return pindex->nHeight;
1350    }
1351};
1352
1353#endif