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
369 unsigned int nLockTime;
\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(int64 nBlockTime=0) const
\r
406 // Time based nLockTime implemented in 0.1.6,
\r
407 // do not use time based until most 0.1.5 nodes have upgraded.
\r
408 if (nBlockTime == 0)
\r
409 nBlockTime = GetAdjustedTime();
\r
410 if (nLockTime == 0)
\r
412 if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))
\r
414 foreach(const CTxIn& txin, vin)
\r
415 if (!txin.IsFinal())
\r
420 bool IsNewerThan(const CTransaction& old) const
\r
422 if (vin.size() != old.vin.size())
\r
424 for (int i = 0; i < vin.size(); i++)
\r
425 if (vin[i].prevout != old.vin[i].prevout)
\r
428 bool fNewer = false;
\r
429 unsigned int nLowest = UINT_MAX;
\r
430 for (int i = 0; i < vin.size(); i++)
\r
432 if (vin[i].nSequence != old.vin[i].nSequence)
\r
434 if (vin[i].nSequence <= nLowest)
\r
437 nLowest = vin[i].nSequence;
\r
439 if (old.vin[i].nSequence < nLowest)
\r
442 nLowest = old.vin[i].nSequence;
\r
449 bool IsCoinBase() const
\r
451 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
454 bool CheckTransaction() const
\r
456 // Basic checks that don't depend on any context
\r
457 if (vin.empty() || vout.empty())
\r
458 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
460 // Check for negative values
\r
461 foreach(const CTxOut& txout, vout)
\r
462 if (txout.nValue < 0)
\r
463 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
467 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
468 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
472 foreach(const CTxIn& txin, vin)
\r
473 if (txin.prevout.IsNull())
\r
474 return error("CTransaction::CheckTransaction() : prevout is null");
\r
480 bool IsMine() const
\r
482 foreach(const CTxOut& txout, vout)
\r
483 if (txout.IsMine())
\r
488 int64 GetDebit() const
\r
491 foreach(const CTxIn& txin, vin)
\r
492 nDebit += txin.GetDebit();
\r
496 int64 GetCredit() const
\r
499 foreach(const CTxOut& txout, vout)
\r
500 nCredit += txout.GetCredit();
\r
504 int64 GetValueOut() const
\r
506 int64 nValueOut = 0;
\r
507 foreach(const CTxOut& txout, vout)
\r
509 if (txout.nValue < 0)
\r
510 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
511 nValueOut += txout.nValue;
\r
516 int64 GetMinFee(bool fDiscount=false) const
\r
518 // Base fee is 1 cent per kilobyte
\r
519 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
520 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
522 // First 100 transactions in a block are free
\r
523 if (fDiscount && nBytes < 10000)
\r
526 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
527 if (nMinFee < CENT)
\r
528 foreach(const CTxOut& txout, vout)
\r
529 if (txout.nValue < CENT)
\r
537 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
539 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
541 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
543 // Read transaction
\r
544 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
545 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
548 // Return file pointer
\r
551 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
552 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
553 *pfileRet = filein.release();
\r
559 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
561 return (a.nVersion == b.nVersion &&
\r
563 a.vout == b.vout &&
\r
564 a.nLockTime == b.nLockTime);
\r
567 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
573 string ToString() const
\r
576 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
577 GetHash().ToString().substr(0,6).c_str(),
\r
582 for (int i = 0; i < vin.size(); i++)
\r
583 str += " " + vin[i].ToString() + "\n";
\r
584 for (int i = 0; i < vout.size(); i++)
\r
585 str += " " + vout[i].ToString() + "\n";
\r
591 printf("%s", ToString().c_str());
\r
596 bool DisconnectInputs(CTxDB& txdb);
\r
597 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
598 bool ClientConnectInputs();
\r
600 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
602 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
605 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
609 bool AddToMemoryPool();
\r
611 bool RemoveFromMemoryPool();
\r
619 // A transaction with a merkle branch linking it to the block chain
\r
621 class CMerkleTx : public CTransaction
\r
625 vector<uint256> vMerkleBranch;
\r
629 mutable bool fMerkleVerified;
\r
637 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
646 fMerkleVerified = false;
\r
649 int64 GetCredit() const
\r
651 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
652 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
654 return CTransaction::GetCredit();
\r
657 IMPLEMENT_SERIALIZE
\r
659 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
660 nVersion = this->nVersion;
\r
661 READWRITE(hashBlock);
\r
662 READWRITE(vMerkleBranch);
\r
667 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
668 int GetDepthInMainChain() const;
\r
669 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
670 int GetBlocksToMaturity() const;
\r
671 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
672 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
679 // A transaction with a bunch of additional info that only the owner cares
\r
680 // about. It includes any unrecorded transactions needed to link it back
\r
681 // to the block chain.
\r
683 class CWalletTx : public CMerkleTx
\r
686 vector<CMerkleTx> vtxPrev;
\r
687 map<string, string> mapValue;
\r
688 vector<pair<string, string> > vOrderForm;
\r
689 unsigned int fTimeReceivedIsTxTime;
\r
690 unsigned int nTimeReceived; // time received by this node
\r
693 //// probably need to sign the order info so know it came from payer
\r
695 // memory only UI hints
\r
696 mutable unsigned int nTimeDisplayed;
\r
697 mutable int nLinesDisplayed;
\r
705 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
710 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
717 fTimeReceivedIsTxTime = false;
\r
721 nTimeDisplayed = 0;
\r
722 nLinesDisplayed = 0;
\r
725 IMPLEMENT_SERIALIZE
\r
727 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
728 nVersion = this->nVersion;
\r
729 READWRITE(vtxPrev);
\r
730 READWRITE(mapValue);
\r
731 READWRITE(vOrderForm);
\r
732 READWRITE(fTimeReceivedIsTxTime);
\r
733 READWRITE(nTimeReceived);
\r
734 READWRITE(fFromMe);
\r
740 return CWalletDB().WriteTx(GetHash(), *this);
\r
744 int64 GetTxTime() const;
\r
746 void AddSupportingTransactions(CTxDB& txdb);
\r
748 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
749 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
751 void RelayWalletTransaction(CTxDB& txdb);
\r
752 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
759 // A txdb record that contains the disk location of a transaction and the
\r
760 // locations of transactions that spend its outputs. vSpent is really only
\r
761 // used as a flag, but having the location is very helpful for debugging.
\r
767 vector<CDiskTxPos> vSpent;
\r
774 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
777 vSpent.resize(nOutputs);
\r
780 IMPLEMENT_SERIALIZE
\r
782 if (!(nType & SER_GETHASH))
\r
783 READWRITE(nVersion);
\r
796 return pos.IsNull();
\r
799 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
801 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
803 for (int i = 0; i < a.vSpent.size(); i++)
\r
804 if (a.vSpent[i] != b.vSpent[i])
\r
809 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
820 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
821 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
822 // requirements. When they solve the proof-of-work, they broadcast the block
\r
823 // to everyone and the block is added to the block chain. The first transaction
\r
824 // in the block is a special one that creates a new coin owned by the creator
\r
827 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
828 // is indexed by CBlockIndex objects in memory.
\r
835 uint256 hashPrevBlock;
\r
836 uint256 hashMerkleRoot;
\r
837 unsigned int nTime;
\r
838 unsigned int nBits;
\r
839 unsigned int nNonce;
\r
841 // network and disk
\r
842 vector<CTransaction> vtx;
\r
845 mutable vector<uint256> vMerkleTree;
\r
853 IMPLEMENT_SERIALIZE
\r
855 READWRITE(this->nVersion);
\r
856 nVersion = this->nVersion;
\r
857 READWRITE(hashPrevBlock);
\r
858 READWRITE(hashMerkleRoot);
\r
863 // ConnectBlock depends on vtx being last so it can calculate offset
\r
864 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
867 const_cast<CBlock*>(this)->vtx.clear();
\r
874 hashMerkleRoot = 0;
\r
879 vMerkleTree.clear();
\r
882 bool IsNull() const
\r
884 return (nBits == 0);
\r
887 uint256 GetHash() const
\r
889 return Hash(BEGIN(nVersion), END(nNonce));
\r
893 uint256 BuildMerkleTree() const
\r
895 vMerkleTree.clear();
\r
896 foreach(const CTransaction& tx, vtx)
\r
897 vMerkleTree.push_back(tx.GetHash());
\r
899 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
901 for (int i = 0; i < nSize; i += 2)
\r
903 int i2 = min(i+1, nSize-1);
\r
904 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
905 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
909 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
912 vector<uint256> GetMerkleBranch(int nIndex) const
\r
914 if (vMerkleTree.empty())
\r
916 vector<uint256> vMerkleBranch;
\r
918 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
920 int i = min(nIndex^1, nSize-1);
\r
921 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
925 return vMerkleBranch;
\r
928 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
932 foreach(const uint256& otherside, vMerkleBranch)
\r
935 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
937 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
944 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
946 // Open history file to append
\r
947 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
949 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
950 if (!fWriteTransactions)
\r
951 fileout.nType |= SER_BLOCKHEADERONLY;
\r
953 // Write index header
\r
954 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
955 fileout << FLATDATA(pchMessageStart) << nSize;
\r
958 nBlockPosRet = ftell(fileout);
\r
959 if (nBlockPosRet == -1)
\r
960 return error("CBlock::WriteToDisk() : ftell failed");
\r
966 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)
\r
970 // Open history file to read
\r
971 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
973 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
974 if (!fReadTransactions)
\r
975 filein.nType |= SER_BLOCKHEADERONLY;
\r
980 // Check the header
\r
981 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
982 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
983 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
984 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
993 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
994 GetHash().ToString().substr(0,14).c_str(),
\r
996 hashPrevBlock.ToString().substr(0,14).c_str(),
\r
997 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
998 nTime, nBits, nNonce,
\r
1000 for (int i = 0; i < vtx.size(); i++)
\r
1005 printf(" vMerkleTree: ");
\r
1006 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1007 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1012 int64 GetBlockValue(int64 nFees) const;
\r
1013 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1014 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1015 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions);
\r
1016 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1017 bool CheckBlock() const;
\r
1018 bool AcceptBlock();
\r
1027 // The block chain is a tree shaped structure starting with the
\r
1028 // genesis block at the root, with each block potentially having multiple
\r
1029 // candidates to be the next block. pprev and pnext link a path through the
\r
1030 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1031 // to it, but pnext will only point forward to the longest branch, or will
\r
1032 // be null if the block is not part of the longest chain.
\r
1037 const uint256* phashBlock;
\r
1038 CBlockIndex* pprev;
\r
1039 CBlockIndex* pnext;
\r
1040 unsigned int nFile;
\r
1041 unsigned int nBlockPos;
\r
1046 uint256 hashMerkleRoot;
\r
1047 unsigned int nTime;
\r
1048 unsigned int nBits;
\r
1049 unsigned int nNonce;
\r
1054 phashBlock = NULL;
\r
1062 hashMerkleRoot = 0;
\r
1068 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1070 phashBlock = NULL;
\r
1074 nBlockPos = nBlockPosIn;
\r
1077 nVersion = block.nVersion;
\r
1078 hashMerkleRoot = block.hashMerkleRoot;
\r
1079 nTime = block.nTime;
\r
1080 nBits = block.nBits;
\r
1081 nNonce = block.nNonce;
\r
1084 uint256 GetBlockHash() const
\r
1086 return *phashBlock;
\r
1089 bool IsInMainChain() const
\r
1091 return (pnext || this == pindexBest);
\r
1094 bool EraseBlockFromDisk()
\r
1096 // Open history file
\r
1097 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1101 // Overwrite with empty null block
\r
1109 enum { nMedianTimeSpan=11 };
\r
1111 int64 GetMedianTimePast() const
\r
1113 unsigned int pmedian[nMedianTimeSpan];
\r
1114 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1115 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1117 const CBlockIndex* pindex = this;
\r
1118 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1119 *(--pbegin) = pindex->nTime;
\r
1121 sort(pbegin, pend);
\r
1122 return pbegin[(pend - pbegin)/2];
\r
1125 int64 GetMedianTime() const
\r
1127 const CBlockIndex* pindex = this;
\r
1128 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1130 if (!pindex->pnext)
\r
1132 pindex = pindex->pnext;
\r
1134 return pindex->GetMedianTimePast();
\r
1139 string ToString() const
\r
1141 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1142 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1143 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1144 GetBlockHash().ToString().substr(0,14).c_str());
\r
1147 void print() const
\r
1149 printf("%s\n", ToString().c_str());
\r
1156 // Used to marshal pointers into hashes for db storage.
\r
1158 class CDiskBlockIndex : public CBlockIndex
\r
1170 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1172 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1173 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1176 IMPLEMENT_SERIALIZE
\r
1178 if (!(nType & SER_GETHASH))
\r
1179 READWRITE(nVersion);
\r
1181 READWRITE(hashNext);
\r
1183 READWRITE(nBlockPos);
\r
1184 READWRITE(nHeight);
\r
1187 READWRITE(this->nVersion);
\r
1188 READWRITE(hashPrev);
\r
1189 READWRITE(hashMerkleRoot);
\r
1192 READWRITE(nNonce);
\r
1195 uint256 GetBlockHash() const
\r
1198 block.nVersion = nVersion;
\r
1199 block.hashPrevBlock = hashPrev;
\r
1200 block.hashMerkleRoot = hashMerkleRoot;
\r
1201 block.nTime = nTime;
\r
1202 block.nBits = nBits;
\r
1203 block.nNonce = nNonce;
\r
1204 return block.GetHash();
\r
1208 string ToString() const
\r
1210 string str = "CDiskBlockIndex(";
\r
1211 str += CBlockIndex::ToString();
\r
1212 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1213 GetBlockHash().ToString().c_str(),
\r
1214 hashPrev.ToString().substr(0,14).c_str(),
\r
1215 hashNext.ToString().substr(0,14).c_str());
\r
1219 void print() const
\r
1221 printf("%s\n", ToString().c_str());
\r
1233 // Describes a place in the block chain to another node such that if the
\r
1234 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1235 // The further back it is, the further before the fork it may be.
\r
1237 class CBlockLocator
\r
1240 vector<uint256> vHave;
\r
1247 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1252 explicit CBlockLocator(uint256 hashBlock)
\r
1254 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1255 if (mi != mapBlockIndex.end())
\r
1256 Set((*mi).second);
\r
1259 IMPLEMENT_SERIALIZE
\r
1261 if (!(nType & SER_GETHASH))
\r
1262 READWRITE(nVersion);
\r
1266 void Set(const CBlockIndex* pindex)
\r
1272 vHave.push_back(pindex->GetBlockHash());
\r
1274 // Exponentially larger steps back
\r
1275 for (int i = 0; pindex && i < nStep; i++)
\r
1276 pindex = pindex->pprev;
\r
1277 if (vHave.size() > 10)
\r
1280 vHave.push_back(hashGenesisBlock);
\r
1283 CBlockIndex* GetBlockIndex()
\r
1285 // Find the first block the caller has in the main chain
\r
1286 foreach(const uint256& hash, vHave)
\r
1288 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1289 if (mi != mapBlockIndex.end())
\r
1291 CBlockIndex* pindex = (*mi).second;
\r
1292 if (pindex->IsInMainChain())
\r
1296 return pindexGenesisBlock;
\r
1299 uint256 GetBlockHash()
\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 hashGenesisBlock;
\r
1317 CBlockIndex* pindex = GetBlockIndex();
\r
1320 return pindex->nHeight;
\r
1335 extern map<uint256, CTransaction> mapTransactions;
\r
1336 extern map<uint256, CWalletTx> mapWallet;
\r
1337 extern vector<uint256> vWalletUpdated;
\r
1338 extern CCriticalSection cs_mapWallet;
\r
1339 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1340 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1341 extern CCriticalSection cs_mapKeys;
\r
1342 extern CKey keyUser;
\r