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.
17 static const unsigned int MAX_BLOCK_SIZE = 1000000;
18 static const int64 COIN = 100000000;
19 static const int64 CENT = 1000000;
20 static const int64 MAX_MONEY = 21000000 * COIN;
21 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
22 static const int COINBASE_MATURITY = 100;
23 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
30 extern CCriticalSection cs_main;
31 extern map<uint256, CBlockIndex*> mapBlockIndex;
32 extern const uint256 hashGenesisBlock;
33 extern CBlockIndex* pindexGenesisBlock;
34 extern int nBestHeight;
35 extern CBigNum bnBestChainWork;
36 extern CBigNum bnBestInvalidWork;
37 extern uint256 hashBestChain;
38 extern CBlockIndex* pindexBest;
39 extern unsigned int nTransactionsUpdated;
40 extern map<uint256, int> mapRequestCount;
41 extern CCriticalSection cs_mapRequestCount;
42 extern map<string, string> mapAddressBook;
43 extern CCriticalSection cs_mapAddressBook;
44 extern vector<unsigned char> vchDefaultKey;
45 extern double dHashesPerSec;
46 extern int64 nHPSTimerStart;
49 extern int fGenerateBitcoins;
50 extern int64 nTransactionFee;
51 extern CAddress addrIncoming;
52 extern int fLimitProcessors;
53 extern int nLimitProcessors;
54 extern int fMinimizeToTray;
55 extern int fMinimizeOnClose;
63 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
64 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
65 FILE* AppendBlockFile(unsigned int& nFileRet);
66 bool AddKey(const CKey& key);
67 vector<unsigned char> GenerateNewKey();
68 bool AddToWallet(const CWalletTx& wtxIn);
69 void WalletUpdateSpent(const COutPoint& prevout);
70 void ReacceptWalletTransactions();
71 bool LoadBlockIndex(bool fAllowNew=true);
72 void PrintBlockTree();
73 bool ProcessMessages(CNode* pfrom);
74 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
75 bool SendMessages(CNode* pto, bool fSendTrickle);
77 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
78 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);
79 bool BroadcastTransaction(CWalletTx& wtxNew);
80 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
81 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
82 void GenerateBitcoins(bool fGenerate);
83 void ThreadBitcoinMiner(void* parg);
85 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
86 bool IsInitialBlockDownload();
87 string GetWarnings(string strFor);
104 unsigned int nBlockPos;
112 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
115 nBlockPos = nBlockPosIn;
119 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
120 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
121 bool IsNull() const { return (nFile == -1); }
123 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
125 return (a.nFile == b.nFile &&
126 a.nBlockPos == b.nBlockPos &&
127 a.nTxPos == b.nTxPos);
130 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
135 string ToString() const
138 return strprintf("null");
140 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
145 printf("%s", ToString().c_str());
158 CInPoint() { SetNull(); }
159 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
160 void SetNull() { ptx = NULL; n = -1; }
161 bool IsNull() const { return (ptx == NULL && n == -1); }
173 COutPoint() { SetNull(); }
174 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
175 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
176 void SetNull() { hash = 0; n = -1; }
177 bool IsNull() const { return (hash == 0 && n == -1); }
179 friend bool operator<(const COutPoint& a, const COutPoint& b)
181 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
184 friend bool operator==(const COutPoint& a, const COutPoint& b)
186 return (a.hash == b.hash && a.n == b.n);
189 friend bool operator!=(const COutPoint& a, const COutPoint& b)
194 string ToString() const
196 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
201 printf("%s\n", ToString().c_str());
209 // An input of a transaction. It contains the location of the previous
210 // transaction's output that it claims and a signature that matches the
211 // output's public key.
218 unsigned int nSequence;
222 nSequence = UINT_MAX;
225 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
228 scriptSig = scriptSigIn;
229 nSequence = nSequenceIn;
232 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
234 prevout = COutPoint(hashPrevTx, nOut);
235 scriptSig = scriptSigIn;
236 nSequence = nSequenceIn;
242 READWRITE(scriptSig);
243 READWRITE(nSequence);
248 return (nSequence == UINT_MAX);
251 friend bool operator==(const CTxIn& a, const CTxIn& b)
253 return (a.prevout == b.prevout &&
254 a.scriptSig == b.scriptSig &&
255 a.nSequence == b.nSequence);
258 friend bool operator!=(const CTxIn& a, const CTxIn& b)
263 string ToString() const
266 str += strprintf("CTxIn(");
267 str += prevout.ToString();
268 if (prevout.IsNull())
269 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
271 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
272 if (nSequence != UINT_MAX)
273 str += strprintf(", nSequence=%u", nSequence);
280 printf("%s\n", ToString().c_str());
284 int64 GetDebit() const;
291 // An output of a transaction. It contains the public key that the next input
292 // must be able to sign with to claim it.
298 CScript scriptPubKey;
305 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
308 scriptPubKey = scriptPubKeyIn;
314 READWRITE(scriptPubKey);
320 scriptPubKey.clear();
325 return (nValue == -1);
328 uint256 GetHash() const
330 return SerializeHash(*this);
335 return ::IsMine(scriptPubKey);
338 int64 GetCredit() const
340 if (!MoneyRange(nValue))
341 throw runtime_error("CTxOut::GetCredit() : value out of range");
347 friend bool operator==(const CTxOut& a, const CTxOut& b)
349 return (a.nValue == b.nValue &&
350 a.scriptPubKey == b.scriptPubKey);
353 friend bool operator!=(const CTxOut& a, const CTxOut& b)
358 string ToString() const
360 if (scriptPubKey.size() < 6)
361 return "CTxOut(error)";
362 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
367 printf("%s\n", ToString().c_str());
375 // The basic transaction that is broadcasted on the network and contained in
376 // blocks. A transaction can contain multiple inputs and outputs.
384 unsigned int nLockTime;
394 READWRITE(this->nVersion);
395 nVersion = this->nVersion;
398 READWRITE(nLockTime);
411 return (vin.empty() && vout.empty());
414 uint256 GetHash() const
416 return SerializeHash(*this);
419 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
421 // Time based nLockTime implemented in 0.1.6
424 if (nBlockHeight == 0)
425 nBlockHeight = nBestHeight;
427 nBlockTime = GetAdjustedTime();
428 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
430 foreach(const CTxIn& txin, vin)
436 bool IsNewerThan(const CTransaction& old) const
438 if (vin.size() != old.vin.size())
440 for (int i = 0; i < vin.size(); i++)
441 if (vin[i].prevout != old.vin[i].prevout)
445 unsigned int nLowest = UINT_MAX;
446 for (int i = 0; i < vin.size(); i++)
448 if (vin[i].nSequence != old.vin[i].nSequence)
450 if (vin[i].nSequence <= nLowest)
453 nLowest = vin[i].nSequence;
455 if (old.vin[i].nSequence < nLowest)
458 nLowest = old.vin[i].nSequence;
465 bool IsCoinBase() const
467 return (vin.size() == 1 && vin[0].prevout.IsNull());
470 bool CheckTransaction() const
472 // Basic checks that don't depend on any context
473 if (vin.empty() || vout.empty())
474 return error("CTransaction::CheckTransaction() : vin or vout empty");
477 if (::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
478 return error("CTransaction::CheckTransaction() : size limits failed");
480 // Check for negative or overflow output values
482 foreach(const CTxOut& txout, vout)
484 if (txout.nValue < 0)
485 return error("CTransaction::CheckTransaction() : txout.nValue negative");
486 if (txout.nValue > MAX_MONEY)
487 return error("CTransaction::CheckTransaction() : txout.nValue too high");
488 nValueOut += txout.nValue;
489 if (!MoneyRange(nValueOut))
490 return error("CTransaction::CheckTransaction() : txout total out of range");
495 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
496 return error("CTransaction::CheckTransaction() : coinbase script size");
500 foreach(const CTxIn& txin, vin)
501 if (txin.prevout.IsNull())
502 return error("CTransaction::CheckTransaction() : prevout is null");
510 foreach(const CTxOut& txout, vout)
516 int64 GetDebit() const
519 foreach(const CTxIn& txin, vin)
521 nDebit += txin.GetDebit();
522 if (!MoneyRange(nDebit))
523 throw runtime_error("CTransaction::GetDebit() : value out of range");
528 int64 GetCredit() const
531 foreach(const CTxOut& txout, vout)
533 nCredit += txout.GetCredit();
534 if (!MoneyRange(nCredit))
535 throw runtime_error("CTransaction::GetCredit() : value out of range");
540 int64 GetValueOut() const
543 foreach(const CTxOut& txout, vout)
545 nValueOut += txout.nValue;
546 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
547 throw runtime_error("CTransaction::GetValueOut() : value out of range");
552 int64 GetMinFee(unsigned int nBlockSize=1) const
554 // Base fee is 1 cent per kilobyte
555 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
556 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
558 // Transactions under 60K are free as long as block size is under 80K
559 // (about 27,000bc if made of 50bc inputs)
560 if (nBytes < 60000 && nBlockSize < 80000)
563 // Transactions under 3K are free as long as block size is under 200K
564 if (nBytes < 3000 && nBlockSize < 200000)
567 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
569 foreach(const CTxOut& txout, vout)
570 if (txout.nValue < CENT)
578 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
580 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
582 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
585 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
586 return error("CTransaction::ReadFromDisk() : fseek failed");
589 // Return file pointer
592 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
593 return error("CTransaction::ReadFromDisk() : second fseek failed");
594 *pfileRet = filein.release();
600 friend bool operator==(const CTransaction& a, const CTransaction& b)
602 return (a.nVersion == b.nVersion &&
605 a.nLockTime == b.nLockTime);
608 friend bool operator!=(const CTransaction& a, const CTransaction& b)
614 string ToString() const
617 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
618 GetHash().ToString().substr(0,6).c_str(),
623 for (int i = 0; i < vin.size(); i++)
624 str += " " + vin[i].ToString() + "\n";
625 for (int i = 0; i < vout.size(); i++)
626 str += " " + vout[i].ToString() + "\n";
632 printf("%s", ToString().c_str());
637 bool DisconnectInputs(CTxDB& txdb);
638 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
639 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
640 bool ClientConnectInputs();
642 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
644 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
647 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
651 bool AddToMemoryPool();
653 bool RemoveFromMemoryPool();
661 // A transaction with a merkle branch linking it to the block chain
663 class CMerkleTx : public CTransaction
667 vector<uint256> vMerkleBranch;
671 mutable bool fMerkleVerified;
672 mutable bool fGetCreditCached;
673 mutable int64 nGetCreditCached;
681 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
690 fMerkleVerified = false;
691 fGetCreditCached = false;
692 nGetCreditCached = 0;
697 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
698 nVersion = this->nVersion;
699 READWRITE(hashBlock);
700 READWRITE(vMerkleBranch);
704 int64 GetCredit(bool fUseCache=false) const
706 // Must wait until coinbase is safely deep enough in the chain before valuing it
707 if (IsCoinBase() && GetBlocksToMaturity() > 0)
710 // GetBalance can assume transactions in mapWallet won't change
711 if (fUseCache && fGetCreditCached)
712 return nGetCreditCached;
713 nGetCreditCached = CTransaction::GetCredit();
714 fGetCreditCached = true;
715 return nGetCreditCached;
719 int SetMerkleBranch(const CBlock* pblock=NULL);
720 int GetDepthInMainChain(int& nHeightRet) const;
721 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
722 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
723 int GetBlocksToMaturity() const;
724 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
725 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
732 // A transaction with a bunch of additional info that only the owner cares
733 // about. It includes any unrecorded transactions needed to link it back
734 // to the block chain.
736 class CWalletTx : public CMerkleTx
739 vector<CMerkleTx> vtxPrev;
740 map<string, string> mapValue;
741 vector<pair<string, string> > vOrderForm;
742 unsigned int fTimeReceivedIsTxTime;
743 unsigned int nTimeReceived; // time received by this node
746 //// probably need to sign the order info so know it came from payer
748 // memory only UI hints
749 mutable unsigned int nTimeDisplayed;
750 mutable int nLinesDisplayed;
758 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
763 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
770 fTimeReceivedIsTxTime = false;
780 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
781 nVersion = this->nVersion;
784 READWRITE(vOrderForm);
785 READWRITE(fTimeReceivedIsTxTime);
786 READWRITE(nTimeReceived);
793 return CWalletDB().WriteTx(GetHash(), *this);
797 int64 GetTxTime() const;
798 int GetRequestCount() const;
800 void AddSupportingTransactions(CTxDB& txdb);
802 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
803 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
805 void RelayWalletTransaction(CTxDB& txdb);
806 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
813 // A txdb record that contains the disk location of a transaction and the
814 // locations of transactions that spend its outputs. vSpent is really only
815 // used as a flag, but having the location is very helpful for debugging.
821 vector<CDiskTxPos> vSpent;
828 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
831 vSpent.resize(nOutputs);
836 if (!(nType & SER_GETHASH))
853 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
855 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
857 for (int i = 0; i < a.vSpent.size(); i++)
858 if (a.vSpent[i] != b.vSpent[i])
863 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
874 // Nodes collect new transactions into a block, hash them into a hash tree,
875 // and scan through nonce values to make the block's hash satisfy proof-of-work
876 // requirements. When they solve the proof-of-work, they broadcast the block
877 // to everyone and the block is added to the block chain. The first transaction
878 // in the block is a special one that creates a new coin owned by the creator
881 // Blocks are appended to blk0001.dat files on disk. Their location on disk
882 // is indexed by CBlockIndex objects in memory.
889 uint256 hashPrevBlock;
890 uint256 hashMerkleRoot;
896 vector<CTransaction> vtx;
899 mutable vector<uint256> vMerkleTree;
909 READWRITE(this->nVersion);
910 nVersion = this->nVersion;
911 READWRITE(hashPrevBlock);
912 READWRITE(hashMerkleRoot);
917 // ConnectBlock depends on vtx being last so it can calculate offset
918 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
921 const_cast<CBlock*>(this)->vtx.clear();
941 uint256 GetHash() const
943 return Hash(BEGIN(nVersion), END(nNonce));
946 int64 GetBlockTime() const
952 uint256 BuildMerkleTree() const
955 foreach(const CTransaction& tx, vtx)
956 vMerkleTree.push_back(tx.GetHash());
958 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
960 for (int i = 0; i < nSize; i += 2)
962 int i2 = min(i+1, nSize-1);
963 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
964 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
968 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
971 vector<uint256> GetMerkleBranch(int nIndex) const
973 if (vMerkleTree.empty())
975 vector<uint256> vMerkleBranch;
977 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
979 int i = min(nIndex^1, nSize-1);
980 vMerkleBranch.push_back(vMerkleTree[j+i]);
984 return vMerkleBranch;
987 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
991 foreach(const uint256& otherside, vMerkleBranch)
994 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
996 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1003 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1005 // Open history file to append
1006 CAutoFile fileout = AppendBlockFile(nFileRet);
1008 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1009 if (!fWriteTransactions)
1010 fileout.nType |= SER_BLOCKHEADERONLY;
1012 // Write index header
1013 unsigned int nSize = fileout.GetSerializeSize(*this);
1014 fileout << FLATDATA(pchMessageStart) << nSize;
1017 nBlockPosRet = ftell(fileout);
1018 if (nBlockPosRet == -1)
1019 return error("CBlock::WriteToDisk() : ftell failed");
1022 // Flush stdio buffers and commit to disk before returning
1024 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1027 _commit(_fileno(fileout));
1029 fsync(fileno(fileout));
1036 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1040 // Open history file to read
1041 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1043 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1044 if (!fReadTransactions)
1045 filein.nType |= SER_BLOCKHEADERONLY;
1051 if (!CheckProofOfWork(GetHash(), nBits))
1052 return error("CBlock::ReadFromDisk() : errors in block header");
1061 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1062 GetHash().ToString().substr(0,20).c_str(),
1064 hashPrevBlock.ToString().substr(0,20).c_str(),
1065 hashMerkleRoot.ToString().substr(0,6).c_str(),
1066 nTime, nBits, nNonce,
1068 for (int i = 0; i < vtx.size(); i++)
1073 printf(" vMerkleTree: ");
1074 for (int i = 0; i < vMerkleTree.size(); i++)
1075 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
1080 int64 GetBlockValue(int nHeight, int64 nFees) const;
1081 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1082 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1083 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1084 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1085 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1086 bool CheckBlock() const;
1096 // The block chain is a tree shaped structure starting with the
1097 // genesis block at the root, with each block potentially having multiple
1098 // candidates to be the next block. pprev and pnext link a path through the
1099 // main/longest chain. A blockindex may have multiple pprev pointing back
1100 // to it, but pnext will only point forward to the longest branch, or will
1101 // be null if the block is not part of the longest chain.
1106 const uint256* phashBlock;
1110 unsigned int nBlockPos;
1112 CBigNum bnChainWork;
1116 uint256 hashMerkleRoot;
1119 unsigned int nNonce;
1139 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1145 nBlockPos = nBlockPosIn;
1149 nVersion = block.nVersion;
1150 hashMerkleRoot = block.hashMerkleRoot;
1151 nTime = block.nTime;
1152 nBits = block.nBits;
1153 nNonce = block.nNonce;
1156 uint256 GetBlockHash() const
1161 int64 GetBlockTime() const
1163 return (int64)nTime;
1166 CBigNum GetBlockWork() const
1168 if (CBigNum().SetCompact(nBits) <= 0)
1170 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);
1173 bool IsInMainChain() const
1175 return (pnext || this == pindexBest);
1178 bool CheckIndex() const
1180 return CheckProofOfWork(GetBlockHash(), nBits);
1183 bool EraseBlockFromDisk()
1185 // Open history file
1186 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1190 // Overwrite with empty null block
1198 enum { nMedianTimeSpan=11 };
1200 int64 GetMedianTimePast() const
1202 int64 pmedian[nMedianTimeSpan];
1203 int64* pbegin = &pmedian[nMedianTimeSpan];
1204 int64* pend = &pmedian[nMedianTimeSpan];
1206 const CBlockIndex* pindex = this;
1207 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1208 *(--pbegin) = pindex->GetBlockTime();
1211 return pbegin[(pend - pbegin)/2];
1214 int64 GetMedianTime() const
1216 const CBlockIndex* pindex = this;
1217 for (int i = 0; i < nMedianTimeSpan/2; i++)
1220 return GetBlockTime();
1221 pindex = pindex->pnext;
1223 return pindex->GetMedianTimePast();
1228 string ToString() const
1230 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1231 pprev, pnext, nFile, nBlockPos, nHeight,
1232 hashMerkleRoot.ToString().substr(0,6).c_str(),
1233 GetBlockHash().ToString().substr(0,20).c_str());
1238 printf("%s\n", ToString().c_str());
1245 // Used to marshal pointers into hashes for db storage.
1247 class CDiskBlockIndex : public CBlockIndex
1259 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1261 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1262 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1267 if (!(nType & SER_GETHASH))
1268 READWRITE(nVersion);
1270 READWRITE(hashNext);
1272 READWRITE(nBlockPos);
1276 READWRITE(this->nVersion);
1277 READWRITE(hashPrev);
1278 READWRITE(hashMerkleRoot);
1284 uint256 GetBlockHash() const
1287 block.nVersion = nVersion;
1288 block.hashPrevBlock = hashPrev;
1289 block.hashMerkleRoot = hashMerkleRoot;
1290 block.nTime = nTime;
1291 block.nBits = nBits;
1292 block.nNonce = nNonce;
1293 return block.GetHash();
1297 string ToString() const
1299 string str = "CDiskBlockIndex(";
1300 str += CBlockIndex::ToString();
1301 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1302 GetBlockHash().ToString().c_str(),
1303 hashPrev.ToString().substr(0,20).c_str(),
1304 hashNext.ToString().substr(0,20).c_str());
1310 printf("%s\n", ToString().c_str());
1322 // Describes a place in the block chain to another node such that if the
1323 // other node doesn't have the same branch, it can find a recent common trunk.
1324 // The further back it is, the further before the fork it may be.
1329 vector<uint256> vHave;
1336 explicit CBlockLocator(const CBlockIndex* pindex)
1341 explicit CBlockLocator(uint256 hashBlock)
1343 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1344 if (mi != mapBlockIndex.end())
1350 if (!(nType & SER_GETHASH))
1351 READWRITE(nVersion);
1355 void Set(const CBlockIndex* pindex)
1361 vHave.push_back(pindex->GetBlockHash());
1363 // Exponentially larger steps back
1364 for (int i = 0; pindex && i < nStep; i++)
1365 pindex = pindex->pprev;
1366 if (vHave.size() > 10)
1369 vHave.push_back(hashGenesisBlock);
1372 int GetDistanceBack()
1374 // Retrace how far back it was in the sender's branch
1377 foreach(const uint256& hash, vHave)
1379 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1380 if (mi != mapBlockIndex.end())
1382 CBlockIndex* pindex = (*mi).second;
1383 if (pindex->IsInMainChain())
1393 CBlockIndex* GetBlockIndex()
1395 // Find the first block the caller has in the main chain
1396 foreach(const uint256& hash, vHave)
1398 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1399 if (mi != mapBlockIndex.end())
1401 CBlockIndex* pindex = (*mi).second;
1402 if (pindex->IsInMainChain())
1406 return pindexGenesisBlock;
1409 uint256 GetBlockHash()
1411 // Find the first block the caller has in the main chain
1412 foreach(const uint256& hash, vHave)
1414 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1415 if (mi != mapBlockIndex.end())
1417 CBlockIndex* pindex = (*mi).second;
1418 if (pindex->IsInMainChain())
1422 return hashGenesisBlock;
1427 CBlockIndex* pindex = GetBlockIndex();
1430 return pindex->nHeight;
1440 // Private key that includes an expiration date in case it never gets used.
1445 CPrivKey vchPrivKey;
1449 //// todo: add something to note what created it (user, getnewaddress, change)
1450 //// maybe should have a map<string, string> property map
1452 CWalletKey(int64 nTimeExpiresIn=0)
1454 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
1455 nTimeExpires = nTimeExpiresIn;
1460 if (!(nType & SER_GETHASH))
1461 READWRITE(nVersion);
1462 READWRITE(vchPrivKey);
1463 READWRITE(nTimeCreated);
1464 READWRITE(nTimeExpires);
1465 READWRITE(strComment);
1475 // Alert messages are broadcast as a vector of signed data. Unserializing may
1476 // not read the entire buffer if the alert is for a newer version, but older
1477 // versions can still relay the original data.
1479 class CUnsignedAlert
1483 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1488 int nMinVer; // lowest version inclusive
1489 int nMaxVer; // highest version inclusive
1490 set<string> setSubVer; // empty matches all
1495 string strStatusBar;
1500 READWRITE(this->nVersion);
1501 nVersion = this->nVersion;
1502 READWRITE(nRelayUntil);
1503 READWRITE(nExpiration);
1506 READWRITE(setCancel);
1509 READWRITE(setSubVer);
1510 READWRITE(nPriority);
1512 READWRITE(strComment);
1513 READWRITE(strStatusBar);
1514 READWRITE(strRPCError);
1531 strStatusBar.clear();
1532 strRPCError.clear();
1535 string ToString() const
1537 string strSetCancel;
1538 foreach(int n, setCancel)
1539 strSetCancel += strprintf("%d ", n);
1540 string strSetSubVer;
1541 foreach(string str, setSubVer)
1542 strSetSubVer += "\"" + str + "\" ";
1546 " nRelayUntil = %"PRI64d"\n"
1547 " nExpiration = %"PRI64d"\n"
1555 " strComment = \"%s\"\n"
1556 " strStatusBar = \"%s\"\n"
1557 " strRPCError = \"%s\"\n"
1564 strSetCancel.c_str(),
1567 strSetSubVer.c_str(),
1570 strStatusBar.c_str(),
1571 strRPCError.c_str());
1576 printf("%s", ToString().c_str());
1580 class CAlert : public CUnsignedAlert
1583 vector<unsigned char> vchMsg;
1584 vector<unsigned char> vchSig;
1599 CUnsignedAlert::SetNull();
1606 return (nExpiration == 0);
1609 uint256 GetHash() const
1611 return SerializeHash(*this);
1614 bool IsInEffect() const
1616 return (GetAdjustedTime() < nExpiration);
1619 bool Cancels(const CAlert& alert) const
1623 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1626 bool AppliesTo(int nVersion, string strSubVerIn) const
1628 return (IsInEffect() &&
1629 nMinVer <= nVersion && nVersion <= nMaxVer &&
1630 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1633 bool AppliesToMe() const
1635 return AppliesTo(VERSION, ::pszSubVer);
1638 bool RelayTo(CNode* pnode) const
1642 // returns true if wasn't already contained in the set
1643 if (pnode->setKnown.insert(GetHash()).second)
1645 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1647 GetAdjustedTime() < nRelayUntil)
1649 pnode->PushMessage("alert", *this);
1656 bool CheckSignature()
1659 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1660 return error("CAlert::CheckSignature() : SetPubKey failed");
1661 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1662 return error("CAlert::CheckSignature() : verify signature failed");
1664 // Now unserialize the data
1665 CDataStream sMsg(vchMsg);
1666 sMsg >> *(CUnsignedAlert*)this;
1670 bool ProcessAlert();
1682 extern map<uint256, CTransaction> mapTransactions;
1683 extern map<uint256, CWalletTx> mapWallet;
1684 extern vector<uint256> vWalletUpdated;
1685 extern CCriticalSection cs_mapWallet;
1686 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1687 extern map<uint160, vector<unsigned char> > mapPubKeys;
1688 extern CCriticalSection cs_mapKeys;
1689 extern CKey keyUser;