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
44 extern int fLimitProcessors;
\r
45 extern int nLimitProcessors;
\r
54 bool CheckDiskSpace(int64 nAdditionalBytes=0);
\r
55 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
\r
56 FILE* AppendBlockFile(unsigned int& nFileRet);
\r
57 bool AddKey(const CKey& key);
\r
58 vector<unsigned char> GenerateNewKey();
\r
59 bool AddToWallet(const CWalletTx& wtxIn);
\r
60 void ReacceptWalletTransactions();
\r
61 void RelayWalletTransactions();
\r
62 bool LoadBlockIndex(bool fAllowNew=true);
\r
63 void PrintBlockTree();
\r
64 bool ProcessMessages(CNode* pfrom);
\r
65 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
66 bool SendMessages(CNode* pto);
\r
68 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
69 bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key);
\r
70 bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);
\r
71 void GenerateBitcoins(bool fGenerate);
\r
72 void ThreadBitcoinMiner(void* parg);
\r
73 bool BitcoinMiner();
\r
90 unsigned int nBlockPos;
\r
91 unsigned int nTxPos;
\r
98 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
101 nBlockPos = nBlockPosIn;
\r
105 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
106 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
107 bool IsNull() const { return (nFile == -1); }
\r
109 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
111 return (a.nFile == b.nFile &&
\r
112 a.nBlockPos == b.nBlockPos &&
\r
113 a.nTxPos == b.nTxPos);
\r
116 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
121 string ToString() const
\r
124 return strprintf("null");
\r
126 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
131 printf("%s", ToString().c_str());
\r
144 CInPoint() { SetNull(); }
\r
145 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
146 void SetNull() { ptx = NULL; n = -1; }
\r
147 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
159 COutPoint() { SetNull(); }
\r
160 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
161 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
162 void SetNull() { hash = 0; n = -1; }
\r
163 bool IsNull() const { return (hash == 0 && n == -1); }
\r
165 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
167 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
170 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
172 return (a.hash == b.hash && a.n == b.n);
\r
175 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
180 string ToString() const
\r
182 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
187 printf("%s\n", ToString().c_str());
\r
195 // An input of a transaction. It contains the location of the previous
\r
196 // transaction's output that it claims and a signature that matches the
\r
197 // output's public key.
\r
204 unsigned int nSequence;
\r
208 nSequence = UINT_MAX;
\r
211 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
213 prevout = prevoutIn;
\r
214 scriptSig = scriptSigIn;
\r
215 nSequence = nSequenceIn;
\r
218 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
220 prevout = COutPoint(hashPrevTx, nOut);
\r
221 scriptSig = scriptSigIn;
\r
222 nSequence = nSequenceIn;
\r
225 IMPLEMENT_SERIALIZE
\r
227 READWRITE(prevout);
\r
228 READWRITE(scriptSig);
\r
229 READWRITE(nSequence);
\r
232 bool IsFinal() const
\r
234 return (nSequence == UINT_MAX);
\r
237 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
239 return (a.prevout == b.prevout &&
\r
240 a.scriptSig == b.scriptSig &&
\r
241 a.nSequence == b.nSequence);
\r
244 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
249 string ToString() const
\r
252 str += strprintf("CTxIn(");
\r
253 str += prevout.ToString();
\r
254 if (prevout.IsNull())
\r
255 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
257 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
258 if (nSequence != UINT_MAX)
\r
259 str += strprintf(", nSequence=%u", nSequence);
\r
266 printf("%s\n", ToString().c_str());
\r
269 bool IsMine() const;
\r
270 int64 GetDebit() const;
\r
277 // An output of a transaction. It contains the public key that the next input
\r
278 // must be able to sign with to claim it.
\r
284 CScript scriptPubKey;
\r
292 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
295 scriptPubKey = scriptPubKeyIn;
\r
298 IMPLEMENT_SERIALIZE
\r
301 READWRITE(scriptPubKey);
\r
307 scriptPubKey.clear();
\r
312 return (nValue == -1);
\r
315 uint256 GetHash() const
\r
317 return SerializeHash(*this);
\r
320 bool IsMine() const
\r
322 return ::IsMine(scriptPubKey);
\r
325 int64 GetCredit() const
\r
332 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
334 return (a.nValue == b.nValue &&
\r
335 a.scriptPubKey == b.scriptPubKey);
\r
338 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
343 string ToString() const
\r
345 if (scriptPubKey.size() < 6)
\r
346 return "CTxOut(error)";
\r
347 return strprintf("CTxOut(nValue=%I64d.%08I64d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
352 printf("%s\n", ToString().c_str());
\r
360 // The basic transaction that is broadcasted on the network and contained in
\r
361 // blocks. A transaction can contain multiple inputs and outputs.
\r
368 vector<CTxOut> vout;
\r
377 IMPLEMENT_SERIALIZE
\r
379 READWRITE(this->nVersion);
\r
380 nVersion = this->nVersion;
\r
383 READWRITE(nLockTime);
\r
394 bool IsNull() const
\r
396 return (vin.empty() && vout.empty());
\r
399 uint256 GetHash() const
\r
401 return SerializeHash(*this);
\r
404 bool IsFinal() const
\r
406 if (nLockTime == 0 || nLockTime < nBestHeight)
\r
408 foreach(const CTxIn& txin, vin)
\r
409 if (!txin.IsFinal())
\r
414 bool IsNewerThan(const CTransaction& old) const
\r
416 if (vin.size() != old.vin.size())
\r
418 for (int i = 0; i < vin.size(); i++)
\r
419 if (vin[i].prevout != old.vin[i].prevout)
\r
422 bool fNewer = false;
\r
423 unsigned int nLowest = UINT_MAX;
\r
424 for (int i = 0; i < vin.size(); i++)
\r
426 if (vin[i].nSequence != old.vin[i].nSequence)
\r
428 if (vin[i].nSequence <= nLowest)
\r
431 nLowest = vin[i].nSequence;
\r
433 if (old.vin[i].nSequence < nLowest)
\r
436 nLowest = old.vin[i].nSequence;
\r
443 bool IsCoinBase() const
\r
445 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
448 bool CheckTransaction() const
\r
450 // Basic checks that don't depend on any context
\r
451 if (vin.empty() || vout.empty())
\r
452 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
454 // Check for negative values
\r
455 foreach(const CTxOut& txout, vout)
\r
456 if (txout.nValue < 0)
\r
457 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
461 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
462 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
466 foreach(const CTxIn& txin, vin)
\r
467 if (txin.prevout.IsNull())
\r
468 return error("CTransaction::CheckTransaction() : prevout is null");
\r
474 bool IsMine() const
\r
476 foreach(const CTxOut& txout, vout)
\r
477 if (txout.IsMine())
\r
482 int64 GetDebit() const
\r
485 foreach(const CTxIn& txin, vin)
\r
486 nDebit += txin.GetDebit();
\r
490 int64 GetCredit() const
\r
493 foreach(const CTxOut& txout, vout)
\r
494 nCredit += txout.GetCredit();
\r
498 int64 GetValueOut() const
\r
500 int64 nValueOut = 0;
\r
501 foreach(const CTxOut& txout, vout)
\r
503 if (txout.nValue < 0)
\r
504 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
505 nValueOut += txout.nValue;
\r
510 int64 GetMinFee(bool fDiscount=false) const
\r
512 // Base fee is 1 cent per kilobyte
\r
513 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
514 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
516 // First 100 transactions in a block are free
\r
517 if (fDiscount && nBytes < 10000)
\r
520 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
521 if (nMinFee < CENT)
\r
522 foreach(const CTxOut& txout, vout)
\r
523 if (txout.nValue < CENT)
\r
531 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
533 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
535 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
537 // Read transaction
\r
538 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
539 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
542 // Return file pointer
\r
545 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
546 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
547 *pfileRet = filein.release();
\r
553 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
555 return (a.nVersion == b.nVersion &&
\r
557 a.vout == b.vout &&
\r
558 a.nLockTime == b.nLockTime);
\r
561 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
567 string ToString() const
\r
570 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
571 GetHash().ToString().substr(0,6).c_str(),
\r
576 for (int i = 0; i < vin.size(); i++)
\r
577 str += " " + vin[i].ToString() + "\n";
\r
578 for (int i = 0; i < vout.size(); i++)
\r
579 str += " " + vout[i].ToString() + "\n";
\r
585 printf("%s", ToString().c_str());
\r
590 bool DisconnectInputs(CTxDB& txdb);
\r
591 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
592 bool ClientConnectInputs();
\r
594 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
596 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
599 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
603 bool AddToMemoryPool();
\r
605 bool RemoveFromMemoryPool();
\r
613 // A transaction with a merkle branch linking it to the block chain
\r
615 class CMerkleTx : public CTransaction
\r
619 vector<uint256> vMerkleBranch;
\r
623 mutable bool fMerkleVerified;
\r
631 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
640 fMerkleVerified = false;
\r
643 int64 GetCredit() const
\r
645 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
646 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
648 return CTransaction::GetCredit();
\r
651 IMPLEMENT_SERIALIZE
\r
653 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
654 nVersion = this->nVersion;
\r
655 READWRITE(hashBlock);
\r
656 READWRITE(vMerkleBranch);
\r
661 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
662 int GetDepthInMainChain() const;
\r
663 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
664 int GetBlocksToMaturity() const;
\r
665 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
666 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
673 // A transaction with a bunch of additional info that only the owner cares
\r
674 // about. It includes any unrecorded transactions needed to link it back
\r
675 // to the block chain.
\r
677 class CWalletTx : public CMerkleTx
\r
680 vector<CMerkleTx> vtxPrev;
\r
681 map<string, string> mapValue;
\r
682 vector<pair<string, string> > vOrderForm;
\r
683 unsigned int fTimeReceivedIsTxTime;
\r
684 unsigned int nTimeReceived; // time received by this node
\r
687 //// probably need to sign the order info so know it came from payer
\r
690 mutable unsigned int nTimeDisplayed;
\r
698 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
703 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
710 fTimeReceivedIsTxTime = false;
\r
714 nTimeDisplayed = 0;
\r
717 IMPLEMENT_SERIALIZE
\r
719 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
720 nVersion = this->nVersion;
\r
721 READWRITE(vtxPrev);
\r
722 READWRITE(mapValue);
\r
723 READWRITE(vOrderForm);
\r
724 READWRITE(fTimeReceivedIsTxTime);
\r
725 READWRITE(nTimeReceived);
\r
726 READWRITE(fFromMe);
\r
732 return CWalletDB().WriteTx(GetHash(), *this);
\r
736 int64 GetTxTime() const;
\r
738 void AddSupportingTransactions(CTxDB& txdb);
\r
740 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
741 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
743 void RelayWalletTransaction(CTxDB& txdb);
\r
744 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
751 // A txdb record that contains the disk location of a transaction and the
\r
752 // locations of transactions that spend its outputs. vSpent is really only
\r
753 // used as a flag, but having the location is very helpful for debugging.
\r
759 vector<CDiskTxPos> vSpent;
\r
766 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
769 vSpent.resize(nOutputs);
\r
772 IMPLEMENT_SERIALIZE
\r
774 if (!(nType & SER_GETHASH))
\r
775 READWRITE(nVersion);
\r
788 return pos.IsNull();
\r
791 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
793 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
795 for (int i = 0; i < a.vSpent.size(); i++)
\r
796 if (a.vSpent[i] != b.vSpent[i])
\r
801 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
812 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
813 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
814 // requirements. When they solve the proof-of-work, they broadcast the block
\r
815 // to everyone and the block is added to the block chain. The first transaction
\r
816 // in the block is a special one that creates a new coin owned by the creator
\r
819 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
820 // is indexed by CBlockIndex objects in memory.
\r
827 uint256 hashPrevBlock;
\r
828 uint256 hashMerkleRoot;
\r
829 unsigned int nTime;
\r
830 unsigned int nBits;
\r
831 unsigned int nNonce;
\r
833 // network and disk
\r
834 vector<CTransaction> vtx;
\r
837 mutable vector<uint256> vMerkleTree;
\r
845 IMPLEMENT_SERIALIZE
\r
847 READWRITE(this->nVersion);
\r
848 nVersion = this->nVersion;
\r
849 READWRITE(hashPrevBlock);
\r
850 READWRITE(hashMerkleRoot);
\r
855 // ConnectBlock depends on vtx being last so it can calculate offset
\r
856 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
859 const_cast<CBlock*>(this)->vtx.clear();
\r
866 hashMerkleRoot = 0;
\r
871 vMerkleTree.clear();
\r
874 bool IsNull() const
\r
876 return (nBits == 0);
\r
879 uint256 GetHash() const
\r
881 return Hash(BEGIN(nVersion), END(nNonce));
\r
885 uint256 BuildMerkleTree() const
\r
887 vMerkleTree.clear();
\r
888 foreach(const CTransaction& tx, vtx)
\r
889 vMerkleTree.push_back(tx.GetHash());
\r
891 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
893 for (int i = 0; i < nSize; i += 2)
\r
895 int i2 = min(i+1, nSize-1);
\r
896 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
897 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
901 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
904 vector<uint256> GetMerkleBranch(int nIndex) const
\r
906 if (vMerkleTree.empty())
\r
908 vector<uint256> vMerkleBranch;
\r
910 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
912 int i = min(nIndex^1, nSize-1);
\r
913 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
917 return vMerkleBranch;
\r
920 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
924 foreach(const uint256& otherside, vMerkleBranch)
\r
927 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
929 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
936 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
938 // Open history file to append
\r
939 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
941 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
942 if (!fWriteTransactions)
\r
943 fileout.nType |= SER_BLOCKHEADERONLY;
\r
945 // Write index header
\r
946 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
947 fileout << FLATDATA(pchMessageStart) << nSize;
\r
950 nBlockPosRet = ftell(fileout);
\r
951 if (nBlockPosRet == -1)
\r
952 return error("CBlock::WriteToDisk() : ftell failed");
\r
958 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)
\r
962 // Open history file to read
\r
963 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
965 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
966 if (!fReadTransactions)
\r
967 filein.nType |= SER_BLOCKHEADERONLY;
\r
972 // Check the header
\r
973 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
974 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
975 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
976 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
985 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
986 GetHash().ToString().substr(0,14).c_str(),
\r
988 hashPrevBlock.ToString().substr(0,14).c_str(),
\r
989 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
990 nTime, nBits, nNonce,
\r
992 for (int i = 0; i < vtx.size(); i++)
\r
997 printf(" vMerkleTree: ");
\r
998 for (int i = 0; i < vMerkleTree.size(); i++)
\r
999 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1004 int64 GetBlockValue(int64 nFees) const;
\r
1005 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1006 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1007 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions);
\r
1008 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1009 bool CheckBlock() const;
\r
1010 bool AcceptBlock();
\r
1019 // The block chain is a tree shaped structure starting with the
\r
1020 // genesis block at the root, with each block potentially having multiple
\r
1021 // candidates to be the next block. pprev and pnext link a path through the
\r
1022 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1023 // to it, but pnext will only point forward to the longest branch, or will
\r
1024 // be null if the block is not part of the longest chain.
\r
1029 const uint256* phashBlock;
\r
1030 CBlockIndex* pprev;
\r
1031 CBlockIndex* pnext;
\r
1032 unsigned int nFile;
\r
1033 unsigned int nBlockPos;
\r
1038 uint256 hashMerkleRoot;
\r
1039 unsigned int nTime;
\r
1040 unsigned int nBits;
\r
1041 unsigned int nNonce;
\r
1046 phashBlock = NULL;
\r
1054 hashMerkleRoot = 0;
\r
1060 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1062 phashBlock = NULL;
\r
1066 nBlockPos = nBlockPosIn;
\r
1069 nVersion = block.nVersion;
\r
1070 hashMerkleRoot = block.hashMerkleRoot;
\r
1071 nTime = block.nTime;
\r
1072 nBits = block.nBits;
\r
1073 nNonce = block.nNonce;
\r
1076 uint256 GetBlockHash() const
\r
1078 return *phashBlock;
\r
1081 bool IsInMainChain() const
\r
1083 return (pnext || this == pindexBest);
\r
1086 bool EraseBlockFromDisk()
\r
1088 // Open history file
\r
1089 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1093 // Overwrite with empty null block
\r
1101 enum { nMedianTimeSpan=11 };
\r
1103 int64 GetMedianTimePast() const
\r
1105 unsigned int pmedian[nMedianTimeSpan];
\r
1106 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1107 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1109 const CBlockIndex* pindex = this;
\r
1110 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1111 *(--pbegin) = pindex->nTime;
\r
1113 sort(pbegin, pend);
\r
1114 return pbegin[(pend - pbegin)/2];
\r
1117 int64 GetMedianTime() const
\r
1119 const CBlockIndex* pindex = this;
\r
1120 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1122 if (!pindex->pnext)
\r
1124 pindex = pindex->pnext;
\r
1126 return pindex->GetMedianTimePast();
\r
1131 string ToString() const
\r
1133 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1134 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1135 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1136 GetBlockHash().ToString().substr(0,14).c_str());
\r
1139 void print() const
\r
1141 printf("%s\n", ToString().c_str());
\r
1148 // Used to marshal pointers into hashes for db storage.
\r
1150 class CDiskBlockIndex : public CBlockIndex
\r
1162 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1164 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1165 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1168 IMPLEMENT_SERIALIZE
\r
1170 if (!(nType & SER_GETHASH))
\r
1171 READWRITE(nVersion);
\r
1173 READWRITE(hashNext);
\r
1175 READWRITE(nBlockPos);
\r
1176 READWRITE(nHeight);
\r
1179 READWRITE(this->nVersion);
\r
1180 READWRITE(hashPrev);
\r
1181 READWRITE(hashMerkleRoot);
\r
1184 READWRITE(nNonce);
\r
1187 uint256 GetBlockHash() const
\r
1190 block.nVersion = nVersion;
\r
1191 block.hashPrevBlock = hashPrev;
\r
1192 block.hashMerkleRoot = hashMerkleRoot;
\r
1193 block.nTime = nTime;
\r
1194 block.nBits = nBits;
\r
1195 block.nNonce = nNonce;
\r
1196 return block.GetHash();
\r
1200 string ToString() const
\r
1202 string str = "CDiskBlockIndex(";
\r
1203 str += CBlockIndex::ToString();
\r
1204 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1205 GetBlockHash().ToString().c_str(),
\r
1206 hashPrev.ToString().substr(0,14).c_str(),
\r
1207 hashNext.ToString().substr(0,14).c_str());
\r
1211 void print() const
\r
1213 printf("%s\n", ToString().c_str());
\r
1225 // Describes a place in the block chain to another node such that if the
\r
1226 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1227 // The further back it is, the further before the fork it may be.
\r
1229 class CBlockLocator
\r
1232 vector<uint256> vHave;
\r
1239 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1244 explicit CBlockLocator(uint256 hashBlock)
\r
1246 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1247 if (mi != mapBlockIndex.end())
\r
1248 Set((*mi).second);
\r
1251 IMPLEMENT_SERIALIZE
\r
1253 if (!(nType & SER_GETHASH))
\r
1254 READWRITE(nVersion);
\r
1258 void Set(const CBlockIndex* pindex)
\r
1264 vHave.push_back(pindex->GetBlockHash());
\r
1266 // Exponentially larger steps back
\r
1267 for (int i = 0; pindex && i < nStep; i++)
\r
1268 pindex = pindex->pprev;
\r
1269 if (vHave.size() > 10)
\r
1272 vHave.push_back(hashGenesisBlock);
\r
1275 CBlockIndex* GetBlockIndex()
\r
1277 // Find the first block the caller has in the main chain
\r
1278 foreach(const uint256& hash, vHave)
\r
1280 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1281 if (mi != mapBlockIndex.end())
\r
1283 CBlockIndex* pindex = (*mi).second;
\r
1284 if (pindex->IsInMainChain())
\r
1288 return pindexGenesisBlock;
\r
1291 uint256 GetBlockHash()
\r
1293 // Find the first block the caller has in the main chain
\r
1294 foreach(const uint256& hash, vHave)
\r
1296 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1297 if (mi != mapBlockIndex.end())
\r
1299 CBlockIndex* pindex = (*mi).second;
\r
1300 if (pindex->IsInMainChain())
\r
1304 return hashGenesisBlock;
\r
1309 CBlockIndex* pindex = GetBlockIndex();
\r
1312 return pindex->nHeight;
\r
1327 extern map<uint256, CTransaction> mapTransactions;
\r
1328 extern map<uint256, CWalletTx> mapWallet;
\r
1329 extern vector<uint256> vWalletUpdated;
\r
1330 extern CCriticalSection cs_mapWallet;
\r
1331 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1332 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1333 extern CCriticalSection cs_mapKeys;
\r
1334 extern CKey keyUser;
\r