Bitcoin v0.1.5 · 2009-02-04
main.h
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45class COutPoint;6class CInPoint;7class CDiskTxPos;8class CCoinBase;9class CTxIn;10class CTxOut;11class CTransaction;12class CBlock;13class CBlockIndex;14class CWalletTx;15class CKeyItem;1617static const unsigned int MAX_SIZE = 0x02000000;18static const int64 COIN = 100000000;19static const int64 CENT = 1000000;20static const int COINBASE_MATURITY = 100;2122static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);23242526272829extern CCriticalSection cs_main;30extern map<uint256, CBlockIndex*> mapBlockIndex;31extern const uint256 hashGenesisBlock;32extern CBlockIndex* pindexGenesisBlock;33extern int nBestHeight;34extern uint256 hashBestChain;35extern CBlockIndex* pindexBest;36extern unsigned int nTransactionsUpdated;37extern string strSetDataDir;38extern int nDropMessagesTest;3940// Settings41extern int fGenerateBitcoins;42extern int64 nTransactionFee;43extern CAddress addrIncoming;4445464748495051string GetAppDir();52bool CheckDiskSpace(int64 nAdditionalBytes=0);53FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");54FILE* AppendBlockFile(unsigned int& nFileRet);55bool AddKey(const CKey& key);56vector<unsigned char> GenerateNewKey();57bool AddToWallet(const CWalletTx& wtxIn);58void ReacceptWalletTransactions();59void RelayWalletTransactions();60bool LoadBlockIndex(bool fAllowNew=true);61void PrintBlockTree();62bool BitcoinMiner();63bool ProcessMessages(CNode* pfrom);64bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);65bool SendMessages(CNode* pto);66int64 GetBalance();67bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& txNew, int64& nFeeRequiredRet);68bool CommitTransactionSpent(const CWalletTx& wtxNew);69bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);707172737475767778798081class CDiskTxPos82{83public:84 unsigned int nFile;85 unsigned int nBlockPos;86 unsigned int nTxPos;8788 CDiskTxPos()89 {90 SetNull();91 }9293 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)94 {95 nFile = nFileIn;96 nBlockPos = nBlockPosIn;97 nTxPos = nTxPosIn;98 }99100 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )101 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }102 bool IsNull() const { return (nFile == -1); }103104 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)105 {106 return (a.nFile == b.nFile &&107 a.nBlockPos == b.nBlockPos &&108 a.nTxPos == b.nTxPos);109 }110111 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)112 {113 return !(a == b);114 }115116 string ToString() const117 {118 if (IsNull())119 return strprintf("null");120 else121 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);122 }123124 void print() const125 {126 printf("%s", ToString().c_str());127 }128};129130131132133class CInPoint134{135public:136 CTransaction* ptx;137 unsigned int n;138139 CInPoint() { SetNull(); }140 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }141 void SetNull() { ptx = NULL; n = -1; }142 bool IsNull() const { return (ptx == NULL && n == -1); }143};144145146147148class COutPoint149{150public:151 uint256 hash;152 unsigned int n;153154 COutPoint() { SetNull(); }155 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }156 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )157 void SetNull() { hash = 0; n = -1; }158 bool IsNull() const { return (hash == 0 && n == -1); }159160 friend bool operator<(const COutPoint& a, const COutPoint& b)161 {162 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));163 }164165 friend bool operator==(const COutPoint& a, const COutPoint& b)166 {167 return (a.hash == b.hash && a.n == b.n);168 }169170 friend bool operator!=(const COutPoint& a, const COutPoint& b)171 {172 return !(a == b);173 }174175 string ToString() const176 {177 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);178 }179180 void print() const181 {182 printf("%s\n", ToString().c_str());183 }184};185186187188189//190// An input of a transaction. It contains the location of the previous191// transaction's output that it claims and a signature that matches the192// output's public key.193//194class CTxIn195{196public:197 COutPoint prevout;198 CScript scriptSig;199 unsigned int nSequence;200201 CTxIn()202 {203 nSequence = UINT_MAX;204 }205206 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)207 {208 prevout = prevoutIn;209 scriptSig = scriptSigIn;210 nSequence = nSequenceIn;211 }212213 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)214 {215 prevout = COutPoint(hashPrevTx, nOut);216 scriptSig = scriptSigIn;217 nSequence = nSequenceIn;218 }219220 IMPLEMENT_SERIALIZE221 (222 READWRITE(prevout);223 READWRITE(scriptSig);224 READWRITE(nSequence);225 )226227 bool IsFinal() const228 {229 return (nSequence == UINT_MAX);230 }231232 friend bool operator==(const CTxIn& a, const CTxIn& b)233 {234 return (a.prevout == b.prevout &&235 a.scriptSig == b.scriptSig &&236 a.nSequence == b.nSequence);237 }238239 friend bool operator!=(const CTxIn& a, const CTxIn& b)240 {241 return !(a == b);242 }243244 string ToString() const245 {246 string str;247 str += strprintf("CTxIn(");248 str += prevout.ToString();249 if (prevout.IsNull())250 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());251 else252 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());253 if (nSequence != UINT_MAX)254 str += strprintf(", nSequence=%u", nSequence);255 str += ")";256 return str;257 }258259 void print() const260 {261 printf("%s\n", ToString().c_str());262 }263264 bool IsMine() const;265 int64 GetDebit() const;266};267268269270271//272// An output of a transaction. It contains the public key that the next input273// must be able to sign with to claim it.274//275class CTxOut276{277public:278 int64 nValue;279 CScript scriptPubKey;280281public:282 CTxOut()283 {284 SetNull();285 }286287 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)288 {289 nValue = nValueIn;290 scriptPubKey = scriptPubKeyIn;291 }292293 IMPLEMENT_SERIALIZE294 (295 READWRITE(nValue);296 READWRITE(scriptPubKey);297 )298299 void SetNull()300 {301 nValue = -1;302 scriptPubKey.clear();303 }304305 bool IsNull()306 {307 return (nValue == -1);308 }309310 uint256 GetHash() const311 {312 return SerializeHash(*this);313 }314315 bool IsMine() const316 {317 return ::IsMine(scriptPubKey);318 }319320 int64 GetCredit() const321 {322 if (IsMine())323 return nValue;324 return 0;325 }326327 friend bool operator==(const CTxOut& a, const CTxOut& b)328 {329 return (a.nValue == b.nValue &&330 a.scriptPubKey == b.scriptPubKey);331 }332333 friend bool operator!=(const CTxOut& a, const CTxOut& b)334 {335 return !(a == b);336 }337338 string ToString() const339 {340 if (scriptPubKey.size() < 6)341 return "CTxOut(error)";342 return strprintf("CTxOut(nValue=%I64d.%08I64d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());343 }344345 void print() const346 {347 printf("%s\n", ToString().c_str());348 }349};350351352353354//355// The basic transaction that is broadcasted on the network and contained in356// blocks. A transaction can contain multiple inputs and outputs.357//358class CTransaction359{360public:361 int nVersion;362 vector<CTxIn> vin;363 vector<CTxOut> vout;364 int nLockTime;365366367 CTransaction()368 {369 SetNull();370 }371372 IMPLEMENT_SERIALIZE373 (374 READWRITE(this->nVersion);375 nVersion = this->nVersion;376 READWRITE(vin);377 READWRITE(vout);378 READWRITE(nLockTime);379 )380381 void SetNull()382 {383 nVersion = 1;384 vin.clear();385 vout.clear();386 nLockTime = 0;387 }388389 bool IsNull() const390 {391 return (vin.empty() && vout.empty());392 }393394 uint256 GetHash() const395 {396 return SerializeHash(*this);397 }398399 bool IsFinal() const400 {401 if (nLockTime == 0 || nLockTime < nBestHeight)402 return true;403 foreach(const CTxIn& txin, vin)404 if (!txin.IsFinal())405 return false;406 return true;407 }408409 bool IsNewerThan(const CTransaction& old) const410 {411 if (vin.size() != old.vin.size())412 return false;413 for (int i = 0; i < vin.size(); i++)414 if (vin[i].prevout != old.vin[i].prevout)415 return false;416417 bool fNewer = false;418 unsigned int nLowest = UINT_MAX;419 for (int i = 0; i < vin.size(); i++)420 {421 if (vin[i].nSequence != old.vin[i].nSequence)422 {423 if (vin[i].nSequence <= nLowest)424 {425 fNewer = false;426 nLowest = vin[i].nSequence;427 }428 if (old.vin[i].nSequence < nLowest)429 {430 fNewer = true;431 nLowest = old.vin[i].nSequence;432 }433 }434 }435 return fNewer;436 }437438 bool IsCoinBase() const439 {440 return (vin.size() == 1 && vin[0].prevout.IsNull());441 }442443 bool CheckTransaction() const444 {445 // Basic checks that don't depend on any context446 if (vin.empty() || vout.empty())447 return error("CTransaction::CheckTransaction() : vin or vout empty");448449 // Check for negative values450 foreach(const CTxOut& txout, vout)451 if (txout.nValue < 0)452 return error("CTransaction::CheckTransaction() : txout.nValue negative");453454 if (IsCoinBase())455 {456 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)457 return error("CTransaction::CheckTransaction() : coinbase script size");458 }459 else460 {461 foreach(const CTxIn& txin, vin)462 if (txin.prevout.IsNull())463 return error("CTransaction::CheckTransaction() : prevout is null");464 }465466 return true;467 }468469 bool IsMine() const470 {471 foreach(const CTxOut& txout, vout)472 if (txout.IsMine())473 return true;474 return false;475 }476477 int64 GetDebit() const478 {479 int64 nDebit = 0;480 foreach(const CTxIn& txin, vin)481 nDebit += txin.GetDebit();482 return nDebit;483 }484485 int64 GetCredit() const486 {487 int64 nCredit = 0;488 foreach(const CTxOut& txout, vout)489 nCredit += txout.GetCredit();490 return nCredit;491 }492493 int64 GetValueOut() const494 {495 int64 nValueOut = 0;496 foreach(const CTxOut& txout, vout)497 {498 if (txout.nValue < 0)499 throw runtime_error("CTransaction::GetValueOut() : negative value");500 nValueOut += txout.nValue;501 }502 return nValueOut;503 }504505 int64 GetMinFee(bool fDiscount=false) const506 {507 // Base fee is 1 cent per kilobyte508 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);509 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;510511 // First 100 transactions in a block are free512 if (fDiscount && nBytes < 10000)513 nMinFee = 0;514515 // To limit dust spam, require a 0.01 fee if any output is less than 0.01516 if (nMinFee < CENT)517 foreach(const CTxOut& txout, vout)518 if (txout.nValue < CENT)519 nMinFee = CENT;520521 return nMinFee;522 }523524525526 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)527 {528 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");529 if (!filein)530 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");531532 // Read transaction533 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)534 return error("CTransaction::ReadFromDisk() : fseek failed");535 filein >> *this;536537 // Return file pointer538 if (pfileRet)539 {540 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)541 return error("CTransaction::ReadFromDisk() : second fseek failed");542 *pfileRet = filein.release();543 }544 return true;545 }546547548 friend bool operator==(const CTransaction& a, const CTransaction& b)549 {550 return (a.nVersion == b.nVersion &&551 a.vin == b.vin &&552 a.vout == b.vout &&553 a.nLockTime == b.nLockTime);554 }555556 friend bool operator!=(const CTransaction& a, const CTransaction& b)557 {558 return !(a == b);559 }560561562 string ToString() const563 {564 string str;565 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",566 GetHash().ToString().substr(0,6).c_str(),567 nVersion,568 vin.size(),569 vout.size(),570 nLockTime);571 for (int i = 0; i < vin.size(); i++)572 str += " " + vin[i].ToString() + "\n";573 for (int i = 0; i < vout.size(); i++)574 str += " " + vout[i].ToString() + "\n";575 return str;576 }577578 void print() const579 {580 printf("%s", ToString().c_str());581 }582583584585 bool DisconnectInputs(CTxDB& txdb);586 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);587 bool ClientConnectInputs();588589 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);590591 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)592 {593 CTxDB txdb("r");594 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);595 }596597protected:598 bool AddToMemoryPool();599public:600 bool RemoveFromMemoryPool();601};602603604605606607//608// A transaction with a merkle branch linking it to the block chain609//610class CMerkleTx : public CTransaction611{612public:613 uint256 hashBlock;614 vector<uint256> vMerkleBranch;615 int nIndex;616617 // memory only618 mutable bool fMerkleVerified;619620621 CMerkleTx()622 {623 Init();624 }625626 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)627 {628 Init();629 }630631 void Init()632 {633 hashBlock = 0;634 nIndex = -1;635 fMerkleVerified = false;636 }637638 int64 GetCredit() const639 {640 // Must wait until coinbase is safely deep enough in the chain before valuing it641 if (IsCoinBase() && GetBlocksToMaturity() > 0)642 return 0;643 return CTransaction::GetCredit();644 }645646 IMPLEMENT_SERIALIZE647 (648 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);649 nVersion = this->nVersion;650 READWRITE(hashBlock);651 READWRITE(vMerkleBranch);652 READWRITE(nIndex);653 )654655656 int SetMerkleBranch(const CBlock* pblock=NULL);657 int GetDepthInMainChain() const;658 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }659 int GetBlocksToMaturity() const;660 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);661 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }662};663664665666667//668// A transaction with a bunch of additional info that only the owner cares669// about. It includes any unrecorded transactions needed to link it back670// to the block chain.671//672class CWalletTx : public CMerkleTx673{674public:675 vector<CMerkleTx> vtxPrev;676 map<string, string> mapValue;677 vector<pair<string, string> > vOrderForm;678 unsigned int fTimeReceivedIsTxTime;679 unsigned int nTimeReceived; // time received by this node680 char fFromMe;681 char fSpent;682 //// probably need to sign the order info so know it came from payer683684 // memory only685 mutable unsigned int nTimeDisplayed;686687688 CWalletTx()689 {690 Init();691 }692693 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)694 {695 Init();696 }697698 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)699 {700 Init();701 }702703 void Init()704 {705 fTimeReceivedIsTxTime = false;706 nTimeReceived = 0;707 fFromMe = false;708 fSpent = false;709 nTimeDisplayed = 0;710 }711712 IMPLEMENT_SERIALIZE713 (714 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);715 nVersion = this->nVersion;716 READWRITE(vtxPrev);717 READWRITE(mapValue);718 READWRITE(vOrderForm);719 READWRITE(fTimeReceivedIsTxTime);720 READWRITE(nTimeReceived);721 READWRITE(fFromMe);722 READWRITE(fSpent);723 )724725 bool WriteToDisk()726 {727 return CWalletDB().WriteTx(GetHash(), *this);728 }729730731 int64 GetTxTime() const;732733 void AddSupportingTransactions(CTxDB& txdb);734735 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);736 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }737738 void RelayWalletTransaction(CTxDB& txdb);739 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }740};741742743744745//746// A txdb record that contains the disk location of a transaction and the747// locations of transactions that spend its outputs. vSpent is really only748// used as a flag, but having the location is very helpful for debugging.749//750class CTxIndex751{752public:753 CDiskTxPos pos;754 vector<CDiskTxPos> vSpent;755756 CTxIndex()757 {758 SetNull();759 }760761 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)762 {763 pos = posIn;764 vSpent.resize(nOutputs);765 }766767 IMPLEMENT_SERIALIZE768 (769 if (!(nType & SER_GETHASH))770 READWRITE(nVersion);771 READWRITE(pos);772 READWRITE(vSpent);773 )774775 void SetNull()776 {777 pos.SetNull();778 vSpent.clear();779 }780781 bool IsNull()782 {783 return pos.IsNull();784 }785786 friend bool operator==(const CTxIndex& a, const CTxIndex& b)787 {788 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())789 return false;790 for (int i = 0; i < a.vSpent.size(); i++)791 if (a.vSpent[i] != b.vSpent[i])792 return false;793 return true;794 }795796 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)797 {798 return !(a == b);799 }800};801802803804805806//807// Nodes collect new transactions into a block, hash them into a hash tree,808// and scan through nonce values to make the block's hash satisfy proof-of-work809// requirements. When they solve the proof-of-work, they broadcast the block810// to everyone and the block is added to the block chain. The first transaction811// in the block is a special one that creates a new coin owned by the creator812// of the block.813//814// Blocks are appended to blk0001.dat files on disk. Their location on disk815// is indexed by CBlockIndex objects in memory.816//817class CBlock818{819public:820 // header821 int nVersion;822 uint256 hashPrevBlock;823 uint256 hashMerkleRoot;824 unsigned int nTime;825 unsigned int nBits;826 unsigned int nNonce;827828 // network and disk829 vector<CTransaction> vtx;830831 // memory only832 mutable vector<uint256> vMerkleTree;833834835 CBlock()836 {837 SetNull();838 }839840 IMPLEMENT_SERIALIZE841 (842 READWRITE(this->nVersion);843 nVersion = this->nVersion;844 READWRITE(hashPrevBlock);845 READWRITE(hashMerkleRoot);846 READWRITE(nTime);847 READWRITE(nBits);848 READWRITE(nNonce);849850 // ConnectBlock depends on vtx being last so it can calculate offset851 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))852 READWRITE(vtx);853 else if (fRead)854 const_cast<CBlock*>(this)->vtx.clear();855 )856857 void SetNull()858 {859 nVersion = 1;860 hashPrevBlock = 0;861 hashMerkleRoot = 0;862 nTime = 0;863 nBits = 0;864 nNonce = 0;865 vtx.clear();866 vMerkleTree.clear();867 }868869 bool IsNull() const870 {871 return (nBits == 0);872 }873874 uint256 GetHash() const875 {876 return Hash(BEGIN(nVersion), END(nNonce));877 }878879880 uint256 BuildMerkleTree() const881 {882 vMerkleTree.clear();883 foreach(const CTransaction& tx, vtx)884 vMerkleTree.push_back(tx.GetHash());885 int j = 0;886 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)887 {888 for (int i = 0; i < nSize; i += 2)889 {890 int i2 = min(i+1, nSize-1);891 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),892 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));893 }894 j += nSize;895 }896 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());897 }898899 vector<uint256> GetMerkleBranch(int nIndex) const900 {901 if (vMerkleTree.empty())902 BuildMerkleTree();903 vector<uint256> vMerkleBranch;904 int j = 0;905 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)906 {907 int i = min(nIndex^1, nSize-1);908 vMerkleBranch.push_back(vMerkleTree[j+i]);909 nIndex >>= 1;910 j += nSize;911 }912 return vMerkleBranch;913 }914915 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)916 {917 if (nIndex == -1)918 return 0;919 foreach(const uint256& otherside, vMerkleBranch)920 {921 if (nIndex & 1)922 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));923 else924 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));925 nIndex >>= 1;926 }927 return hash;928 }929930931 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)932 {933 // Open history file to append934 CAutoFile fileout = AppendBlockFile(nFileRet);935 if (!fileout)936 return error("CBlock::WriteToDisk() : AppendBlockFile failed");937 if (!fWriteTransactions)938 fileout.nType |= SER_BLOCKHEADERONLY;939940 // Write index header941 unsigned int nSize = fileout.GetSerializeSize(*this);942 fileout << FLATDATA(pchMessageStart) << nSize;943944 // Write block945 nBlockPosRet = ftell(fileout);946 if (nBlockPosRet == -1)947 return error("CBlock::WriteToDisk() : ftell failed");948 fileout << *this;949950 return true;951 }952953 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)954 {955 SetNull();956957 // Open history file to read958 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");959 if (!filein)960 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");961 if (!fReadTransactions)962 filein.nType |= SER_BLOCKHEADERONLY;963964 // Read block965 filein >> *this;966967 // Check the header968 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)969 return error("CBlock::ReadFromDisk() : nBits errors in block header");970 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())971 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");972973 return true;974 }975976977978 void print() const979 {980 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",981 GetHash().ToString().substr(0,14).c_str(),982 nVersion,983 hashPrevBlock.ToString().substr(0,14).c_str(),984 hashMerkleRoot.ToString().substr(0,6).c_str(),985 nTime, nBits, nNonce,986 vtx.size());987 for (int i = 0; i < vtx.size(); i++)988 {989 printf(" ");990 vtx[i].print();991 }992 printf(" vMerkleTree: ");993 for (int i = 0; i < vMerkleTree.size(); i++)994 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());995 printf("\n");996 }997998999 int64 GetBlockValue(int64 nFees) const;1000 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);1001 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);1002 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions);1003 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);1004 bool CheckBlock() const;1005 bool AcceptBlock();1006};1007100810091010101110121013//1014// The block chain is a tree shaped structure starting with the1015// genesis block at the root, with each block potentially having multiple1016// candidates to be the next block. pprev and pnext link a path through the1017// main/longest chain. A blockindex may have multiple pprev pointing back1018// to it, but pnext will only point forward to the longest branch, or will1019// be null if the block is not part of the longest chain.1020//1021class CBlockIndex1022{1023public:1024 const uint256* phashBlock;1025 CBlockIndex* pprev;1026 CBlockIndex* pnext;1027 unsigned int nFile;1028 unsigned int nBlockPos;1029 int nHeight;10301031 // block header1032 int nVersion;1033 uint256 hashMerkleRoot;1034 unsigned int nTime;1035 unsigned int nBits;1036 unsigned int nNonce;103710381039 CBlockIndex()1040 {1041 phashBlock = NULL;1042 pprev = NULL;1043 pnext = NULL;1044 nFile = 0;1045 nBlockPos = 0;1046 nHeight = 0;10471048 nVersion = 0;1049 hashMerkleRoot = 0;1050 nTime = 0;1051 nBits = 0;1052 nNonce = 0;1053 }10541055 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)1056 {1057 phashBlock = NULL;1058 pprev = NULL;1059 pnext = NULL;1060 nFile = nFileIn;1061 nBlockPos = nBlockPosIn;1062 nHeight = 0;10631064 nVersion = block.nVersion;1065 hashMerkleRoot = block.hashMerkleRoot;1066 nTime = block.nTime;1067 nBits = block.nBits;1068 nNonce = block.nNonce;1069 }10701071 uint256 GetBlockHash() const1072 {1073 return *phashBlock;1074 }10751076 bool IsInMainChain() const1077 {1078 return (pnext || this == pindexBest);1079 }10801081 bool EraseBlockFromDisk()1082 {1083 // Open history file1084 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");1085 if (!fileout)1086 return false;10871088 // Overwrite with empty null block1089 CBlock block;1090 block.SetNull();1091 fileout << block;10921093 return true;1094 }10951096 enum { nMedianTimeSpan=11 };10971098 int64 GetMedianTimePast() const1099 {1100 unsigned int pmedian[nMedianTimeSpan];1101 unsigned int* pbegin = &pmedian[nMedianTimeSpan];1102 unsigned int* pend = &pmedian[nMedianTimeSpan];11031104 const CBlockIndex* pindex = this;1105 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)1106 *(--pbegin) = pindex->nTime;11071108 sort(pbegin, pend);1109 return pbegin[(pend - pbegin)/2];1110 }11111112 int64 GetMedianTime() const1113 {1114 const CBlockIndex* pindex = this;1115 for (int i = 0; i < nMedianTimeSpan/2; i++)1116 {1117 if (!pindex->pnext)1118 return nTime;1119 pindex = pindex->pnext;1120 }1121 return pindex->GetMedianTimePast();1122 }1123112411251126 string ToString() const1127 {1128 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",1129 pprev, pnext, nFile, nBlockPos, nHeight,1130 hashMerkleRoot.ToString().substr(0,6).c_str(),1131 GetBlockHash().ToString().substr(0,14).c_str());1132 }11331134 void print() const1135 {1136 printf("%s\n", ToString().c_str());1137 }1138};1139114011411142//1143// Used to marshal pointers into hashes for db storage.1144//1145class CDiskBlockIndex : public CBlockIndex1146{1147public:1148 uint256 hashPrev;1149 uint256 hashNext;11501151 CDiskBlockIndex()1152 {1153 hashPrev = 0;1154 hashNext = 0;1155 }11561157 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)1158 {1159 hashPrev = (pprev ? pprev->GetBlockHash() : 0);1160 hashNext = (pnext ? pnext->GetBlockHash() : 0);1161 }11621163 IMPLEMENT_SERIALIZE1164 (1165 if (!(nType & SER_GETHASH))1166 READWRITE(nVersion);11671168 READWRITE(hashNext);1169 READWRITE(nFile);1170 READWRITE(nBlockPos);1171 READWRITE(nHeight);11721173 // block header1174 READWRITE(this->nVersion);1175 READWRITE(hashPrev);1176 READWRITE(hashMerkleRoot);1177 READWRITE(nTime);1178 READWRITE(nBits);1179 READWRITE(nNonce);1180 )11811182 uint256 GetBlockHash() const1183 {1184 CBlock block;1185 block.nVersion = nVersion;1186 block.hashPrevBlock = hashPrev;1187 block.hashMerkleRoot = hashMerkleRoot;1188 block.nTime = nTime;1189 block.nBits = nBits;1190 block.nNonce = nNonce;1191 return block.GetHash();1192 }119311941195 string ToString() const1196 {1197 string str = "CDiskBlockIndex(";1198 str += CBlockIndex::ToString();1199 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",1200 GetBlockHash().ToString().c_str(),1201 hashPrev.ToString().substr(0,14).c_str(),1202 hashNext.ToString().substr(0,14).c_str());1203 return str;1204 }12051206 void print() const1207 {1208 printf("%s\n", ToString().c_str());1209 }1210};121112121213121412151216121712181219//1220// Describes a place in the block chain to another node such that if the1221// other node doesn't have the same branch, it can find a recent common trunk.1222// The further back it is, the further before the fork it may be.1223//1224class CBlockLocator1225{1226protected:1227 vector<uint256> vHave;1228public:12291230 CBlockLocator()1231 {1232 }12331234 explicit CBlockLocator(const CBlockIndex* pindex)1235 {1236 Set(pindex);1237 }12381239 explicit CBlockLocator(uint256 hashBlock)1240 {1241 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);1242 if (mi != mapBlockIndex.end())1243 Set((*mi).second);1244 }12451246 IMPLEMENT_SERIALIZE1247 (1248 if (!(nType & SER_GETHASH))1249 READWRITE(nVersion);1250 READWRITE(vHave);1251 )12521253 void Set(const CBlockIndex* pindex)1254 {1255 vHave.clear();1256 int nStep = 1;1257 while (pindex)1258 {1259 vHave.push_back(pindex->GetBlockHash());12601261 // Exponentially larger steps back1262 for (int i = 0; pindex && i < nStep; i++)1263 pindex = pindex->pprev;1264 if (vHave.size() > 10)1265 nStep *= 2;1266 }1267 vHave.push_back(hashGenesisBlock);1268 }12691270 CBlockIndex* GetBlockIndex()1271 {1272 // Find the first block the caller has in the main chain1273 foreach(const uint256& hash, vHave)1274 {1275 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1276 if (mi != mapBlockIndex.end())1277 {1278 CBlockIndex* pindex = (*mi).second;1279 if (pindex->IsInMainChain())1280 return pindex;1281 }1282 }1283 return pindexGenesisBlock;1284 }12851286 uint256 GetBlockHash()1287 {1288 // Find the first block the caller has in the main chain1289 foreach(const uint256& hash, vHave)1290 {1291 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1292 if (mi != mapBlockIndex.end())1293 {1294 CBlockIndex* pindex = (*mi).second;1295 if (pindex->IsInMainChain())1296 return hash;1297 }1298 }1299 return hashGenesisBlock;1300 }13011302 int GetHeight()1303 {1304 CBlockIndex* pindex = GetBlockIndex();1305 if (!pindex)1306 return 0;1307 return pindex->nHeight;1308 }1309};1310131113121313131413151316131713181319132013211322extern map<uint256, CTransaction> mapTransactions;1323extern map<uint256, CWalletTx> mapWallet;1324extern vector<pair<uint256, bool> > vWalletUpdated;1325extern CCriticalSection cs_mapWallet;1326extern map<vector<unsigned char>, CPrivKey> mapKeys;1327extern map<uint160, vector<unsigned char> > mapPubKeys;1328extern CCriticalSection cs_mapKeys;1329extern CKey keyUser;
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
