Bitcoin v0.2.0 · 2009-12-16
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 map<uint256, int> mapRequestCount;38extern CCriticalSection cs_mapRequestCount;3940// Settings41extern int fGenerateBitcoins;42extern int64 nTransactionFee;43extern CAddress addrIncoming;44extern int fLimitProcessors;45extern int nLimitProcessors;4647484950515253bool CheckDiskSpace(int64 nAdditionalBytes=0);54FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");55FILE* AppendBlockFile(unsigned int& nFileRet);56bool AddKey(const CKey& key);57vector<unsigned char> GenerateNewKey();58bool AddToWallet(const CWalletTx& wtxIn);59void ReacceptWalletTransactions();60void RelayWalletTransactions();61bool LoadBlockIndex(bool fAllowNew=true);62void PrintBlockTree();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& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);68bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key);69bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);70void GenerateBitcoins(bool fGenerate);71void ThreadBitcoinMiner(void* parg);72void BitcoinMiner();73747576777879808182838485class CDiskTxPos86{87public:88 unsigned int nFile;89 unsigned int nBlockPos;90 unsigned int nTxPos;9192 CDiskTxPos()93 {94 SetNull();95 }9697 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)98 {99 nFile = nFileIn;100 nBlockPos = nBlockPosIn;101 nTxPos = nTxPosIn;102 }103104 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )105 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }106 bool IsNull() const { return (nFile == -1); }107108 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)109 {110 return (a.nFile == b.nFile &&111 a.nBlockPos == b.nBlockPos &&112 a.nTxPos == b.nTxPos);113 }114115 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)116 {117 return !(a == b);118 }119120 string ToString() const121 {122 if (IsNull())123 return strprintf("null");124 else125 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);126 }127128 void print() const129 {130 printf("%s", ToString().c_str());131 }132};133134135136137class CInPoint138{139public:140 CTransaction* ptx;141 unsigned int n;142143 CInPoint() { SetNull(); }144 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }145 void SetNull() { ptx = NULL; n = -1; }146 bool IsNull() const { return (ptx == NULL && n == -1); }147};148149150151152class COutPoint153{154public:155 uint256 hash;156 unsigned int n;157158 COutPoint() { SetNull(); }159 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }160 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )161 void SetNull() { hash = 0; n = -1; }162 bool IsNull() const { return (hash == 0 && n == -1); }163164 friend bool operator<(const COutPoint& a, const COutPoint& b)165 {166 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));167 }168169 friend bool operator==(const COutPoint& a, const COutPoint& b)170 {171 return (a.hash == b.hash && a.n == b.n);172 }173174 friend bool operator!=(const COutPoint& a, const COutPoint& b)175 {176 return !(a == b);177 }178179 string ToString() const180 {181 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);182 }183184 void print() const185 {186 printf("%s\n", ToString().c_str());187 }188};189190191192193//194// An input of a transaction. It contains the location of the previous195// transaction's output that it claims and a signature that matches the196// output's public key.197//198class CTxIn199{200public:201 COutPoint prevout;202 CScript scriptSig;203 unsigned int nSequence;204205 CTxIn()206 {207 nSequence = UINT_MAX;208 }209210 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)211 {212 prevout = prevoutIn;213 scriptSig = scriptSigIn;214 nSequence = nSequenceIn;215 }216217 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)218 {219 prevout = COutPoint(hashPrevTx, nOut);220 scriptSig = scriptSigIn;221 nSequence = nSequenceIn;222 }223224 IMPLEMENT_SERIALIZE225 (226 READWRITE(prevout);227 READWRITE(scriptSig);228 READWRITE(nSequence);229 )230231 bool IsFinal() const232 {233 return (nSequence == UINT_MAX);234 }235236 friend bool operator==(const CTxIn& a, const CTxIn& b)237 {238 return (a.prevout == b.prevout &&239 a.scriptSig == b.scriptSig &&240 a.nSequence == b.nSequence);241 }242243 friend bool operator!=(const CTxIn& a, const CTxIn& b)244 {245 return !(a == b);246 }247248 string ToString() const249 {250 string str;251 str += strprintf("CTxIn(");252 str += prevout.ToString();253 if (prevout.IsNull())254 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());255 else256 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());257 if (nSequence != UINT_MAX)258 str += strprintf(", nSequence=%u", nSequence);259 str += ")";260 return str;261 }262263 void print() const264 {265 printf("%s\n", ToString().c_str());266 }267268 bool IsMine() const;269 int64 GetDebit() const;270};271272273274275//276// An output of a transaction. It contains the public key that the next input277// must be able to sign with to claim it.278//279class CTxOut280{281public:282 int64 nValue;283 CScript scriptPubKey;284285public:286 CTxOut()287 {288 SetNull();289 }290291 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)292 {293 nValue = nValueIn;294 scriptPubKey = scriptPubKeyIn;295 }296297 IMPLEMENT_SERIALIZE298 (299 READWRITE(nValue);300 READWRITE(scriptPubKey);301 )302303 void SetNull()304 {305 nValue = -1;306 scriptPubKey.clear();307 }308309 bool IsNull()310 {311 return (nValue == -1);312 }313314 uint256 GetHash() const315 {316 return SerializeHash(*this);317 }318319 bool IsMine() const320 {321 return ::IsMine(scriptPubKey);322 }323324 int64 GetCredit() const325 {326 if (IsMine())327 return nValue;328 return 0;329 }330331 friend bool operator==(const CTxOut& a, const CTxOut& b)332 {333 return (a.nValue == b.nValue &&334 a.scriptPubKey == b.scriptPubKey);335 }336337 friend bool operator!=(const CTxOut& a, const CTxOut& b)338 {339 return !(a == b);340 }341342 string ToString() const343 {344 if (scriptPubKey.size() < 6)345 return "CTxOut(error)";346 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());347 }348349 void print() const350 {351 printf("%s\n", ToString().c_str());352 }353};354355356357358//359// The basic transaction that is broadcasted on the network and contained in360// blocks. A transaction can contain multiple inputs and outputs.361//362class CTransaction363{364public:365 int nVersion;366 vector<CTxIn> vin;367 vector<CTxOut> vout;368 unsigned int nLockTime;369370371 CTransaction()372 {373 SetNull();374 }375376 IMPLEMENT_SERIALIZE377 (378 READWRITE(this->nVersion);379 nVersion = this->nVersion;380 READWRITE(vin);381 READWRITE(vout);382 READWRITE(nLockTime);383 )384385 void SetNull()386 {387 nVersion = 1;388 vin.clear();389 vout.clear();390 nLockTime = 0;391 }392393 bool IsNull() const394 {395 return (vin.empty() && vout.empty());396 }397398 uint256 GetHash() const399 {400 return SerializeHash(*this);401 }402403 bool IsFinal(int64 nBlockTime=0) const404 {405 // Time based nLockTime implemented in 0.1.6,406 // do not use time based until most 0.1.5 nodes have upgraded.407 if (nLockTime == 0)408 return true;409 if (nBlockTime == 0)410 nBlockTime = GetAdjustedTime();411 if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))412 return true;413 foreach(const CTxIn& txin, vin)414 if (!txin.IsFinal())415 return false;416 return true;417 }418419 bool IsNewerThan(const CTransaction& old) const420 {421 if (vin.size() != old.vin.size())422 return false;423 for (int i = 0; i < vin.size(); i++)424 if (vin[i].prevout != old.vin[i].prevout)425 return false;426427 bool fNewer = false;428 unsigned int nLowest = UINT_MAX;429 for (int i = 0; i < vin.size(); i++)430 {431 if (vin[i].nSequence != old.vin[i].nSequence)432 {433 if (vin[i].nSequence <= nLowest)434 {435 fNewer = false;436 nLowest = vin[i].nSequence;437 }438 if (old.vin[i].nSequence < nLowest)439 {440 fNewer = true;441 nLowest = old.vin[i].nSequence;442 }443 }444 }445 return fNewer;446 }447448 bool IsCoinBase() const449 {450 return (vin.size() == 1 && vin[0].prevout.IsNull());451 }452453 bool CheckTransaction() const454 {455 // Basic checks that don't depend on any context456 if (vin.empty() || vout.empty())457 return error("CTransaction::CheckTransaction() : vin or vout empty");458459 // Check for negative values460 foreach(const CTxOut& txout, vout)461 if (txout.nValue < 0)462 return error("CTransaction::CheckTransaction() : txout.nValue negative");463464 if (IsCoinBase())465 {466 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)467 return error("CTransaction::CheckTransaction() : coinbase script size");468 }469 else470 {471 foreach(const CTxIn& txin, vin)472 if (txin.prevout.IsNull())473 return error("CTransaction::CheckTransaction() : prevout is null");474 }475476 return true;477 }478479 bool IsMine() const480 {481 foreach(const CTxOut& txout, vout)482 if (txout.IsMine())483 return true;484 return false;485 }486487 int64 GetDebit() const488 {489 int64 nDebit = 0;490 foreach(const CTxIn& txin, vin)491 nDebit += txin.GetDebit();492 return nDebit;493 }494495 int64 GetCredit() const496 {497 int64 nCredit = 0;498 foreach(const CTxOut& txout, vout)499 nCredit += txout.GetCredit();500 return nCredit;501 }502503 int64 GetValueOut() const504 {505 int64 nValueOut = 0;506 foreach(const CTxOut& txout, vout)507 {508 if (txout.nValue < 0)509 throw runtime_error("CTransaction::GetValueOut() : negative value");510 nValueOut += txout.nValue;511 }512 return nValueOut;513 }514515 int64 GetMinFee(unsigned int nBlockSize=1) const516 {517 // Base fee is 1 cent per kilobyte518 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);519 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;520521 // Transactions under 60K are free as long as block size is under 80K522 // (about 27,000bc if made of 50bc inputs)523 if (nBytes < 60000 && nBlockSize < 80000)524 nMinFee = 0;525526 // Transactions under 3K are free as long as block size is under 200K527 if (nBytes < 3000 && nBlockSize < 200000)528 nMinFee = 0;529530 // To limit dust spam, require a 0.01 fee if any output is less than 0.01531 if (nMinFee < CENT)532 foreach(const CTxOut& txout, vout)533 if (txout.nValue < CENT)534 nMinFee = CENT;535536 return nMinFee;537 }538539540541 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)542 {543 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");544 if (!filein)545 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");546547 // Read transaction548 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)549 return error("CTransaction::ReadFromDisk() : fseek failed");550 filein >> *this;551552 // Return file pointer553 if (pfileRet)554 {555 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)556 return error("CTransaction::ReadFromDisk() : second fseek failed");557 *pfileRet = filein.release();558 }559 return true;560 }561562563 friend bool operator==(const CTransaction& a, const CTransaction& b)564 {565 return (a.nVersion == b.nVersion &&566 a.vin == b.vin &&567 a.vout == b.vout &&568 a.nLockTime == b.nLockTime);569 }570571 friend bool operator!=(const CTransaction& a, const CTransaction& b)572 {573 return !(a == b);574 }575576577 string ToString() const578 {579 string str;580 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",581 GetHash().ToString().substr(0,6).c_str(),582 nVersion,583 vin.size(),584 vout.size(),585 nLockTime);586 for (int i = 0; i < vin.size(); i++)587 str += " " + vin[i].ToString() + "\n";588 for (int i = 0; i < vout.size(); i++)589 str += " " + vout[i].ToString() + "\n";590 return str;591 }592593 void print() const594 {595 printf("%s", ToString().c_str());596 }597598599600 bool DisconnectInputs(CTxDB& txdb);601 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);602 bool ClientConnectInputs();603604 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);605606 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)607 {608 CTxDB txdb("r");609 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);610 }611612protected:613 bool AddToMemoryPool();614public:615 bool RemoveFromMemoryPool();616};617618619620621622//623// A transaction with a merkle branch linking it to the block chain624//625class CMerkleTx : public CTransaction626{627public:628 uint256 hashBlock;629 vector<uint256> vMerkleBranch;630 int nIndex;631632 // memory only633 mutable bool fMerkleVerified;634 mutable bool fGetCreditCached;635 mutable int64 nGetCreditCached;636637638 CMerkleTx()639 {640 Init();641 }642643 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)644 {645 Init();646 }647648 void Init()649 {650 hashBlock = 0;651 nIndex = -1;652 fMerkleVerified = false;653 fGetCreditCached = false;654 nGetCreditCached = 0;655 }656657 IMPLEMENT_SERIALIZE658 (659 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);660 nVersion = this->nVersion;661 READWRITE(hashBlock);662 READWRITE(vMerkleBranch);663 READWRITE(nIndex);664 )665666 int64 GetCredit(bool fUseCache=false) const667 {668 // Must wait until coinbase is safely deep enough in the chain before valuing it669 if (IsCoinBase() && GetBlocksToMaturity() > 0)670 return 0;671672 // GetBalance can assume transactions in mapWallet won't change673 if (fUseCache && fGetCreditCached)674 return nGetCreditCached;675 nGetCreditCached = CTransaction::GetCredit();676 fGetCreditCached = true;677 return nGetCreditCached;678 }679680681 int SetMerkleBranch(const CBlock* pblock=NULL);682 int GetDepthInMainChain() const;683 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }684 int GetBlocksToMaturity() const;685 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);686 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }687};688689690691692//693// A transaction with a bunch of additional info that only the owner cares694// about. It includes any unrecorded transactions needed to link it back695// to the block chain.696//697class CWalletTx : public CMerkleTx698{699public:700 vector<CMerkleTx> vtxPrev;701 map<string, string> mapValue;702 vector<pair<string, string> > vOrderForm;703 unsigned int fTimeReceivedIsTxTime;704 unsigned int nTimeReceived; // time received by this node705 char fFromMe;706 char fSpent;707 //// probably need to sign the order info so know it came from payer708709 // memory only UI hints710 mutable unsigned int nTimeDisplayed;711 mutable int nLinesDisplayed;712713714 CWalletTx()715 {716 Init();717 }718719 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)720 {721 Init();722 }723724 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)725 {726 Init();727 }728729 void Init()730 {731 fTimeReceivedIsTxTime = false;732 nTimeReceived = 0;733 fFromMe = false;734 fSpent = false;735 nTimeDisplayed = 0;736 nLinesDisplayed = 0;737 }738739 IMPLEMENT_SERIALIZE740 (741 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);742 nVersion = this->nVersion;743 READWRITE(vtxPrev);744 READWRITE(mapValue);745 READWRITE(vOrderForm);746 READWRITE(fTimeReceivedIsTxTime);747 READWRITE(nTimeReceived);748 READWRITE(fFromMe);749 READWRITE(fSpent);750 )751752 bool WriteToDisk()753 {754 return CWalletDB().WriteTx(GetHash(), *this);755 }756757758 int64 GetTxTime() const;759 int GetRequestCount() const;760761 void AddSupportingTransactions(CTxDB& txdb);762763 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);764 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }765766 void RelayWalletTransaction(CTxDB& txdb);767 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }768};769770771772773//774// A txdb record that contains the disk location of a transaction and the775// locations of transactions that spend its outputs. vSpent is really only776// used as a flag, but having the location is very helpful for debugging.777//778class CTxIndex779{780public:781 CDiskTxPos pos;782 vector<CDiskTxPos> vSpent;783784 CTxIndex()785 {786 SetNull();787 }788789 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)790 {791 pos = posIn;792 vSpent.resize(nOutputs);793 }794795 IMPLEMENT_SERIALIZE796 (797 if (!(nType & SER_GETHASH))798 READWRITE(nVersion);799 READWRITE(pos);800 READWRITE(vSpent);801 )802803 void SetNull()804 {805 pos.SetNull();806 vSpent.clear();807 }808809 bool IsNull()810 {811 return pos.IsNull();812 }813814 friend bool operator==(const CTxIndex& a, const CTxIndex& b)815 {816 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())817 return false;818 for (int i = 0; i < a.vSpent.size(); i++)819 if (a.vSpent[i] != b.vSpent[i])820 return false;821 return true;822 }823824 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)825 {826 return !(a == b);827 }828};829830831832833834//835// Nodes collect new transactions into a block, hash them into a hash tree,836// and scan through nonce values to make the block's hash satisfy proof-of-work837// requirements. When they solve the proof-of-work, they broadcast the block838// to everyone and the block is added to the block chain. The first transaction839// in the block is a special one that creates a new coin owned by the creator840// of the block.841//842// Blocks are appended to blk0001.dat files on disk. Their location on disk843// is indexed by CBlockIndex objects in memory.844//845class CBlock846{847public:848 // header849 int nVersion;850 uint256 hashPrevBlock;851 uint256 hashMerkleRoot;852 unsigned int nTime;853 unsigned int nBits;854 unsigned int nNonce;855856 // network and disk857 vector<CTransaction> vtx;858859 // memory only860 mutable vector<uint256> vMerkleTree;861862863 CBlock()864 {865 SetNull();866 }867868 IMPLEMENT_SERIALIZE869 (870 READWRITE(this->nVersion);871 nVersion = this->nVersion;872 READWRITE(hashPrevBlock);873 READWRITE(hashMerkleRoot);874 READWRITE(nTime);875 READWRITE(nBits);876 READWRITE(nNonce);877878 // ConnectBlock depends on vtx being last so it can calculate offset879 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))880 READWRITE(vtx);881 else if (fRead)882 const_cast<CBlock*>(this)->vtx.clear();883 )884885 void SetNull()886 {887 nVersion = 1;888 hashPrevBlock = 0;889 hashMerkleRoot = 0;890 nTime = 0;891 nBits = 0;892 nNonce = 0;893 vtx.clear();894 vMerkleTree.clear();895 }896897 bool IsNull() const898 {899 return (nBits == 0);900 }901902 uint256 GetHash() const903 {904 return Hash(BEGIN(nVersion), END(nNonce));905 }906907908 uint256 BuildMerkleTree() const909 {910 vMerkleTree.clear();911 foreach(const CTransaction& tx, vtx)912 vMerkleTree.push_back(tx.GetHash());913 int j = 0;914 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)915 {916 for (int i = 0; i < nSize; i += 2)917 {918 int i2 = min(i+1, nSize-1);919 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),920 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));921 }922 j += nSize;923 }924 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());925 }926927 vector<uint256> GetMerkleBranch(int nIndex) const928 {929 if (vMerkleTree.empty())930 BuildMerkleTree();931 vector<uint256> vMerkleBranch;932 int j = 0;933 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)934 {935 int i = min(nIndex^1, nSize-1);936 vMerkleBranch.push_back(vMerkleTree[j+i]);937 nIndex >>= 1;938 j += nSize;939 }940 return vMerkleBranch;941 }942943 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)944 {945 if (nIndex == -1)946 return 0;947 foreach(const uint256& otherside, vMerkleBranch)948 {949 if (nIndex & 1)950 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));951 else952 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));953 nIndex >>= 1;954 }955 return hash;956 }957958959 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)960 {961 // Open history file to append962 CAutoFile fileout = AppendBlockFile(nFileRet);963 if (!fileout)964 return error("CBlock::WriteToDisk() : AppendBlockFile failed");965 if (!fWriteTransactions)966 fileout.nType |= SER_BLOCKHEADERONLY;967968 // Write index header969 unsigned int nSize = fileout.GetSerializeSize(*this);970 fileout << FLATDATA(pchMessageStart) << nSize;971972 // Write block973 nBlockPosRet = ftell(fileout);974 if (nBlockPosRet == -1)975 return error("CBlock::WriteToDisk() : ftell failed");976 fileout << *this;977978 // Flush stdio buffers and commit to disk before returning979 fflush(fileout);980#ifdef __WXMSW__981 _commit(_fileno(fileout));982#else983 fsync(fileno(fileout));984#endif985986 return true;987 }988989 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)990 {991 SetNull();992993 // Open history file to read994 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");995 if (!filein)996 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");997 if (!fReadTransactions)998 filein.nType |= SER_BLOCKHEADERONLY;9991000 // Read block1001 filein >> *this;10021003 // Check the header1004 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1005 return error("CBlock::ReadFromDisk() : nBits errors in block header");1006 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1007 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");10081009 return true;1010 }1011101210131014 void print() const1015 {1016 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",1017 GetHash().ToString().substr(0,16).c_str(),1018 nVersion,1019 hashPrevBlock.ToString().substr(0,16).c_str(),1020 hashMerkleRoot.ToString().substr(0,6).c_str(),1021 nTime, nBits, nNonce,1022 vtx.size());1023 for (int i = 0; i < vtx.size(); i++)1024 {1025 printf(" ");1026 vtx[i].print();1027 }1028 printf(" vMerkleTree: ");1029 for (int i = 0; i < vMerkleTree.size(); i++)1030 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());1031 printf("\n");1032 }103310341035 int64 GetBlockValue(int64 nFees) const;1036 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);1037 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);1038 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);1039 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);1040 bool CheckBlock() const;1041 bool AcceptBlock();1042};1043104410451046104710481049//1050// The block chain is a tree shaped structure starting with the1051// genesis block at the root, with each block potentially having multiple1052// candidates to be the next block. pprev and pnext link a path through the1053// main/longest chain. A blockindex may have multiple pprev pointing back1054// to it, but pnext will only point forward to the longest branch, or will1055// be null if the block is not part of the longest chain.1056//1057class CBlockIndex1058{1059public:1060 const uint256* phashBlock;1061 CBlockIndex* pprev;1062 CBlockIndex* pnext;1063 unsigned int nFile;1064 unsigned int nBlockPos;1065 int nHeight;10661067 // block header1068 int nVersion;1069 uint256 hashMerkleRoot;1070 unsigned int nTime;1071 unsigned int nBits;1072 unsigned int nNonce;107310741075 CBlockIndex()1076 {1077 phashBlock = NULL;1078 pprev = NULL;1079 pnext = NULL;1080 nFile = 0;1081 nBlockPos = 0;1082 nHeight = 0;10831084 nVersion = 0;1085 hashMerkleRoot = 0;1086 nTime = 0;1087 nBits = 0;1088 nNonce = 0;1089 }10901091 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)1092 {1093 phashBlock = NULL;1094 pprev = NULL;1095 pnext = NULL;1096 nFile = nFileIn;1097 nBlockPos = nBlockPosIn;1098 nHeight = 0;10991100 nVersion = block.nVersion;1101 hashMerkleRoot = block.hashMerkleRoot;1102 nTime = block.nTime;1103 nBits = block.nBits;1104 nNonce = block.nNonce;1105 }11061107 uint256 GetBlockHash() const1108 {1109 return *phashBlock;1110 }11111112 bool IsInMainChain() const1113 {1114 return (pnext || this == pindexBest);1115 }11161117 bool EraseBlockFromDisk()1118 {1119 // Open history file1120 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");1121 if (!fileout)1122 return false;11231124 // Overwrite with empty null block1125 CBlock block;1126 block.SetNull();1127 fileout << block;11281129 return true;1130 }11311132 enum { nMedianTimeSpan=11 };11331134 int64 GetMedianTimePast() const1135 {1136 unsigned int pmedian[nMedianTimeSpan];1137 unsigned int* pbegin = &pmedian[nMedianTimeSpan];1138 unsigned int* pend = &pmedian[nMedianTimeSpan];11391140 const CBlockIndex* pindex = this;1141 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)1142 *(--pbegin) = pindex->nTime;11431144 sort(pbegin, pend);1145 return pbegin[(pend - pbegin)/2];1146 }11471148 int64 GetMedianTime() const1149 {1150 const CBlockIndex* pindex = this;1151 for (int i = 0; i < nMedianTimeSpan/2; i++)1152 {1153 if (!pindex->pnext)1154 return nTime;1155 pindex = pindex->pnext;1156 }1157 return pindex->GetMedianTimePast();1158 }1159116011611162 string ToString() const1163 {1164 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",1165 pprev, pnext, nFile, nBlockPos, nHeight,1166 hashMerkleRoot.ToString().substr(0,6).c_str(),1167 GetBlockHash().ToString().substr(0,16).c_str());1168 }11691170 void print() const1171 {1172 printf("%s\n", ToString().c_str());1173 }1174};1175117611771178//1179// Used to marshal pointers into hashes for db storage.1180//1181class CDiskBlockIndex : public CBlockIndex1182{1183public:1184 uint256 hashPrev;1185 uint256 hashNext;11861187 CDiskBlockIndex()1188 {1189 hashPrev = 0;1190 hashNext = 0;1191 }11921193 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)1194 {1195 hashPrev = (pprev ? pprev->GetBlockHash() : 0);1196 hashNext = (pnext ? pnext->GetBlockHash() : 0);1197 }11981199 IMPLEMENT_SERIALIZE1200 (1201 if (!(nType & SER_GETHASH))1202 READWRITE(nVersion);12031204 READWRITE(hashNext);1205 READWRITE(nFile);1206 READWRITE(nBlockPos);1207 READWRITE(nHeight);12081209 // block header1210 READWRITE(this->nVersion);1211 READWRITE(hashPrev);1212 READWRITE(hashMerkleRoot);1213 READWRITE(nTime);1214 READWRITE(nBits);1215 READWRITE(nNonce);1216 )12171218 uint256 GetBlockHash() const1219 {1220 CBlock block;1221 block.nVersion = nVersion;1222 block.hashPrevBlock = hashPrev;1223 block.hashMerkleRoot = hashMerkleRoot;1224 block.nTime = nTime;1225 block.nBits = nBits;1226 block.nNonce = nNonce;1227 return block.GetHash();1228 }122912301231 string ToString() const1232 {1233 string str = "CDiskBlockIndex(";1234 str += CBlockIndex::ToString();1235 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",1236 GetBlockHash().ToString().c_str(),1237 hashPrev.ToString().substr(0,16).c_str(),1238 hashNext.ToString().substr(0,16).c_str());1239 return str;1240 }12411242 void print() const1243 {1244 printf("%s\n", ToString().c_str());1245 }1246};124712481249125012511252125312541255//1256// Describes a place in the block chain to another node such that if the1257// other node doesn't have the same branch, it can find a recent common trunk.1258// The further back it is, the further before the fork it may be.1259//1260class CBlockLocator1261{1262protected:1263 vector<uint256> vHave;1264public:12651266 CBlockLocator()1267 {1268 }12691270 explicit CBlockLocator(const CBlockIndex* pindex)1271 {1272 Set(pindex);1273 }12741275 explicit CBlockLocator(uint256 hashBlock)1276 {1277 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);1278 if (mi != mapBlockIndex.end())1279 Set((*mi).second);1280 }12811282 IMPLEMENT_SERIALIZE1283 (1284 if (!(nType & SER_GETHASH))1285 READWRITE(nVersion);1286 READWRITE(vHave);1287 )12881289 void Set(const CBlockIndex* pindex)1290 {1291 vHave.clear();1292 int nStep = 1;1293 while (pindex)1294 {1295 vHave.push_back(pindex->GetBlockHash());12961297 // Exponentially larger steps back1298 for (int i = 0; pindex && i < nStep; i++)1299 pindex = pindex->pprev;1300 if (vHave.size() > 10)1301 nStep *= 2;1302 }1303 vHave.push_back(hashGenesisBlock);1304 }13051306 int GetDistanceBack()1307 {1308 // Retrace how far back it was in the sender's branch1309 int nDistance = 0;1310 int nStep = 1;1311 foreach(const uint256& hash, vHave)1312 {1313 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1314 if (mi != mapBlockIndex.end())1315 {1316 CBlockIndex* pindex = (*mi).second;1317 if (pindex->IsInMainChain())1318 return nDistance;1319 }1320 nDistance += nStep;1321 if (nDistance > 10)1322 nStep *= 2;1323 }1324 return nDistance;1325 }13261327 CBlockIndex* GetBlockIndex()1328 {1329 // Find the first block the caller has in the main chain1330 foreach(const uint256& hash, vHave)1331 {1332 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1333 if (mi != mapBlockIndex.end())1334 {1335 CBlockIndex* pindex = (*mi).second;1336 if (pindex->IsInMainChain())1337 return pindex;1338 }1339 }1340 return pindexGenesisBlock;1341 }13421343 uint256 GetBlockHash()1344 {1345 // Find the first block the caller has in the main chain1346 foreach(const uint256& hash, vHave)1347 {1348 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1349 if (mi != mapBlockIndex.end())1350 {1351 CBlockIndex* pindex = (*mi).second;1352 if (pindex->IsInMainChain())1353 return hash;1354 }1355 }1356 return hashGenesisBlock;1357 }13581359 int GetHeight()1360 {1361 CBlockIndex* pindex = GetBlockIndex();1362 if (!pindex)1363 return 0;1364 return pindex->nHeight;1365 }1366};1367136813691370137113721373137413751376137713781379extern map<uint256, CTransaction> mapTransactions;1380extern map<uint256, CWalletTx> mapWallet;1381extern vector<uint256> vWalletUpdated;1382extern CCriticalSection cs_mapWallet;1383extern map<vector<unsigned char>, CPrivKey> mapKeys;1384extern map<uint160, vector<unsigned char> > mapPubKeys;1385extern CCriticalSection cs_mapKeys;1386extern 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.
