1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
30 class CRequestTracker;
34 static const unsigned int MAX_BLOCK_SIZE = 1000000;
35 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
36 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
37 static const int64 COIN = 100000000;
38 static const int64 CENT = 1000000;
39 static const int64 MIN_TX_FEE = 50000;
40 static const int64 MIN_RELAY_TX_FEE = 10000;
41 static const int64 MAX_MONEY = 21000000 * COIN;
42 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
43 static const int COINBASE_MATURITY = 100;
45 static const int fHaveUPnP = true;
47 static const int fHaveUPnP = false;
55 extern CCriticalSection cs_main;
56 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
57 extern uint256 hashGenesisBlock;
58 extern CBigNum bnProofOfWorkLimit;
59 extern CBlockIndex* pindexGenesisBlock;
60 extern int nBestHeight;
61 extern CBigNum bnBestChainWork;
62 extern CBigNum bnBestInvalidWork;
63 extern uint256 hashBestChain;
64 extern CBlockIndex* pindexBest;
65 extern std::set<int64> setKeyPool;
66 extern CCriticalSection cs_setKeyPool;
67 extern unsigned int nTransactionsUpdated;
68 extern double dHashesPerSec;
69 extern int64 nHPSTimerStart;
70 extern int64 nTimeBestReceived;
71 extern std::map<std::string, std::string> mapAddressBook;
72 extern CCriticalSection cs_mapAddressBook;
76 extern int fGenerateBitcoins;
77 extern int64 nTransactionFee;
78 extern CAddress addrIncoming;
79 extern int fLimitProcessors;
80 extern int nLimitProcessors;
81 extern int fMinimizeToTray;
82 extern int fMinimizeOnClose;
93 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
94 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
95 FILE* AppendBlockFile(unsigned int& nFileRet);
96 bool LoadBlockIndex(bool fAllowNew=true);
97 void PrintBlockTree();
98 bool ProcessMessages(CNode* pfrom);
99 bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
100 bool SendMessages(CNode* pto, bool fSendTrickle);
101 void GenerateBitcoins(bool fGenerate);
102 void ThreadBitcoinMiner(void* parg);
103 CBlock* CreateNewBlock(CReserveKey& reservekey);
104 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
105 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
106 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
108 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
109 bool IsInitialBlockDownload();
110 std::string GetWarnings(std::string strFor);
127 unsigned int nBlockPos;
135 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
138 nBlockPos = nBlockPosIn;
142 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
143 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
144 bool IsNull() const { return (nFile == -1); }
146 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
148 return (a.nFile == b.nFile &&
149 a.nBlockPos == b.nBlockPos &&
150 a.nTxPos == b.nTxPos);
153 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
158 std::string ToString() const
161 return strprintf("null");
163 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
168 printf("%s", ToString().c_str());
181 CInPoint() { SetNull(); }
182 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
183 void SetNull() { ptx = NULL; n = -1; }
184 bool IsNull() const { return (ptx == NULL && n == -1); }
196 COutPoint() { SetNull(); }
197 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
198 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
199 void SetNull() { hash = 0; n = -1; }
200 bool IsNull() const { return (hash == 0 && n == -1); }
202 friend bool operator<(const COutPoint& a, const COutPoint& b)
204 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
207 friend bool operator==(const COutPoint& a, const COutPoint& b)
209 return (a.hash == b.hash && a.n == b.n);
212 friend bool operator!=(const COutPoint& a, const COutPoint& b)
217 std::string ToString() const
219 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
224 printf("%s\n", ToString().c_str());
232 // An input of a transaction. It contains the location of the previous
233 // transaction's output that it claims and a signature that matches the
234 // output's public key.
241 unsigned int nSequence;
245 nSequence = UINT_MAX;
248 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
251 scriptSig = scriptSigIn;
252 nSequence = nSequenceIn;
255 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
257 prevout = COutPoint(hashPrevTx, nOut);
258 scriptSig = scriptSigIn;
259 nSequence = nSequenceIn;
265 READWRITE(scriptSig);
266 READWRITE(nSequence);
271 return (nSequence == UINT_MAX);
274 friend bool operator==(const CTxIn& a, const CTxIn& b)
276 return (a.prevout == b.prevout &&
277 a.scriptSig == b.scriptSig &&
278 a.nSequence == b.nSequence);
281 friend bool operator!=(const CTxIn& a, const CTxIn& b)
286 std::string ToString() const
289 str += strprintf("CTxIn(");
290 str += prevout.ToString();
291 if (prevout.IsNull())
292 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
294 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
295 if (nSequence != UINT_MAX)
296 str += strprintf(", nSequence=%u", nSequence);
303 printf("%s\n", ToString().c_str());
307 int64 GetDebit() const;
314 // An output of a transaction. It contains the public key that the next input
315 // must be able to sign with to claim it.
321 CScript scriptPubKey;
328 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
331 scriptPubKey = scriptPubKeyIn;
337 READWRITE(scriptPubKey);
343 scriptPubKey.clear();
348 return (nValue == -1);
351 uint256 GetHash() const
353 return SerializeHash(*this);
358 return ::IsMine(scriptPubKey);
361 int64 GetCredit() const
363 if (!MoneyRange(nValue))
364 throw std::runtime_error("CTxOut::GetCredit() : value out of range");
365 return (IsMine() ? nValue : 0);
368 bool IsChange() const
370 // On a debit transaction, a txout that's mine but isn't in the address book is change
371 std::vector<unsigned char> vchPubKey;
372 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
373 CRITICAL_BLOCK(cs_mapAddressBook)
374 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
379 int64 GetChange() const
381 if (!MoneyRange(nValue))
382 throw std::runtime_error("CTxOut::GetChange() : value out of range");
383 return (IsChange() ? nValue : 0);
386 friend bool operator==(const CTxOut& a, const CTxOut& b)
388 return (a.nValue == b.nValue &&
389 a.scriptPubKey == b.scriptPubKey);
392 friend bool operator!=(const CTxOut& a, const CTxOut& b)
397 std::string ToString() const
399 if (scriptPubKey.size() < 6)
400 return "CTxOut(error)";
401 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
406 printf("%s\n", ToString().c_str());
414 // The basic transaction that is broadcasted on the network and contained in
415 // blocks. A transaction can contain multiple inputs and outputs.
421 std::vector<CTxIn> vin;
422 std::vector<CTxOut> vout;
423 unsigned int nLockTime;
433 READWRITE(this->nVersion);
434 nVersion = this->nVersion;
437 READWRITE(nLockTime);
450 return (vin.empty() && vout.empty());
453 uint256 GetHash() const
455 return SerializeHash(*this);
458 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
460 // Time based nLockTime implemented in 0.1.6
463 if (nBlockHeight == 0)
464 nBlockHeight = nBestHeight;
466 nBlockTime = GetAdjustedTime();
467 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
469 BOOST_FOREACH(const CTxIn& txin, vin)
475 bool IsNewerThan(const CTransaction& old) const
477 if (vin.size() != old.vin.size())
479 for (int i = 0; i < vin.size(); i++)
480 if (vin[i].prevout != old.vin[i].prevout)
484 unsigned int nLowest = UINT_MAX;
485 for (int i = 0; i < vin.size(); i++)
487 if (vin[i].nSequence != old.vin[i].nSequence)
489 if (vin[i].nSequence <= nLowest)
492 nLowest = vin[i].nSequence;
494 if (old.vin[i].nSequence < nLowest)
497 nLowest = old.vin[i].nSequence;
504 bool IsCoinBase() const
506 return (vin.size() == 1 && vin[0].prevout.IsNull());
509 int GetSigOpCount() const
512 BOOST_FOREACH(const CTxIn& txin, vin)
513 n += txin.scriptSig.GetSigOpCount();
514 BOOST_FOREACH(const CTxOut& txout, vout)
515 n += txout.scriptPubKey.GetSigOpCount();
519 bool IsStandard() const
521 BOOST_FOREACH(const CTxIn& txin, vin)
522 if (!txin.scriptSig.IsPushOnly())
523 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
524 BOOST_FOREACH(const CTxOut& txout, vout)
525 if (!::IsStandard(txout.scriptPubKey))
526 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
532 BOOST_FOREACH(const CTxOut& txout, vout)
538 bool IsFromMe() const
540 return (GetDebit() > 0);
543 int64 GetDebit() const
546 BOOST_FOREACH(const CTxIn& txin, vin)
548 nDebit += txin.GetDebit();
549 if (!MoneyRange(nDebit))
550 throw std::runtime_error("CTransaction::GetDebit() : value out of range");
555 int64 GetCredit() const
558 BOOST_FOREACH(const CTxOut& txout, vout)
560 nCredit += txout.GetCredit();
561 if (!MoneyRange(nCredit))
562 throw std::runtime_error("CTransaction::GetCredit() : value out of range");
567 int64 GetChange() const
572 BOOST_FOREACH(const CTxOut& txout, vout)
574 nChange += txout.GetChange();
575 if (!MoneyRange(nChange))
576 throw std::runtime_error("CTransaction::GetChange() : value out of range");
581 int64 GetValueOut() const
584 BOOST_FOREACH(const CTxOut& txout, vout)
586 nValueOut += txout.nValue;
587 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
588 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
593 static bool AllowFree(double dPriority)
595 // Large (in bytes) low-priority (new, small-coin) transactions
597 return dPriority > COIN * 144 / 250;
600 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
602 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
603 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
605 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
606 unsigned int nNewBlockSize = nBlockSize + nBytes;
607 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
613 // Transactions under 10K are free
614 // (about 4500bc if made of 50bc inputs)
620 // Free transaction area
621 if (nNewBlockSize < 27000)
626 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
627 if (nMinFee < nBaseFee)
628 BOOST_FOREACH(const CTxOut& txout, vout)
629 if (txout.nValue < CENT)
632 // Raise the price as the block approaches full
633 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
635 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
637 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
640 if (!MoneyRange(nMinFee))
646 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
648 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
650 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
653 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
654 return error("CTransaction::ReadFromDisk() : fseek failed");
657 // Return file pointer
660 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
661 return error("CTransaction::ReadFromDisk() : second fseek failed");
662 *pfileRet = filein.release();
667 friend bool operator==(const CTransaction& a, const CTransaction& b)
669 return (a.nVersion == b.nVersion &&
672 a.nLockTime == b.nLockTime);
675 friend bool operator!=(const CTransaction& a, const CTransaction& b)
681 std::string ToString() const
684 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
685 GetHash().ToString().substr(0,10).c_str(),
690 for (int i = 0; i < vin.size(); i++)
691 str += " " + vin[i].ToString() + "\n";
692 for (int i = 0; i < vout.size(); i++)
693 str += " " + vout[i].ToString() + "\n";
699 printf("%s", ToString().c_str());
703 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
704 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
705 bool ReadFromDisk(COutPoint prevout);
706 bool DisconnectInputs(CTxDB& txdb);
707 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
708 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
709 bool ClientConnectInputs();
710 bool CheckTransaction() const;
711 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
712 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
714 bool AddToMemoryPoolUnchecked();
716 bool RemoveFromMemoryPool();
724 // A transaction with a merkle branch linking it to the block chain
726 class CMerkleTx : public CTransaction
730 std::vector<uint256> vMerkleBranch;
734 mutable char fMerkleVerified;
742 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
751 fMerkleVerified = false;
757 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
758 nVersion = this->nVersion;
759 READWRITE(hashBlock);
760 READWRITE(vMerkleBranch);
765 int SetMerkleBranch(const CBlock* pblock=NULL);
766 int GetDepthInMainChain(int& nHeightRet) const;
767 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
768 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
769 int GetBlocksToMaturity() const;
770 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
771 bool AcceptToMemoryPool();
778 // A txdb record that contains the disk location of a transaction and the
779 // locations of transactions that spend its outputs. vSpent is really only
780 // used as a flag, but having the location is very helpful for debugging.
786 std::vector<CDiskTxPos> vSpent;
793 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
796 vSpent.resize(nOutputs);
801 if (!(nType & SER_GETHASH))
818 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
820 return (a.pos == b.pos &&
821 a.vSpent == b.vSpent);
824 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
828 int GetDepthInMainChain() const;
836 // Nodes collect new transactions into a block, hash them into a hash tree,
837 // and scan through nonce values to make the block's hash satisfy proof-of-work
838 // requirements. When they solve the proof-of-work, they broadcast the block
839 // to everyone and the block is added to the block chain. The first transaction
840 // in the block is a special one that creates a new coin owned by the creator
843 // Blocks are appended to blk0001.dat files on disk. Their location on disk
844 // is indexed by CBlockIndex objects in memory.
851 uint256 hashPrevBlock;
852 uint256 hashMerkleRoot;
858 std::vector<CTransaction> vtx;
861 mutable std::vector<uint256> vMerkleTree;
871 READWRITE(this->nVersion);
872 nVersion = this->nVersion;
873 READWRITE(hashPrevBlock);
874 READWRITE(hashMerkleRoot);
879 // ConnectBlock depends on vtx being last so it can calculate offset
880 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
883 const_cast<CBlock*>(this)->vtx.clear();
903 uint256 GetHash() const
905 return Hash(BEGIN(nVersion), END(nNonce));
908 int64 GetBlockTime() const
913 int GetSigOpCount() const
916 BOOST_FOREACH(const CTransaction& tx, vtx)
917 n += tx.GetSigOpCount();
922 uint256 BuildMerkleTree() const
925 BOOST_FOREACH(const CTransaction& tx, vtx)
926 vMerkleTree.push_back(tx.GetHash());
928 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
930 for (int i = 0; i < nSize; i += 2)
932 int i2 = std::min(i+1, nSize-1);
933 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
934 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
938 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
941 std::vector<uint256> GetMerkleBranch(int nIndex) const
943 if (vMerkleTree.empty())
945 std::vector<uint256> vMerkleBranch;
947 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
949 int i = std::min(nIndex^1, nSize-1);
950 vMerkleBranch.push_back(vMerkleTree[j+i]);
954 return vMerkleBranch;
957 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
961 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
964 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
966 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
973 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
975 // Open history file to append
976 CAutoFile fileout = AppendBlockFile(nFileRet);
978 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
980 // Write index header
981 unsigned int nSize = fileout.GetSerializeSize(*this);
982 fileout << FLATDATA(pchMessageStart) << nSize;
985 nBlockPosRet = ftell(fileout);
986 if (nBlockPosRet == -1)
987 return error("CBlock::WriteToDisk() : ftell failed");
990 // Flush stdio buffers and commit to disk before returning
992 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
995 _commit(_fileno(fileout));
997 fsync(fileno(fileout));
1004 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1008 // Open history file to read
1009 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1011 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1012 if (!fReadTransactions)
1013 filein.nType |= SER_BLOCKHEADERONLY;
1019 if (!CheckProofOfWork(GetHash(), nBits))
1020 return error("CBlock::ReadFromDisk() : errors in block header");
1029 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1030 GetHash().ToString().substr(0,20).c_str(),
1032 hashPrevBlock.ToString().substr(0,20).c_str(),
1033 hashMerkleRoot.ToString().substr(0,10).c_str(),
1034 nTime, nBits, nNonce,
1036 for (int i = 0; i < vtx.size(); i++)
1041 printf(" vMerkleTree: ");
1042 for (int i = 0; i < vMerkleTree.size(); i++)
1043 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1048 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1049 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1050 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1051 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1052 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1053 bool CheckBlock() const;
1063 // The block chain is a tree shaped structure starting with the
1064 // genesis block at the root, with each block potentially having multiple
1065 // candidates to be the next block. pprev and pnext link a path through the
1066 // main/longest chain. A blockindex may have multiple pprev pointing back
1067 // to it, but pnext will only point forward to the longest branch, or will
1068 // be null if the block is not part of the longest chain.
1073 const uint256* phashBlock;
1077 unsigned int nBlockPos;
1079 CBigNum bnChainWork;
1083 uint256 hashMerkleRoot;
1086 unsigned int nNonce;
1106 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1112 nBlockPos = nBlockPosIn;
1116 nVersion = block.nVersion;
1117 hashMerkleRoot = block.hashMerkleRoot;
1118 nTime = block.nTime;
1119 nBits = block.nBits;
1120 nNonce = block.nNonce;
1123 CBlock GetBlockHeader() const
1126 block.nVersion = nVersion;
1128 block.hashPrevBlock = pprev->GetBlockHash();
1129 block.hashMerkleRoot = hashMerkleRoot;
1130 block.nTime = nTime;
1131 block.nBits = nBits;
1132 block.nNonce = nNonce;
1136 uint256 GetBlockHash() const
1141 int64 GetBlockTime() const
1143 return (int64)nTime;
1146 CBigNum GetBlockWork() const
1149 bnTarget.SetCompact(nBits);
1152 return (CBigNum(1)<<256) / (bnTarget+1);
1155 bool IsInMainChain() const
1157 return (pnext || this == pindexBest);
1160 bool CheckIndex() const
1162 return CheckProofOfWork(GetBlockHash(), nBits);
1165 bool EraseBlockFromDisk()
1167 // Open history file
1168 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1172 // Overwrite with empty null block
1180 enum { nMedianTimeSpan=11 };
1182 int64 GetMedianTimePast() const
1184 int64 pmedian[nMedianTimeSpan];
1185 int64* pbegin = &pmedian[nMedianTimeSpan];
1186 int64* pend = &pmedian[nMedianTimeSpan];
1188 const CBlockIndex* pindex = this;
1189 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1190 *(--pbegin) = pindex->GetBlockTime();
1192 std::sort(pbegin, pend);
1193 return pbegin[(pend - pbegin)/2];
1196 int64 GetMedianTime() const
1198 const CBlockIndex* pindex = this;
1199 for (int i = 0; i < nMedianTimeSpan/2; i++)
1202 return GetBlockTime();
1203 pindex = pindex->pnext;
1205 return pindex->GetMedianTimePast();
1210 std::string ToString() const
1212 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1213 pprev, pnext, nFile, nBlockPos, nHeight,
1214 hashMerkleRoot.ToString().substr(0,10).c_str(),
1215 GetBlockHash().ToString().substr(0,20).c_str());
1220 printf("%s\n", ToString().c_str());
1227 // Used to marshal pointers into hashes for db storage.
1229 class CDiskBlockIndex : public CBlockIndex
1241 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1243 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1244 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1249 if (!(nType & SER_GETHASH))
1250 READWRITE(nVersion);
1252 READWRITE(hashNext);
1254 READWRITE(nBlockPos);
1258 READWRITE(this->nVersion);
1259 READWRITE(hashPrev);
1260 READWRITE(hashMerkleRoot);
1266 uint256 GetBlockHash() const
1269 block.nVersion = nVersion;
1270 block.hashPrevBlock = hashPrev;
1271 block.hashMerkleRoot = hashMerkleRoot;
1272 block.nTime = nTime;
1273 block.nBits = nBits;
1274 block.nNonce = nNonce;
1275 return block.GetHash();
1279 std::string ToString() const
1281 std::string str = "CDiskBlockIndex(";
1282 str += CBlockIndex::ToString();
1283 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1284 GetBlockHash().ToString().c_str(),
1285 hashPrev.ToString().substr(0,20).c_str(),
1286 hashNext.ToString().substr(0,20).c_str());
1292 printf("%s\n", ToString().c_str());
1304 // Describes a place in the block chain to another node such that if the
1305 // other node doesn't have the same branch, it can find a recent common trunk.
1306 // The further back it is, the further before the fork it may be.
1311 std::vector<uint256> vHave;
1318 explicit CBlockLocator(const CBlockIndex* pindex)
1323 explicit CBlockLocator(uint256 hashBlock)
1325 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1326 if (mi != mapBlockIndex.end())
1332 if (!(nType & SER_GETHASH))
1333 READWRITE(nVersion);
1344 return vHave.empty();
1347 void Set(const CBlockIndex* pindex)
1353 vHave.push_back(pindex->GetBlockHash());
1355 // Exponentially larger steps back
1356 for (int i = 0; pindex && i < nStep; i++)
1357 pindex = pindex->pprev;
1358 if (vHave.size() > 10)
1361 vHave.push_back(hashGenesisBlock);
1364 int GetDistanceBack()
1366 // Retrace how far back it was in the sender's branch
1369 BOOST_FOREACH(const uint256& hash, vHave)
1371 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1372 if (mi != mapBlockIndex.end())
1374 CBlockIndex* pindex = (*mi).second;
1375 if (pindex->IsInMainChain())
1385 CBlockIndex* GetBlockIndex()
1387 // Find the first block the caller has in the main chain
1388 BOOST_FOREACH(const uint256& hash, vHave)
1390 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1391 if (mi != mapBlockIndex.end())
1393 CBlockIndex* pindex = (*mi).second;
1394 if (pindex->IsInMainChain())
1398 return pindexGenesisBlock;
1401 uint256 GetBlockHash()
1403 // Find the first block the caller has in the main chain
1404 BOOST_FOREACH(const uint256& hash, vHave)
1406 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1407 if (mi != mapBlockIndex.end())
1409 CBlockIndex* pindex = (*mi).second;
1410 if (pindex->IsInMainChain())
1414 return hashGenesisBlock;
1419 CBlockIndex* pindex = GetBlockIndex();
1422 return pindex->nHeight;
1435 // Alerts are for notifying old versions if they become too obsolete and
1436 // need to upgrade. The message is displayed in the status bar.
1437 // Alert messages are broadcast as a vector of signed data. Unserializing may
1438 // not read the entire buffer if the alert is for a newer version, but older
1439 // versions can still relay the original data.
1441 class CUnsignedAlert
1445 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1449 std::set<int> setCancel;
1450 int nMinVer; // lowest version inclusive
1451 int nMaxVer; // highest version inclusive
1452 std::set<std::string> setSubVer; // empty matches all
1456 std::string strComment;
1457 std::string strStatusBar;
1458 std::string strReserved;
1462 READWRITE(this->nVersion);
1463 nVersion = this->nVersion;
1464 READWRITE(nRelayUntil);
1465 READWRITE(nExpiration);
1468 READWRITE(setCancel);
1471 READWRITE(setSubVer);
1472 READWRITE(nPriority);
1474 READWRITE(strComment);
1475 READWRITE(strStatusBar);
1476 READWRITE(strReserved);
1493 strStatusBar.clear();
1494 strReserved.clear();
1497 std::string ToString() const
1499 std::string strSetCancel;
1500 BOOST_FOREACH(int n, setCancel)
1501 strSetCancel += strprintf("%d ", n);
1502 std::string strSetSubVer;
1503 BOOST_FOREACH(std::string str, setSubVer)
1504 strSetSubVer += "\"" + str + "\" ";
1508 " nRelayUntil = %"PRI64d"\n"
1509 " nExpiration = %"PRI64d"\n"
1517 " strComment = \"%s\"\n"
1518 " strStatusBar = \"%s\"\n"
1525 strSetCancel.c_str(),
1528 strSetSubVer.c_str(),
1531 strStatusBar.c_str());
1536 printf("%s", ToString().c_str());
1540 class CAlert : public CUnsignedAlert
1543 std::vector<unsigned char> vchMsg;
1544 std::vector<unsigned char> vchSig;
1559 CUnsignedAlert::SetNull();
1566 return (nExpiration == 0);
1569 uint256 GetHash() const
1571 return SerializeHash(*this);
1574 bool IsInEffect() const
1576 return (GetAdjustedTime() < nExpiration);
1579 bool Cancels(const CAlert& alert) const
1582 return false; // this was a no-op before 31403
1583 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1586 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1588 return (IsInEffect() &&
1589 nMinVer <= nVersion && nVersion <= nMaxVer &&
1590 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1593 bool AppliesToMe() const
1595 return AppliesTo(VERSION, ::pszSubVer);
1598 bool RelayTo(CNode* pnode) const
1602 // returns true if wasn't already contained in the set
1603 if (pnode->setKnown.insert(GetHash()).second)
1605 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1607 GetAdjustedTime() < nRelayUntil)
1609 pnode->PushMessage("alert", *this);
1616 bool CheckSignature()
1619 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1620 return error("CAlert::CheckSignature() : SetPubKey failed");
1621 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1622 return error("CAlert::CheckSignature() : verify signature failed");
1624 // Now unserialize the data
1625 CDataStream sMsg(vchMsg);
1626 sMsg >> *(CUnsignedAlert*)this;
1630 bool ProcessAlert();
1642 extern std::map<uint256, CTransaction> mapTransactions;
1643 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
1644 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
1645 extern CCriticalSection cs_mapKeys;