1 // Copyright (c) 2009 Satoshi Nakamoto
\r
2 // Distributed under the MIT/X11 software license, see the accompanying
\r
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
\r
17 static const unsigned int MAX_SIZE = 0x02000000;
\r
18 static const int64 COIN = 100000000;
\r
19 static const int64 CENT = 1000000;
\r
20 static const int COINBASE_MATURITY = 100;
\r
22 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
\r
29 extern CCriticalSection cs_main;
\r
30 extern map<uint256, CBlockIndex*> mapBlockIndex;
\r
31 extern const uint256 hashGenesisBlock;
\r
32 extern CBlockIndex* pindexGenesisBlock;
\r
33 extern int nBestHeight;
\r
34 extern uint256 hashBestChain;
\r
35 extern CBlockIndex* pindexBest;
\r
36 extern unsigned int nTransactionsUpdated;
\r
37 extern int nDropMessagesTest;
\r
40 extern int fGenerateBitcoins;
\r
41 extern int64 nTransactionFee;
\r
42 extern CAddress addrIncoming;
\r
43 extern int fLimitProcessors;
\r
44 extern int nLimitProcessors;
\r
52 bool CheckDiskSpace(int64 nAdditionalBytes=0);
\r
53 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
\r
54 FILE* AppendBlockFile(unsigned int& nFileRet);
\r
55 bool AddKey(const CKey& key);
\r
56 vector<unsigned char> GenerateNewKey();
\r
57 bool AddToWallet(const CWalletTx& wtxIn);
\r
58 void ReacceptWalletTransactions();
\r
59 void RelayWalletTransactions();
\r
60 bool LoadBlockIndex(bool fAllowNew=true);
\r
61 void PrintBlockTree();
\r
62 bool ProcessMessages(CNode* pfrom);
\r
63 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
64 bool SendMessages(CNode* pto);
\r
66 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
67 bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key);
\r
68 bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);
\r
69 void GenerateBitcoins(bool fGenerate);
\r
70 void ThreadBitcoinMiner(void* parg);
\r
71 bool BitcoinMiner();
\r
88 unsigned int nBlockPos;
\r
89 unsigned int nTxPos;
\r
96 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
99 nBlockPos = nBlockPosIn;
\r
103 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
104 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
105 bool IsNull() const { return (nFile == -1); }
\r
107 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
109 return (a.nFile == b.nFile &&
\r
110 a.nBlockPos == b.nBlockPos &&
\r
111 a.nTxPos == b.nTxPos);
\r
114 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
119 string ToString() const
\r
122 return strprintf("null");
\r
124 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
129 printf("%s", ToString().c_str());
\r
142 CInPoint() { SetNull(); }
\r
143 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
144 void SetNull() { ptx = NULL; n = -1; }
\r
145 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
157 COutPoint() { SetNull(); }
\r
158 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
159 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
160 void SetNull() { hash = 0; n = -1; }
\r
161 bool IsNull() const { return (hash == 0 && n == -1); }
\r
163 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
165 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
168 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
170 return (a.hash == b.hash && a.n == b.n);
\r
173 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
178 string ToString() const
\r
180 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
185 printf("%s\n", ToString().c_str());
\r
193 // An input of a transaction. It contains the location of the previous
\r
194 // transaction's output that it claims and a signature that matches the
\r
195 // output's public key.
\r
202 unsigned int nSequence;
\r
206 nSequence = UINT_MAX;
\r
209 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
211 prevout = prevoutIn;
\r
212 scriptSig = scriptSigIn;
\r
213 nSequence = nSequenceIn;
\r
216 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
218 prevout = COutPoint(hashPrevTx, nOut);
\r
219 scriptSig = scriptSigIn;
\r
220 nSequence = nSequenceIn;
\r
223 IMPLEMENT_SERIALIZE
\r
225 READWRITE(prevout);
\r
226 READWRITE(scriptSig);
\r
227 READWRITE(nSequence);
\r
230 bool IsFinal() const
\r
232 return (nSequence == UINT_MAX);
\r
235 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
237 return (a.prevout == b.prevout &&
\r
238 a.scriptSig == b.scriptSig &&
\r
239 a.nSequence == b.nSequence);
\r
242 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
247 string ToString() const
\r
250 str += strprintf("CTxIn(");
\r
251 str += prevout.ToString();
\r
252 if (prevout.IsNull())
\r
253 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
255 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
256 if (nSequence != UINT_MAX)
\r
257 str += strprintf(", nSequence=%u", nSequence);
\r
264 printf("%s\n", ToString().c_str());
\r
267 bool IsMine() const;
\r
268 int64 GetDebit() const;
\r
275 // An output of a transaction. It contains the public key that the next input
\r
276 // must be able to sign with to claim it.
\r
282 CScript scriptPubKey;
\r
290 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
293 scriptPubKey = scriptPubKeyIn;
\r
296 IMPLEMENT_SERIALIZE
\r
299 READWRITE(scriptPubKey);
\r
305 scriptPubKey.clear();
\r
310 return (nValue == -1);
\r
313 uint256 GetHash() const
\r
315 return SerializeHash(*this);
\r
318 bool IsMine() const
\r
320 return ::IsMine(scriptPubKey);
\r
323 int64 GetCredit() const
\r
330 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
332 return (a.nValue == b.nValue &&
\r
333 a.scriptPubKey == b.scriptPubKey);
\r
336 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
341 string ToString() const
\r
343 if (scriptPubKey.size() < 6)
\r
344 return "CTxOut(error)";
\r
345 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
350 printf("%s\n", ToString().c_str());
\r
358 // The basic transaction that is broadcasted on the network and contained in
\r
359 // blocks. A transaction can contain multiple inputs and outputs.
\r
366 vector<CTxOut> vout;
\r
367 unsigned int nLockTime;
\r
375 IMPLEMENT_SERIALIZE
\r
377 READWRITE(this->nVersion);
\r
378 nVersion = this->nVersion;
\r
381 READWRITE(nLockTime);
\r
392 bool IsNull() const
\r
394 return (vin.empty() && vout.empty());
\r
397 uint256 GetHash() const
\r
399 return SerializeHash(*this);
\r
402 bool IsFinal(int64 nBlockTime=0) const
\r
404 // Time based nLockTime implemented in 0.1.6,
\r
405 // do not use time based until most 0.1.5 nodes have upgraded.
\r
406 if (nLockTime == 0)
\r
408 if (nBlockTime == 0)
\r
409 nBlockTime = GetAdjustedTime();
\r
410 if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))
\r
412 foreach(const CTxIn& txin, vin)
\r
413 if (!txin.IsFinal())
\r
418 bool IsNewerThan(const CTransaction& old) const
\r
420 if (vin.size() != old.vin.size())
\r
422 for (int i = 0; i < vin.size(); i++)
\r
423 if (vin[i].prevout != old.vin[i].prevout)
\r
426 bool fNewer = false;
\r
427 unsigned int nLowest = UINT_MAX;
\r
428 for (int i = 0; i < vin.size(); i++)
\r
430 if (vin[i].nSequence != old.vin[i].nSequence)
\r
432 if (vin[i].nSequence <= nLowest)
\r
435 nLowest = vin[i].nSequence;
\r
437 if (old.vin[i].nSequence < nLowest)
\r
440 nLowest = old.vin[i].nSequence;
\r
447 bool IsCoinBase() const
\r
449 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
452 bool CheckTransaction() const
\r
454 // Basic checks that don't depend on any context
\r
455 if (vin.empty() || vout.empty())
\r
456 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
458 // Check for negative values
\r
459 foreach(const CTxOut& txout, vout)
\r
460 if (txout.nValue < 0)
\r
461 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
465 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
466 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
470 foreach(const CTxIn& txin, vin)
\r
471 if (txin.prevout.IsNull())
\r
472 return error("CTransaction::CheckTransaction() : prevout is null");
\r
478 bool IsMine() const
\r
480 foreach(const CTxOut& txout, vout)
\r
481 if (txout.IsMine())
\r
486 int64 GetDebit() const
\r
489 foreach(const CTxIn& txin, vin)
\r
490 nDebit += txin.GetDebit();
\r
494 int64 GetCredit() const
\r
497 foreach(const CTxOut& txout, vout)
\r
498 nCredit += txout.GetCredit();
\r
502 int64 GetValueOut() const
\r
504 int64 nValueOut = 0;
\r
505 foreach(const CTxOut& txout, vout)
\r
507 if (txout.nValue < 0)
\r
508 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
509 nValueOut += txout.nValue;
\r
514 int64 GetMinFee(bool fDiscount=false) const
\r
516 // Base fee is 1 cent per kilobyte
\r
517 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
518 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
520 // First 100 transactions in a block are free
\r
521 if (fDiscount && nBytes < 10000)
\r
524 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
525 if (nMinFee < CENT)
\r
526 foreach(const CTxOut& txout, vout)
\r
527 if (txout.nValue < CENT)
\r
535 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
537 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
539 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
541 // Read transaction
\r
542 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
543 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
546 // Return file pointer
\r
549 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
550 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
551 *pfileRet = filein.release();
\r
557 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
559 return (a.nVersion == b.nVersion &&
\r
561 a.vout == b.vout &&
\r
562 a.nLockTime == b.nLockTime);
\r
565 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
571 string ToString() const
\r
574 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
575 GetHash().ToString().substr(0,6).c_str(),
\r
580 for (int i = 0; i < vin.size(); i++)
\r
581 str += " " + vin[i].ToString() + "\n";
\r
582 for (int i = 0; i < vout.size(); i++)
\r
583 str += " " + vout[i].ToString() + "\n";
\r
589 printf("%s", ToString().c_str());
\r
594 bool DisconnectInputs(CTxDB& txdb);
\r
595 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
596 bool ClientConnectInputs();
\r
598 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
600 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
603 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
607 bool AddToMemoryPool();
\r
609 bool RemoveFromMemoryPool();
\r
617 // A transaction with a merkle branch linking it to the block chain
\r
619 class CMerkleTx : public CTransaction
\r
623 vector<uint256> vMerkleBranch;
\r
627 mutable bool fMerkleVerified;
\r
628 mutable bool fGetCreditCached;
\r
629 mutable int64 nGetCreditCached;
\r
637 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
646 fMerkleVerified = false;
\r
647 fGetCreditCached = false;
\r
648 nGetCreditCached = 0;
\r
651 int64 GetCredit(bool fUseCache=false) const
\r
653 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
654 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
657 // GetBalance can assume transactions in mapWallet won't change
\r
658 if (fUseCache && fGetCreditCached)
\r
659 return nGetCreditCached;
\r
660 nGetCreditCached = CTransaction::GetCredit();
\r
661 fGetCreditCached = true;
\r
662 return nGetCreditCached;
\r
665 IMPLEMENT_SERIALIZE
\r
667 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
668 nVersion = this->nVersion;
\r
669 READWRITE(hashBlock);
\r
670 READWRITE(vMerkleBranch);
\r
675 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
676 int GetDepthInMainChain() const;
\r
677 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
678 int GetBlocksToMaturity() const;
\r
679 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
680 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
687 // A transaction with a bunch of additional info that only the owner cares
\r
688 // about. It includes any unrecorded transactions needed to link it back
\r
689 // to the block chain.
\r
691 class CWalletTx : public CMerkleTx
\r
694 vector<CMerkleTx> vtxPrev;
\r
695 map<string, string> mapValue;
\r
696 vector<pair<string, string> > vOrderForm;
\r
697 unsigned int fTimeReceivedIsTxTime;
\r
698 unsigned int nTimeReceived; // time received by this node
\r
701 //// probably need to sign the order info so know it came from payer
\r
703 // memory only UI hints
\r
704 mutable unsigned int nTimeDisplayed;
\r
705 mutable int nLinesDisplayed;
\r
713 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
718 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
725 fTimeReceivedIsTxTime = false;
\r
729 nTimeDisplayed = 0;
\r
730 nLinesDisplayed = 0;
\r
733 IMPLEMENT_SERIALIZE
\r
735 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
736 nVersion = this->nVersion;
\r
737 READWRITE(vtxPrev);
\r
738 READWRITE(mapValue);
\r
739 READWRITE(vOrderForm);
\r
740 READWRITE(fTimeReceivedIsTxTime);
\r
741 READWRITE(nTimeReceived);
\r
742 READWRITE(fFromMe);
\r
748 return CWalletDB().WriteTx(GetHash(), *this);
\r
752 int64 GetTxTime() const;
\r
754 void AddSupportingTransactions(CTxDB& txdb);
\r
756 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
757 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
759 void RelayWalletTransaction(CTxDB& txdb);
\r
760 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
767 // A txdb record that contains the disk location of a transaction and the
\r
768 // locations of transactions that spend its outputs. vSpent is really only
\r
769 // used as a flag, but having the location is very helpful for debugging.
\r
775 vector<CDiskTxPos> vSpent;
\r
782 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
785 vSpent.resize(nOutputs);
\r
788 IMPLEMENT_SERIALIZE
\r
790 if (!(nType & SER_GETHASH))
\r
791 READWRITE(nVersion);
\r
804 return pos.IsNull();
\r
807 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
809 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
811 for (int i = 0; i < a.vSpent.size(); i++)
\r
812 if (a.vSpent[i] != b.vSpent[i])
\r
817 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
828 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
829 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
830 // requirements. When they solve the proof-of-work, they broadcast the block
\r
831 // to everyone and the block is added to the block chain. The first transaction
\r
832 // in the block is a special one that creates a new coin owned by the creator
\r
835 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
836 // is indexed by CBlockIndex objects in memory.
\r
843 uint256 hashPrevBlock;
\r
844 uint256 hashMerkleRoot;
\r
845 unsigned int nTime;
\r
846 unsigned int nBits;
\r
847 unsigned int nNonce;
\r
849 // network and disk
\r
850 vector<CTransaction> vtx;
\r
853 mutable vector<uint256> vMerkleTree;
\r
861 IMPLEMENT_SERIALIZE
\r
863 READWRITE(this->nVersion);
\r
864 nVersion = this->nVersion;
\r
865 READWRITE(hashPrevBlock);
\r
866 READWRITE(hashMerkleRoot);
\r
871 // ConnectBlock depends on vtx being last so it can calculate offset
\r
872 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
875 const_cast<CBlock*>(this)->vtx.clear();
\r
882 hashMerkleRoot = 0;
\r
887 vMerkleTree.clear();
\r
890 bool IsNull() const
\r
892 return (nBits == 0);
\r
895 uint256 GetHash() const
\r
897 return Hash(BEGIN(nVersion), END(nNonce));
\r
901 uint256 BuildMerkleTree() const
\r
903 vMerkleTree.clear();
\r
904 foreach(const CTransaction& tx, vtx)
\r
905 vMerkleTree.push_back(tx.GetHash());
\r
907 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
909 for (int i = 0; i < nSize; i += 2)
\r
911 int i2 = min(i+1, nSize-1);
\r
912 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
913 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
917 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
920 vector<uint256> GetMerkleBranch(int nIndex) const
\r
922 if (vMerkleTree.empty())
\r
924 vector<uint256> vMerkleBranch;
\r
926 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
928 int i = min(nIndex^1, nSize-1);
\r
929 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
933 return vMerkleBranch;
\r
936 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
940 foreach(const uint256& otherside, vMerkleBranch)
\r
943 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
945 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
952 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
954 // Open history file to append
\r
955 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
957 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
958 if (!fWriteTransactions)
\r
959 fileout.nType |= SER_BLOCKHEADERONLY;
\r
961 // Write index header
\r
962 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
963 fileout << FLATDATA(pchMessageStart) << nSize;
\r
966 nBlockPosRet = ftell(fileout);
\r
967 if (nBlockPosRet == -1)
\r
968 return error("CBlock::WriteToDisk() : ftell failed");
\r
971 // Flush stdio buffers and commit to disk before returning
\r
974 _commit(_fileno(fileout));
\r
976 fsync(fileno(fileout));
\r
982 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)
\r
986 // Open history file to read
\r
987 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
989 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
990 if (!fReadTransactions)
\r
991 filein.nType |= SER_BLOCKHEADERONLY;
\r
996 // Check the header
\r
997 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
998 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
999 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
1000 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
1007 void print() const
\r
1009 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
1010 GetHash().ToString().substr(0,14).c_str(),
\r
1012 hashPrevBlock.ToString().substr(0,14).c_str(),
\r
1013 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1014 nTime, nBits, nNonce,
\r
1016 for (int i = 0; i < vtx.size(); i++)
\r
1021 printf(" vMerkleTree: ");
\r
1022 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1023 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1028 int64 GetBlockValue(int64 nFees) const;
\r
1029 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1030 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1031 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions);
\r
1032 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1033 bool CheckBlock() const;
\r
1034 bool AcceptBlock();
\r
1043 // The block chain is a tree shaped structure starting with the
\r
1044 // genesis block at the root, with each block potentially having multiple
\r
1045 // candidates to be the next block. pprev and pnext link a path through the
\r
1046 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1047 // to it, but pnext will only point forward to the longest branch, or will
\r
1048 // be null if the block is not part of the longest chain.
\r
1053 const uint256* phashBlock;
\r
1054 CBlockIndex* pprev;
\r
1055 CBlockIndex* pnext;
\r
1056 unsigned int nFile;
\r
1057 unsigned int nBlockPos;
\r
1062 uint256 hashMerkleRoot;
\r
1063 unsigned int nTime;
\r
1064 unsigned int nBits;
\r
1065 unsigned int nNonce;
\r
1070 phashBlock = NULL;
\r
1078 hashMerkleRoot = 0;
\r
1084 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1086 phashBlock = NULL;
\r
1090 nBlockPos = nBlockPosIn;
\r
1093 nVersion = block.nVersion;
\r
1094 hashMerkleRoot = block.hashMerkleRoot;
\r
1095 nTime = block.nTime;
\r
1096 nBits = block.nBits;
\r
1097 nNonce = block.nNonce;
\r
1100 uint256 GetBlockHash() const
\r
1102 return *phashBlock;
\r
1105 bool IsInMainChain() const
\r
1107 return (pnext || this == pindexBest);
\r
1110 bool EraseBlockFromDisk()
\r
1112 // Open history file
\r
1113 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1117 // Overwrite with empty null block
\r
1125 enum { nMedianTimeSpan=11 };
\r
1127 int64 GetMedianTimePast() const
\r
1129 unsigned int pmedian[nMedianTimeSpan];
\r
1130 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1131 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1133 const CBlockIndex* pindex = this;
\r
1134 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1135 *(--pbegin) = pindex->nTime;
\r
1137 sort(pbegin, pend);
\r
1138 return pbegin[(pend - pbegin)/2];
\r
1141 int64 GetMedianTime() const
\r
1143 const CBlockIndex* pindex = this;
\r
1144 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1146 if (!pindex->pnext)
\r
1148 pindex = pindex->pnext;
\r
1150 return pindex->GetMedianTimePast();
\r
1155 string ToString() const
\r
1157 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1158 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1159 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1160 GetBlockHash().ToString().substr(0,14).c_str());
\r
1163 void print() const
\r
1165 printf("%s\n", ToString().c_str());
\r
1172 // Used to marshal pointers into hashes for db storage.
\r
1174 class CDiskBlockIndex : public CBlockIndex
\r
1186 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1188 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1189 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1192 IMPLEMENT_SERIALIZE
\r
1194 if (!(nType & SER_GETHASH))
\r
1195 READWRITE(nVersion);
\r
1197 READWRITE(hashNext);
\r
1199 READWRITE(nBlockPos);
\r
1200 READWRITE(nHeight);
\r
1203 READWRITE(this->nVersion);
\r
1204 READWRITE(hashPrev);
\r
1205 READWRITE(hashMerkleRoot);
\r
1208 READWRITE(nNonce);
\r
1211 uint256 GetBlockHash() const
\r
1214 block.nVersion = nVersion;
\r
1215 block.hashPrevBlock = hashPrev;
\r
1216 block.hashMerkleRoot = hashMerkleRoot;
\r
1217 block.nTime = nTime;
\r
1218 block.nBits = nBits;
\r
1219 block.nNonce = nNonce;
\r
1220 return block.GetHash();
\r
1224 string ToString() const
\r
1226 string str = "CDiskBlockIndex(";
\r
1227 str += CBlockIndex::ToString();
\r
1228 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1229 GetBlockHash().ToString().c_str(),
\r
1230 hashPrev.ToString().substr(0,14).c_str(),
\r
1231 hashNext.ToString().substr(0,14).c_str());
\r
1235 void print() const
\r
1237 printf("%s\n", ToString().c_str());
\r
1249 // Describes a place in the block chain to another node such that if the
\r
1250 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1251 // The further back it is, the further before the fork it may be.
\r
1253 class CBlockLocator
\r
1256 vector<uint256> vHave;
\r
1263 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1268 explicit CBlockLocator(uint256 hashBlock)
\r
1270 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1271 if (mi != mapBlockIndex.end())
\r
1272 Set((*mi).second);
\r
1275 IMPLEMENT_SERIALIZE
\r
1277 if (!(nType & SER_GETHASH))
\r
1278 READWRITE(nVersion);
\r
1282 void Set(const CBlockIndex* pindex)
\r
1288 vHave.push_back(pindex->GetBlockHash());
\r
1290 // Exponentially larger steps back
\r
1291 for (int i = 0; pindex && i < nStep; i++)
\r
1292 pindex = pindex->pprev;
\r
1293 if (vHave.size() > 10)
\r
1296 vHave.push_back(hashGenesisBlock);
\r
1299 CBlockIndex* GetBlockIndex()
\r
1301 // Find the first block the caller has in the main chain
\r
1302 foreach(const uint256& hash, vHave)
\r
1304 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1305 if (mi != mapBlockIndex.end())
\r
1307 CBlockIndex* pindex = (*mi).second;
\r
1308 if (pindex->IsInMainChain())
\r
1312 return pindexGenesisBlock;
\r
1315 uint256 GetBlockHash()
\r
1317 // Find the first block the caller has in the main chain
\r
1318 foreach(const uint256& hash, vHave)
\r
1320 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1321 if (mi != mapBlockIndex.end())
\r
1323 CBlockIndex* pindex = (*mi).second;
\r
1324 if (pindex->IsInMainChain())
\r
1328 return hashGenesisBlock;
\r
1333 CBlockIndex* pindex = GetBlockIndex();
\r
1336 return pindex->nHeight;
\r
1351 extern map<uint256, CTransaction> mapTransactions;
\r
1352 extern map<uint256, CWalletTx> mapWallet;
\r
1353 extern vector<uint256> vWalletUpdated;
\r
1354 extern CCriticalSection cs_mapWallet;
\r
1355 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1356 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1357 extern CCriticalSection cs_mapKeys;
\r
1358 extern CKey keyUser;
\r