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 map<uint256, int> mapRequestCount;
\r
38 extern CCriticalSection cs_mapRequestCount;
\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
53 bool CheckDiskSpace(int64 nAdditionalBytes=0);
\r
54 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
\r
55 FILE* AppendBlockFile(unsigned int& nFileRet);
\r
56 bool AddKey(const CKey& key);
\r
57 vector<unsigned char> GenerateNewKey();
\r
58 bool AddToWallet(const CWalletTx& wtxIn);
\r
59 void ReacceptWalletTransactions();
\r
60 void RelayWalletTransactions();
\r
61 bool LoadBlockIndex(bool fAllowNew=true);
\r
62 void PrintBlockTree();
\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& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
68 bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key);
\r
69 bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);
\r
70 void GenerateBitcoins(bool fGenerate);
\r
71 void ThreadBitcoinMiner(void* parg);
\r
72 void BitcoinMiner();
\r
89 unsigned int nBlockPos;
\r
90 unsigned int nTxPos;
\r
97 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
100 nBlockPos = nBlockPosIn;
\r
104 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
105 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
106 bool IsNull() const { return (nFile == -1); }
\r
108 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
110 return (a.nFile == b.nFile &&
\r
111 a.nBlockPos == b.nBlockPos &&
\r
112 a.nTxPos == b.nTxPos);
\r
115 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
120 string ToString() const
\r
123 return strprintf("null");
\r
125 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
130 printf("%s", ToString().c_str());
\r
143 CInPoint() { SetNull(); }
\r
144 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
145 void SetNull() { ptx = NULL; n = -1; }
\r
146 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
158 COutPoint() { SetNull(); }
\r
159 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
160 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
161 void SetNull() { hash = 0; n = -1; }
\r
162 bool IsNull() const { return (hash == 0 && n == -1); }
\r
164 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
166 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
169 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
171 return (a.hash == b.hash && a.n == b.n);
\r
174 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
179 string ToString() const
\r
181 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
186 printf("%s\n", ToString().c_str());
\r
194 // An input of a transaction. It contains the location of the previous
\r
195 // transaction's output that it claims and a signature that matches the
\r
196 // output's public key.
\r
203 unsigned int nSequence;
\r
207 nSequence = UINT_MAX;
\r
210 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
212 prevout = prevoutIn;
\r
213 scriptSig = scriptSigIn;
\r
214 nSequence = nSequenceIn;
\r
217 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
219 prevout = COutPoint(hashPrevTx, nOut);
\r
220 scriptSig = scriptSigIn;
\r
221 nSequence = nSequenceIn;
\r
224 IMPLEMENT_SERIALIZE
\r
226 READWRITE(prevout);
\r
227 READWRITE(scriptSig);
\r
228 READWRITE(nSequence);
\r
231 bool IsFinal() const
\r
233 return (nSequence == UINT_MAX);
\r
236 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
238 return (a.prevout == b.prevout &&
\r
239 a.scriptSig == b.scriptSig &&
\r
240 a.nSequence == b.nSequence);
\r
243 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
248 string ToString() const
\r
251 str += strprintf("CTxIn(");
\r
252 str += prevout.ToString();
\r
253 if (prevout.IsNull())
\r
254 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
256 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
257 if (nSequence != UINT_MAX)
\r
258 str += strprintf(", nSequence=%u", nSequence);
\r
265 printf("%s\n", ToString().c_str());
\r
268 bool IsMine() const;
\r
269 int64 GetDebit() const;
\r
276 // An output of a transaction. It contains the public key that the next input
\r
277 // must be able to sign with to claim it.
\r
283 CScript scriptPubKey;
\r
291 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
294 scriptPubKey = scriptPubKeyIn;
\r
297 IMPLEMENT_SERIALIZE
\r
300 READWRITE(scriptPubKey);
\r
306 scriptPubKey.clear();
\r
311 return (nValue == -1);
\r
314 uint256 GetHash() const
\r
316 return SerializeHash(*this);
\r
319 bool IsMine() const
\r
321 return ::IsMine(scriptPubKey);
\r
324 int64 GetCredit() const
\r
331 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
333 return (a.nValue == b.nValue &&
\r
334 a.scriptPubKey == b.scriptPubKey);
\r
337 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
342 string ToString() const
\r
344 if (scriptPubKey.size() < 6)
\r
345 return "CTxOut(error)";
\r
346 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
351 printf("%s\n", ToString().c_str());
\r
359 // The basic transaction that is broadcasted on the network and contained in
\r
360 // blocks. A transaction can contain multiple inputs and outputs.
\r
367 vector<CTxOut> vout;
\r
368 unsigned int nLockTime;
\r
376 IMPLEMENT_SERIALIZE
\r
378 READWRITE(this->nVersion);
\r
379 nVersion = this->nVersion;
\r
382 READWRITE(nLockTime);
\r
393 bool IsNull() const
\r
395 return (vin.empty() && vout.empty());
\r
398 uint256 GetHash() const
\r
400 return SerializeHash(*this);
\r
403 bool IsFinal(int64 nBlockTime=0) const
\r
405 // Time based nLockTime implemented in 0.1.6,
\r
406 // do not use time based until most 0.1.5 nodes have upgraded.
\r
407 if (nLockTime == 0)
\r
409 if (nBlockTime == 0)
\r
410 nBlockTime = GetAdjustedTime();
\r
411 if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))
\r
413 foreach(const CTxIn& txin, vin)
\r
414 if (!txin.IsFinal())
\r
419 bool IsNewerThan(const CTransaction& old) const
\r
421 if (vin.size() != old.vin.size())
\r
423 for (int i = 0; i < vin.size(); i++)
\r
424 if (vin[i].prevout != old.vin[i].prevout)
\r
427 bool fNewer = false;
\r
428 unsigned int nLowest = UINT_MAX;
\r
429 for (int i = 0; i < vin.size(); i++)
\r
431 if (vin[i].nSequence != old.vin[i].nSequence)
\r
433 if (vin[i].nSequence <= nLowest)
\r
436 nLowest = vin[i].nSequence;
\r
438 if (old.vin[i].nSequence < nLowest)
\r
441 nLowest = old.vin[i].nSequence;
\r
448 bool IsCoinBase() const
\r
450 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
453 bool CheckTransaction() const
\r
455 // Basic checks that don't depend on any context
\r
456 if (vin.empty() || vout.empty())
\r
457 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
459 // Check for negative values
\r
460 foreach(const CTxOut& txout, vout)
\r
461 if (txout.nValue < 0)
\r
462 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
466 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
467 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
471 foreach(const CTxIn& txin, vin)
\r
472 if (txin.prevout.IsNull())
\r
473 return error("CTransaction::CheckTransaction() : prevout is null");
\r
479 bool IsMine() const
\r
481 foreach(const CTxOut& txout, vout)
\r
482 if (txout.IsMine())
\r
487 int64 GetDebit() const
\r
490 foreach(const CTxIn& txin, vin)
\r
491 nDebit += txin.GetDebit();
\r
495 int64 GetCredit() const
\r
498 foreach(const CTxOut& txout, vout)
\r
499 nCredit += txout.GetCredit();
\r
503 int64 GetValueOut() const
\r
505 int64 nValueOut = 0;
\r
506 foreach(const CTxOut& txout, vout)
\r
508 if (txout.nValue < 0)
\r
509 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
510 nValueOut += txout.nValue;
\r
515 int64 GetMinFee(unsigned int nBlockSize=1) const
\r
517 // Base fee is 1 cent per kilobyte
\r
518 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
519 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
521 // Transactions under 60K are free as long as block size is under 80K
\r
522 // (about 27,000bc if made of 50bc inputs)
\r
523 if (nBytes < 60000 && nBlockSize < 80000)
\r
526 // Transactions under 3K are free as long as block size is under 200K
\r
527 if (nBytes < 3000 && nBlockSize < 200000)
\r
530 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
531 if (nMinFee < CENT)
\r
532 foreach(const CTxOut& txout, vout)
\r
533 if (txout.nValue < CENT)
\r
541 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
543 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
545 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
547 // Read transaction
\r
548 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
549 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
552 // Return file pointer
\r
555 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
556 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
557 *pfileRet = filein.release();
\r
563 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
565 return (a.nVersion == b.nVersion &&
\r
567 a.vout == b.vout &&
\r
568 a.nLockTime == b.nLockTime);
\r
571 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
577 string ToString() const
\r
580 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
581 GetHash().ToString().substr(0,6).c_str(),
\r
586 for (int i = 0; i < vin.size(); i++)
\r
587 str += " " + vin[i].ToString() + "\n";
\r
588 for (int i = 0; i < vout.size(); i++)
\r
589 str += " " + vout[i].ToString() + "\n";
\r
595 printf("%s", ToString().c_str());
\r
600 bool DisconnectInputs(CTxDB& txdb);
\r
601 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
602 bool ClientConnectInputs();
\r
604 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
606 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
609 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
613 bool AddToMemoryPool();
\r
615 bool RemoveFromMemoryPool();
\r
623 // A transaction with a merkle branch linking it to the block chain
\r
625 class CMerkleTx : public CTransaction
\r
629 vector<uint256> vMerkleBranch;
\r
633 mutable bool fMerkleVerified;
\r
634 mutable bool fGetCreditCached;
\r
635 mutable int64 nGetCreditCached;
\r
643 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
652 fMerkleVerified = false;
\r
653 fGetCreditCached = false;
\r
654 nGetCreditCached = 0;
\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
666 int64 GetCredit(bool fUseCache=false) const
\r
668 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
669 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
672 // GetBalance can assume transactions in mapWallet won't change
\r
673 if (fUseCache && fGetCreditCached)
\r
674 return nGetCreditCached;
\r
675 nGetCreditCached = CTransaction::GetCredit();
\r
676 fGetCreditCached = true;
\r
677 return nGetCreditCached;
\r
681 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
682 int GetDepthInMainChain() const;
\r
683 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
684 int GetBlocksToMaturity() const;
\r
685 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
686 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
693 // A transaction with a bunch of additional info that only the owner cares
\r
694 // about. It includes any unrecorded transactions needed to link it back
\r
695 // to the block chain.
\r
697 class CWalletTx : public CMerkleTx
\r
700 vector<CMerkleTx> vtxPrev;
\r
701 map<string, string> mapValue;
\r
702 vector<pair<string, string> > vOrderForm;
\r
703 unsigned int fTimeReceivedIsTxTime;
\r
704 unsigned int nTimeReceived; // time received by this node
\r
707 //// probably need to sign the order info so know it came from payer
\r
709 // memory only UI hints
\r
710 mutable unsigned int nTimeDisplayed;
\r
711 mutable int nLinesDisplayed;
\r
719 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
724 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
731 fTimeReceivedIsTxTime = false;
\r
735 nTimeDisplayed = 0;
\r
736 nLinesDisplayed = 0;
\r
739 IMPLEMENT_SERIALIZE
\r
741 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
742 nVersion = this->nVersion;
\r
743 READWRITE(vtxPrev);
\r
744 READWRITE(mapValue);
\r
745 READWRITE(vOrderForm);
\r
746 READWRITE(fTimeReceivedIsTxTime);
\r
747 READWRITE(nTimeReceived);
\r
748 READWRITE(fFromMe);
\r
754 return CWalletDB().WriteTx(GetHash(), *this);
\r
758 int64 GetTxTime() const;
\r
759 int GetRequestCount() const;
\r
761 void AddSupportingTransactions(CTxDB& txdb);
\r
763 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
764 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
766 void RelayWalletTransaction(CTxDB& txdb);
\r
767 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
774 // A txdb record that contains the disk location of a transaction and the
\r
775 // locations of transactions that spend its outputs. vSpent is really only
\r
776 // used as a flag, but having the location is very helpful for debugging.
\r
782 vector<CDiskTxPos> vSpent;
\r
789 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
792 vSpent.resize(nOutputs);
\r
795 IMPLEMENT_SERIALIZE
\r
797 if (!(nType & SER_GETHASH))
\r
798 READWRITE(nVersion);
\r
811 return pos.IsNull();
\r
814 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
816 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
818 for (int i = 0; i < a.vSpent.size(); i++)
\r
819 if (a.vSpent[i] != b.vSpent[i])
\r
824 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
835 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
836 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
837 // requirements. When they solve the proof-of-work, they broadcast the block
\r
838 // to everyone and the block is added to the block chain. The first transaction
\r
839 // in the block is a special one that creates a new coin owned by the creator
\r
842 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
843 // is indexed by CBlockIndex objects in memory.
\r
850 uint256 hashPrevBlock;
\r
851 uint256 hashMerkleRoot;
\r
852 unsigned int nTime;
\r
853 unsigned int nBits;
\r
854 unsigned int nNonce;
\r
856 // network and disk
\r
857 vector<CTransaction> vtx;
\r
860 mutable vector<uint256> vMerkleTree;
\r
868 IMPLEMENT_SERIALIZE
\r
870 READWRITE(this->nVersion);
\r
871 nVersion = this->nVersion;
\r
872 READWRITE(hashPrevBlock);
\r
873 READWRITE(hashMerkleRoot);
\r
878 // ConnectBlock depends on vtx being last so it can calculate offset
\r
879 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
882 const_cast<CBlock*>(this)->vtx.clear();
\r
889 hashMerkleRoot = 0;
\r
894 vMerkleTree.clear();
\r
897 bool IsNull() const
\r
899 return (nBits == 0);
\r
902 uint256 GetHash() const
\r
904 return Hash(BEGIN(nVersion), END(nNonce));
\r
908 uint256 BuildMerkleTree() const
\r
910 vMerkleTree.clear();
\r
911 foreach(const CTransaction& tx, vtx)
\r
912 vMerkleTree.push_back(tx.GetHash());
\r
914 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
916 for (int i = 0; i < nSize; i += 2)
\r
918 int i2 = min(i+1, nSize-1);
\r
919 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
920 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
924 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
927 vector<uint256> GetMerkleBranch(int nIndex) const
\r
929 if (vMerkleTree.empty())
\r
931 vector<uint256> vMerkleBranch;
\r
933 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
935 int i = min(nIndex^1, nSize-1);
\r
936 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
940 return vMerkleBranch;
\r
943 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
947 foreach(const uint256& otherside, vMerkleBranch)
\r
950 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
952 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
959 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
961 // Open history file to append
\r
962 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
964 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
965 if (!fWriteTransactions)
\r
966 fileout.nType |= SER_BLOCKHEADERONLY;
\r
968 // Write index header
\r
969 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
970 fileout << FLATDATA(pchMessageStart) << nSize;
\r
973 nBlockPosRet = ftell(fileout);
\r
974 if (nBlockPosRet == -1)
\r
975 return error("CBlock::WriteToDisk() : ftell failed");
\r
978 // Flush stdio buffers and commit to disk before returning
\r
981 _commit(_fileno(fileout));
\r
983 fsync(fileno(fileout));
\r
989 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
\r
993 // Open history file to read
\r
994 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
996 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
997 if (!fReadTransactions)
\r
998 filein.nType |= SER_BLOCKHEADERONLY;
\r
1003 // Check the header
\r
1004 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
1005 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
1006 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
1007 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
1014 void print() const
\r
1016 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
1017 GetHash().ToString().substr(0,16).c_str(),
\r
1019 hashPrevBlock.ToString().substr(0,16).c_str(),
\r
1020 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1021 nTime, nBits, nNonce,
\r
1023 for (int i = 0; i < vtx.size(); i++)
\r
1028 printf(" vMerkleTree: ");
\r
1029 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1030 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1035 int64 GetBlockValue(int64 nFees) const;
\r
1036 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1037 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1038 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);
\r
1039 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1040 bool CheckBlock() const;
\r
1041 bool AcceptBlock();
\r
1050 // The block chain is a tree shaped structure starting with the
\r
1051 // genesis block at the root, with each block potentially having multiple
\r
1052 // candidates to be the next block. pprev and pnext link a path through the
\r
1053 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1054 // to it, but pnext will only point forward to the longest branch, or will
\r
1055 // be null if the block is not part of the longest chain.
\r
1060 const uint256* phashBlock;
\r
1061 CBlockIndex* pprev;
\r
1062 CBlockIndex* pnext;
\r
1063 unsigned int nFile;
\r
1064 unsigned int nBlockPos;
\r
1069 uint256 hashMerkleRoot;
\r
1070 unsigned int nTime;
\r
1071 unsigned int nBits;
\r
1072 unsigned int nNonce;
\r
1077 phashBlock = NULL;
\r
1085 hashMerkleRoot = 0;
\r
1091 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1093 phashBlock = NULL;
\r
1097 nBlockPos = nBlockPosIn;
\r
1100 nVersion = block.nVersion;
\r
1101 hashMerkleRoot = block.hashMerkleRoot;
\r
1102 nTime = block.nTime;
\r
1103 nBits = block.nBits;
\r
1104 nNonce = block.nNonce;
\r
1107 uint256 GetBlockHash() const
\r
1109 return *phashBlock;
\r
1112 bool IsInMainChain() const
\r
1114 return (pnext || this == pindexBest);
\r
1117 bool EraseBlockFromDisk()
\r
1119 // Open history file
\r
1120 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1124 // Overwrite with empty null block
\r
1132 enum { nMedianTimeSpan=11 };
\r
1134 int64 GetMedianTimePast() const
\r
1136 unsigned int pmedian[nMedianTimeSpan];
\r
1137 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1138 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1140 const CBlockIndex* pindex = this;
\r
1141 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1142 *(--pbegin) = pindex->nTime;
\r
1144 sort(pbegin, pend);
\r
1145 return pbegin[(pend - pbegin)/2];
\r
1148 int64 GetMedianTime() const
\r
1150 const CBlockIndex* pindex = this;
\r
1151 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1153 if (!pindex->pnext)
\r
1155 pindex = pindex->pnext;
\r
1157 return pindex->GetMedianTimePast();
\r
1162 string ToString() const
\r
1164 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1165 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1166 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1167 GetBlockHash().ToString().substr(0,16).c_str());
\r
1170 void print() const
\r
1172 printf("%s\n", ToString().c_str());
\r
1179 // Used to marshal pointers into hashes for db storage.
\r
1181 class CDiskBlockIndex : public CBlockIndex
\r
1193 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1195 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1196 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1199 IMPLEMENT_SERIALIZE
\r
1201 if (!(nType & SER_GETHASH))
\r
1202 READWRITE(nVersion);
\r
1204 READWRITE(hashNext);
\r
1206 READWRITE(nBlockPos);
\r
1207 READWRITE(nHeight);
\r
1210 READWRITE(this->nVersion);
\r
1211 READWRITE(hashPrev);
\r
1212 READWRITE(hashMerkleRoot);
\r
1215 READWRITE(nNonce);
\r
1218 uint256 GetBlockHash() const
\r
1221 block.nVersion = nVersion;
\r
1222 block.hashPrevBlock = hashPrev;
\r
1223 block.hashMerkleRoot = hashMerkleRoot;
\r
1224 block.nTime = nTime;
\r
1225 block.nBits = nBits;
\r
1226 block.nNonce = nNonce;
\r
1227 return block.GetHash();
\r
1231 string ToString() const
\r
1233 string str = "CDiskBlockIndex(";
\r
1234 str += CBlockIndex::ToString();
\r
1235 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1236 GetBlockHash().ToString().c_str(),
\r
1237 hashPrev.ToString().substr(0,16).c_str(),
\r
1238 hashNext.ToString().substr(0,16).c_str());
\r
1242 void print() const
\r
1244 printf("%s\n", ToString().c_str());
\r
1256 // Describes a place in the block chain to another node such that if the
\r
1257 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1258 // The further back it is, the further before the fork it may be.
\r
1260 class CBlockLocator
\r
1263 vector<uint256> vHave;
\r
1270 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1275 explicit CBlockLocator(uint256 hashBlock)
\r
1277 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1278 if (mi != mapBlockIndex.end())
\r
1279 Set((*mi).second);
\r
1282 IMPLEMENT_SERIALIZE
\r
1284 if (!(nType & SER_GETHASH))
\r
1285 READWRITE(nVersion);
\r
1289 void Set(const CBlockIndex* pindex)
\r
1295 vHave.push_back(pindex->GetBlockHash());
\r
1297 // Exponentially larger steps back
\r
1298 for (int i = 0; pindex && i < nStep; i++)
\r
1299 pindex = pindex->pprev;
\r
1300 if (vHave.size() > 10)
\r
1303 vHave.push_back(hashGenesisBlock);
\r
1306 int GetDistanceBack()
\r
1308 // Retrace how far back it was in the sender's branch
\r
1309 int nDistance = 0;
\r
1311 foreach(const uint256& hash, vHave)
\r
1313 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1314 if (mi != mapBlockIndex.end())
\r
1316 CBlockIndex* pindex = (*mi).second;
\r
1317 if (pindex->IsInMainChain())
\r
1320 nDistance += nStep;
\r
1321 if (nDistance > 10)
\r
1327 CBlockIndex* GetBlockIndex()
\r
1329 // Find the first block the caller has in the main chain
\r
1330 foreach(const uint256& hash, vHave)
\r
1332 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1333 if (mi != mapBlockIndex.end())
\r
1335 CBlockIndex* pindex = (*mi).second;
\r
1336 if (pindex->IsInMainChain())
\r
1340 return pindexGenesisBlock;
\r
1343 uint256 GetBlockHash()
\r
1345 // Find the first block the caller has in the main chain
\r
1346 foreach(const uint256& hash, vHave)
\r
1348 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1349 if (mi != mapBlockIndex.end())
\r
1351 CBlockIndex* pindex = (*mi).second;
\r
1352 if (pindex->IsInMainChain())
\r
1356 return hashGenesisBlock;
\r
1361 CBlockIndex* pindex = GetBlockIndex();
\r
1364 return pindex->nHeight;
\r
1379 extern map<uint256, CTransaction> mapTransactions;
\r
1380 extern map<uint256, CWalletTx> mapWallet;
\r
1381 extern vector<uint256> vWalletUpdated;
\r
1382 extern CCriticalSection cs_mapWallet;
\r
1383 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1384 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1385 extern CCriticalSection cs_mapKeys;
\r
1386 extern CKey keyUser;
\r