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 string strSetDataDir;
\r
38 extern int nDropMessagesTest;
\r
41 extern int fGenerateBitcoins;
\r
42 extern int64 nTransactionFee;
\r
43 extern CAddress addrIncoming;
\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 BitcoinMiner();
\r
63 bool ProcessMessages(CNode* pfrom);
\r
64 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
65 bool SendMessages(CNode* pto);
\r
67 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& txNew, int64& nFeeRequiredRet);
\r
68 bool CommitTransactionSpent(const CWalletTx& wtxNew);
\r
69 bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);
\r
85 unsigned int nBlockPos;
\r
86 unsigned int nTxPos;
\r
93 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
96 nBlockPos = nBlockPosIn;
\r
100 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
101 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
102 bool IsNull() const { return (nFile == -1); }
\r
104 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
106 return (a.nFile == b.nFile &&
\r
107 a.nBlockPos == b.nBlockPos &&
\r
108 a.nTxPos == b.nTxPos);
\r
111 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
116 string ToString() const
\r
119 return strprintf("null");
\r
121 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
126 printf("%s", ToString().c_str());
\r
139 CInPoint() { SetNull(); }
\r
140 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
141 void SetNull() { ptx = NULL; n = -1; }
\r
142 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
154 COutPoint() { SetNull(); }
\r
155 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
156 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
157 void SetNull() { hash = 0; n = -1; }
\r
158 bool IsNull() const { return (hash == 0 && n == -1); }
\r
160 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
162 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
165 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
167 return (a.hash == b.hash && a.n == b.n);
\r
170 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
175 string ToString() const
\r
177 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
182 printf("%s\n", ToString().c_str());
\r
190 // An input of a transaction. It contains the location of the previous
\r
191 // transaction's output that it claims and a signature that matches the
\r
192 // output's public key.
\r
199 unsigned int nSequence;
\r
203 nSequence = UINT_MAX;
\r
206 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
208 prevout = prevoutIn;
\r
209 scriptSig = scriptSigIn;
\r
210 nSequence = nSequenceIn;
\r
213 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
215 prevout = COutPoint(hashPrevTx, nOut);
\r
216 scriptSig = scriptSigIn;
\r
217 nSequence = nSequenceIn;
\r
220 IMPLEMENT_SERIALIZE
\r
222 READWRITE(prevout);
\r
223 READWRITE(scriptSig);
\r
224 READWRITE(nSequence);
\r
227 bool IsFinal() const
\r
229 return (nSequence == UINT_MAX);
\r
232 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
234 return (a.prevout == b.prevout &&
\r
235 a.scriptSig == b.scriptSig &&
\r
236 a.nSequence == b.nSequence);
\r
239 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
244 string ToString() const
\r
247 str += strprintf("CTxIn(");
\r
248 str += prevout.ToString();
\r
249 if (prevout.IsNull())
\r
250 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
252 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
253 if (nSequence != UINT_MAX)
\r
254 str += strprintf(", nSequence=%u", nSequence);
\r
261 printf("%s\n", ToString().c_str());
\r
264 bool IsMine() const;
\r
265 int64 GetDebit() const;
\r
272 // An output of a transaction. It contains the public key that the next input
\r
273 // must be able to sign with to claim it.
\r
279 CScript scriptPubKey;
\r
287 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
290 scriptPubKey = scriptPubKeyIn;
\r
293 IMPLEMENT_SERIALIZE
\r
296 READWRITE(scriptPubKey);
\r
302 scriptPubKey.clear();
\r
307 return (nValue == -1);
\r
310 uint256 GetHash() const
\r
312 return SerializeHash(*this);
\r
315 bool IsMine() const
\r
317 return ::IsMine(scriptPubKey);
\r
320 int64 GetCredit() const
\r
327 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
329 return (a.nValue == b.nValue &&
\r
330 a.scriptPubKey == b.scriptPubKey);
\r
333 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
338 string ToString() const
\r
340 if (scriptPubKey.size() < 6)
\r
341 return "CTxOut(error)";
\r
342 return strprintf("CTxOut(nValue=%I64d.%08I64d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
347 printf("%s\n", ToString().c_str());
\r
355 // The basic transaction that is broadcasted on the network and contained in
\r
356 // blocks. A transaction can contain multiple inputs and outputs.
\r
363 vector<CTxOut> vout;
\r
372 IMPLEMENT_SERIALIZE
\r
374 READWRITE(this->nVersion);
\r
375 nVersion = this->nVersion;
\r
378 READWRITE(nLockTime);
\r
389 bool IsNull() const
\r
391 return (vin.empty() && vout.empty());
\r
394 uint256 GetHash() const
\r
396 return SerializeHash(*this);
\r
399 bool IsFinal() const
\r
401 if (nLockTime == 0 || nLockTime < nBestHeight)
\r
403 foreach(const CTxIn& txin, vin)
\r
404 if (!txin.IsFinal())
\r
409 bool IsNewerThan(const CTransaction& old) const
\r
411 if (vin.size() != old.vin.size())
\r
413 for (int i = 0; i < vin.size(); i++)
\r
414 if (vin[i].prevout != old.vin[i].prevout)
\r
417 bool fNewer = false;
\r
418 unsigned int nLowest = UINT_MAX;
\r
419 for (int i = 0; i < vin.size(); i++)
\r
421 if (vin[i].nSequence != old.vin[i].nSequence)
\r
423 if (vin[i].nSequence <= nLowest)
\r
426 nLowest = vin[i].nSequence;
\r
428 if (old.vin[i].nSequence < nLowest)
\r
431 nLowest = old.vin[i].nSequence;
\r
438 bool IsCoinBase() const
\r
440 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
443 bool CheckTransaction() const
\r
445 // Basic checks that don't depend on any context
\r
446 if (vin.empty() || vout.empty())
\r
447 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
449 // Check for negative values
\r
450 foreach(const CTxOut& txout, vout)
\r
451 if (txout.nValue < 0)
\r
452 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
456 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
457 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
461 foreach(const CTxIn& txin, vin)
\r
462 if (txin.prevout.IsNull())
\r
463 return error("CTransaction::CheckTransaction() : prevout is null");
\r
469 bool IsMine() const
\r
471 foreach(const CTxOut& txout, vout)
\r
472 if (txout.IsMine())
\r
477 int64 GetDebit() const
\r
480 foreach(const CTxIn& txin, vin)
\r
481 nDebit += txin.GetDebit();
\r
485 int64 GetCredit() const
\r
488 foreach(const CTxOut& txout, vout)
\r
489 nCredit += txout.GetCredit();
\r
493 int64 GetValueOut() const
\r
495 int64 nValueOut = 0;
\r
496 foreach(const CTxOut& txout, vout)
\r
498 if (txout.nValue < 0)
\r
499 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
500 nValueOut += txout.nValue;
\r
505 int64 GetMinFee(bool fDiscount=false) const
\r
507 // Base fee is 1 cent per kilobyte
\r
508 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
509 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
511 // First 100 transactions in a block are free
\r
512 if (fDiscount && nBytes < 10000)
\r
515 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
516 if (nMinFee < CENT)
\r
517 foreach(const CTxOut& txout, vout)
\r
518 if (txout.nValue < CENT)
\r
526 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
528 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
530 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
532 // Read transaction
\r
533 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
534 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
537 // Return file pointer
\r
540 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
541 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
542 *pfileRet = filein.release();
\r
548 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
550 return (a.nVersion == b.nVersion &&
\r
552 a.vout == b.vout &&
\r
553 a.nLockTime == b.nLockTime);
\r
556 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
562 string ToString() const
\r
565 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
566 GetHash().ToString().substr(0,6).c_str(),
\r
571 for (int i = 0; i < vin.size(); i++)
\r
572 str += " " + vin[i].ToString() + "\n";
\r
573 for (int i = 0; i < vout.size(); i++)
\r
574 str += " " + vout[i].ToString() + "\n";
\r
580 printf("%s", ToString().c_str());
\r
585 bool DisconnectInputs(CTxDB& txdb);
\r
586 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
587 bool ClientConnectInputs();
\r
589 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
591 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
594 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
598 bool AddToMemoryPool();
\r
600 bool RemoveFromMemoryPool();
\r
608 // A transaction with a merkle branch linking it to the block chain
\r
610 class CMerkleTx : public CTransaction
\r
614 vector<uint256> vMerkleBranch;
\r
618 mutable bool fMerkleVerified;
\r
626 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
635 fMerkleVerified = false;
\r
638 int64 GetCredit() const
\r
640 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
641 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
643 return CTransaction::GetCredit();
\r
646 IMPLEMENT_SERIALIZE
\r
648 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
649 nVersion = this->nVersion;
\r
650 READWRITE(hashBlock);
\r
651 READWRITE(vMerkleBranch);
\r
656 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
657 int GetDepthInMainChain() const;
\r
658 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
659 int GetBlocksToMaturity() const;
\r
660 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
661 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
668 // A transaction with a bunch of additional info that only the owner cares
\r
669 // about. It includes any unrecorded transactions needed to link it back
\r
670 // to the block chain.
\r
672 class CWalletTx : public CMerkleTx
\r
675 vector<CMerkleTx> vtxPrev;
\r
676 map<string, string> mapValue;
\r
677 vector<pair<string, string> > vOrderForm;
\r
678 unsigned int fTimeReceivedIsTxTime;
\r
679 unsigned int nTimeReceived; // time received by this node
\r
682 //// probably need to sign the order info so know it came from payer
\r
685 mutable unsigned int nTimeDisplayed;
\r
693 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
698 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
705 fTimeReceivedIsTxTime = false;
\r
709 nTimeDisplayed = 0;
\r
712 IMPLEMENT_SERIALIZE
\r
714 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
715 nVersion = this->nVersion;
\r
716 READWRITE(vtxPrev);
\r
717 READWRITE(mapValue);
\r
718 READWRITE(vOrderForm);
\r
719 READWRITE(fTimeReceivedIsTxTime);
\r
720 READWRITE(nTimeReceived);
\r
721 READWRITE(fFromMe);
\r
727 return CWalletDB().WriteTx(GetHash(), *this);
\r
731 int64 GetTxTime() const;
\r
733 void AddSupportingTransactions(CTxDB& txdb);
\r
735 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
736 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
738 void RelayWalletTransaction(CTxDB& txdb);
\r
739 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
746 // A txdb record that contains the disk location of a transaction and the
\r
747 // locations of transactions that spend its outputs. vSpent is really only
\r
748 // used as a flag, but having the location is very helpful for debugging.
\r
754 vector<CDiskTxPos> vSpent;
\r
761 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
764 vSpent.resize(nOutputs);
\r
767 IMPLEMENT_SERIALIZE
\r
769 if (!(nType & SER_GETHASH))
\r
770 READWRITE(nVersion);
\r
783 return pos.IsNull();
\r
786 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
788 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
790 for (int i = 0; i < a.vSpent.size(); i++)
\r
791 if (a.vSpent[i] != b.vSpent[i])
\r
796 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
807 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
808 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
809 // requirements. When they solve the proof-of-work, they broadcast the block
\r
810 // to everyone and the block is added to the block chain. The first transaction
\r
811 // in the block is a special one that creates a new coin owned by the creator
\r
814 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
815 // is indexed by CBlockIndex objects in memory.
\r
822 uint256 hashPrevBlock;
\r
823 uint256 hashMerkleRoot;
\r
824 unsigned int nTime;
\r
825 unsigned int nBits;
\r
826 unsigned int nNonce;
\r
828 // network and disk
\r
829 vector<CTransaction> vtx;
\r
832 mutable vector<uint256> vMerkleTree;
\r
840 IMPLEMENT_SERIALIZE
\r
842 READWRITE(this->nVersion);
\r
843 nVersion = this->nVersion;
\r
844 READWRITE(hashPrevBlock);
\r
845 READWRITE(hashMerkleRoot);
\r
850 // ConnectBlock depends on vtx being last so it can calculate offset
\r
851 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
854 const_cast<CBlock*>(this)->vtx.clear();
\r
861 hashMerkleRoot = 0;
\r
866 vMerkleTree.clear();
\r
869 bool IsNull() const
\r
871 return (nBits == 0);
\r
874 uint256 GetHash() const
\r
876 return Hash(BEGIN(nVersion), END(nNonce));
\r
880 uint256 BuildMerkleTree() const
\r
882 vMerkleTree.clear();
\r
883 foreach(const CTransaction& tx, vtx)
\r
884 vMerkleTree.push_back(tx.GetHash());
\r
886 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
888 for (int i = 0; i < nSize; i += 2)
\r
890 int i2 = min(i+1, nSize-1);
\r
891 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
892 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
896 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
899 vector<uint256> GetMerkleBranch(int nIndex) const
\r
901 if (vMerkleTree.empty())
\r
903 vector<uint256> vMerkleBranch;
\r
905 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
907 int i = min(nIndex^1, nSize-1);
\r
908 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
912 return vMerkleBranch;
\r
915 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
919 foreach(const uint256& otherside, vMerkleBranch)
\r
922 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
924 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
931 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
933 // Open history file to append
\r
934 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
936 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
937 if (!fWriteTransactions)
\r
938 fileout.nType |= SER_BLOCKHEADERONLY;
\r
940 // Write index header
\r
941 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
942 fileout << FLATDATA(pchMessageStart) << nSize;
\r
945 nBlockPosRet = ftell(fileout);
\r
946 if (nBlockPosRet == -1)
\r
947 return error("CBlock::WriteToDisk() : ftell failed");
\r
953 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)
\r
957 // Open history file to read
\r
958 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
960 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
961 if (!fReadTransactions)
\r
962 filein.nType |= SER_BLOCKHEADERONLY;
\r
967 // Check the header
\r
968 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
969 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
970 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
971 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
980 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
981 GetHash().ToString().substr(0,14).c_str(),
\r
983 hashPrevBlock.ToString().substr(0,14).c_str(),
\r
984 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
985 nTime, nBits, nNonce,
\r
987 for (int i = 0; i < vtx.size(); i++)
\r
992 printf(" vMerkleTree: ");
\r
993 for (int i = 0; i < vMerkleTree.size(); i++)
\r
994 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
999 int64 GetBlockValue(int64 nFees) const;
\r
1000 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1001 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1002 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions);
\r
1003 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1004 bool CheckBlock() const;
\r
1005 bool AcceptBlock();
\r
1014 // The block chain is a tree shaped structure starting with the
\r
1015 // genesis block at the root, with each block potentially having multiple
\r
1016 // candidates to be the next block. pprev and pnext link a path through the
\r
1017 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1018 // to it, but pnext will only point forward to the longest branch, or will
\r
1019 // be null if the block is not part of the longest chain.
\r
1024 const uint256* phashBlock;
\r
1025 CBlockIndex* pprev;
\r
1026 CBlockIndex* pnext;
\r
1027 unsigned int nFile;
\r
1028 unsigned int nBlockPos;
\r
1033 uint256 hashMerkleRoot;
\r
1034 unsigned int nTime;
\r
1035 unsigned int nBits;
\r
1036 unsigned int nNonce;
\r
1041 phashBlock = NULL;
\r
1049 hashMerkleRoot = 0;
\r
1055 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1057 phashBlock = NULL;
\r
1061 nBlockPos = nBlockPosIn;
\r
1064 nVersion = block.nVersion;
\r
1065 hashMerkleRoot = block.hashMerkleRoot;
\r
1066 nTime = block.nTime;
\r
1067 nBits = block.nBits;
\r
1068 nNonce = block.nNonce;
\r
1071 uint256 GetBlockHash() const
\r
1073 return *phashBlock;
\r
1076 bool IsInMainChain() const
\r
1078 return (pnext || this == pindexBest);
\r
1081 bool EraseBlockFromDisk()
\r
1083 // Open history file
\r
1084 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1088 // Overwrite with empty null block
\r
1096 enum { nMedianTimeSpan=11 };
\r
1098 int64 GetMedianTimePast() const
\r
1100 unsigned int pmedian[nMedianTimeSpan];
\r
1101 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1102 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1104 const CBlockIndex* pindex = this;
\r
1105 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1106 *(--pbegin) = pindex->nTime;
\r
1108 sort(pbegin, pend);
\r
1109 return pbegin[(pend - pbegin)/2];
\r
1112 int64 GetMedianTime() const
\r
1114 const CBlockIndex* pindex = this;
\r
1115 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1117 if (!pindex->pnext)
\r
1119 pindex = pindex->pnext;
\r
1121 return pindex->GetMedianTimePast();
\r
1126 string ToString() const
\r
1128 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1129 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1130 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1131 GetBlockHash().ToString().substr(0,14).c_str());
\r
1134 void print() const
\r
1136 printf("%s\n", ToString().c_str());
\r
1143 // Used to marshal pointers into hashes for db storage.
\r
1145 class CDiskBlockIndex : public CBlockIndex
\r
1157 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1159 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1160 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1163 IMPLEMENT_SERIALIZE
\r
1165 if (!(nType & SER_GETHASH))
\r
1166 READWRITE(nVersion);
\r
1168 READWRITE(hashNext);
\r
1170 READWRITE(nBlockPos);
\r
1171 READWRITE(nHeight);
\r
1174 READWRITE(this->nVersion);
\r
1175 READWRITE(hashPrev);
\r
1176 READWRITE(hashMerkleRoot);
\r
1179 READWRITE(nNonce);
\r
1182 uint256 GetBlockHash() const
\r
1185 block.nVersion = nVersion;
\r
1186 block.hashPrevBlock = hashPrev;
\r
1187 block.hashMerkleRoot = hashMerkleRoot;
\r
1188 block.nTime = nTime;
\r
1189 block.nBits = nBits;
\r
1190 block.nNonce = nNonce;
\r
1191 return block.GetHash();
\r
1195 string ToString() const
\r
1197 string str = "CDiskBlockIndex(";
\r
1198 str += CBlockIndex::ToString();
\r
1199 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1200 GetBlockHash().ToString().c_str(),
\r
1201 hashPrev.ToString().substr(0,14).c_str(),
\r
1202 hashNext.ToString().substr(0,14).c_str());
\r
1206 void print() const
\r
1208 printf("%s\n", ToString().c_str());
\r
1220 // Describes a place in the block chain to another node such that if the
\r
1221 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1222 // The further back it is, the further before the fork it may be.
\r
1224 class CBlockLocator
\r
1227 vector<uint256> vHave;
\r
1234 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1239 explicit CBlockLocator(uint256 hashBlock)
\r
1241 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1242 if (mi != mapBlockIndex.end())
\r
1243 Set((*mi).second);
\r
1246 IMPLEMENT_SERIALIZE
\r
1248 if (!(nType & SER_GETHASH))
\r
1249 READWRITE(nVersion);
\r
1253 void Set(const CBlockIndex* pindex)
\r
1259 vHave.push_back(pindex->GetBlockHash());
\r
1261 // Exponentially larger steps back
\r
1262 for (int i = 0; pindex && i < nStep; i++)
\r
1263 pindex = pindex->pprev;
\r
1264 if (vHave.size() > 10)
\r
1267 vHave.push_back(hashGenesisBlock);
\r
1270 CBlockIndex* GetBlockIndex()
\r
1272 // Find the first block the caller has in the main chain
\r
1273 foreach(const uint256& hash, vHave)
\r
1275 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1276 if (mi != mapBlockIndex.end())
\r
1278 CBlockIndex* pindex = (*mi).second;
\r
1279 if (pindex->IsInMainChain())
\r
1283 return pindexGenesisBlock;
\r
1286 uint256 GetBlockHash()
\r
1288 // Find the first block the caller has in the main chain
\r
1289 foreach(const uint256& hash, vHave)
\r
1291 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1292 if (mi != mapBlockIndex.end())
\r
1294 CBlockIndex* pindex = (*mi).second;
\r
1295 if (pindex->IsInMainChain())
\r
1299 return hashGenesisBlock;
\r
1304 CBlockIndex* pindex = GetBlockIndex();
\r
1307 return pindex->nHeight;
\r
1322 extern map<uint256, CTransaction> mapTransactions;
\r
1323 extern map<uint256, CWalletTx> mapWallet;
\r
1324 extern vector<pair<uint256, bool> > vWalletUpdated;
\r
1325 extern CCriticalSection cs_mapWallet;
\r
1326 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1327 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1328 extern CCriticalSection cs_mapKeys;
\r
1329 extern CKey keyUser;
\r