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 unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
19 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
20 static const int64 COIN = 100000000;
21 static const int64 CENT = 1000000;
22 static const int64 MAX_MONEY = 21000000 * COIN;
23 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
24 static const int COINBASE_MATURITY = 100;
25 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
32 extern CCriticalSection cs_main;
33 extern map<uint256, CBlockIndex*> mapBlockIndex;
34 extern const uint256 hashGenesisBlock;
35 extern CBlockIndex* pindexGenesisBlock;
36 extern int nBestHeight;
37 extern CBigNum bnBestChainWork;
38 extern CBigNum bnBestInvalidWork;
39 extern uint256 hashBestChain;
40 extern CBlockIndex* pindexBest;
41 extern unsigned int nTransactionsUpdated;
42 extern map<uint256, int> mapRequestCount;
43 extern CCriticalSection cs_mapRequestCount;
44 extern map<string, string> mapAddressBook;
45 extern CCriticalSection cs_mapAddressBook;
46 extern vector<unsigned char> vchDefaultKey;
47 extern double dHashesPerSec;
48 extern int64 nHPSTimerStart;
51 extern int fGenerateBitcoins;
52 extern int64 nTransactionFee;
53 extern CAddress addrIncoming;
54 extern int fLimitProcessors;
55 extern int nLimitProcessors;
56 extern int fMinimizeToTray;
57 extern int fMinimizeOnClose;
65 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
66 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
67 FILE* AppendBlockFile(unsigned int& nFileRet);
68 bool AddKey(const CKey& key);
69 vector<unsigned char> GenerateNewKey();
70 bool AddToWallet(const CWalletTx& wtxIn);
71 void WalletUpdateSpent(const COutPoint& prevout);
72 void ReacceptWalletTransactions();
73 bool LoadBlockIndex(bool fAllowNew=true);
74 void PrintBlockTree();
75 bool ProcessMessages(CNode* pfrom);
76 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
77 bool SendMessages(CNode* pto, bool fSendTrickle);
79 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
80 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);
81 bool BroadcastTransaction(CWalletTx& wtxNew);
82 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
83 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
84 void GenerateBitcoins(bool fGenerate);
85 void ThreadBitcoinMiner(void* parg);
87 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
88 bool IsInitialBlockDownload();
89 string GetWarnings(string strFor);
106 unsigned int nBlockPos;
114 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
117 nBlockPos = nBlockPosIn;
121 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
122 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
123 bool IsNull() const { return (nFile == -1); }
125 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
127 return (a.nFile == b.nFile &&
128 a.nBlockPos == b.nBlockPos &&
129 a.nTxPos == b.nTxPos);
132 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
137 string ToString() const
140 return strprintf("null");
142 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
147 printf("%s", ToString().c_str());
160 CInPoint() { SetNull(); }
161 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
162 void SetNull() { ptx = NULL; n = -1; }
163 bool IsNull() const { return (ptx == NULL && n == -1); }
175 COutPoint() { SetNull(); }
176 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
177 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
178 void SetNull() { hash = 0; n = -1; }
179 bool IsNull() const { return (hash == 0 && n == -1); }
181 friend bool operator<(const COutPoint& a, const COutPoint& b)
183 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
186 friend bool operator==(const COutPoint& a, const COutPoint& b)
188 return (a.hash == b.hash && a.n == b.n);
191 friend bool operator!=(const COutPoint& a, const COutPoint& b)
196 string ToString() const
198 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
203 printf("%s\n", ToString().c_str());
211 // An input of a transaction. It contains the location of the previous
212 // transaction's output that it claims and a signature that matches the
213 // output's public key.
220 unsigned int nSequence;
224 nSequence = UINT_MAX;
227 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
230 scriptSig = scriptSigIn;
231 nSequence = nSequenceIn;
234 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
236 prevout = COutPoint(hashPrevTx, nOut);
237 scriptSig = scriptSigIn;
238 nSequence = nSequenceIn;
244 READWRITE(scriptSig);
245 READWRITE(nSequence);
250 return (nSequence == UINT_MAX);
253 friend bool operator==(const CTxIn& a, const CTxIn& b)
255 return (a.prevout == b.prevout &&
256 a.scriptSig == b.scriptSig &&
257 a.nSequence == b.nSequence);
260 friend bool operator!=(const CTxIn& a, const CTxIn& b)
265 string ToString() const
268 str += strprintf("CTxIn(");
269 str += prevout.ToString();
270 if (prevout.IsNull())
271 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
273 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
274 if (nSequence != UINT_MAX)
275 str += strprintf(", nSequence=%u", nSequence);
282 printf("%s\n", ToString().c_str());
286 int64 GetDebit() const;
293 // An output of a transaction. It contains the public key that the next input
294 // must be able to sign with to claim it.
300 CScript scriptPubKey;
307 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
310 scriptPubKey = scriptPubKeyIn;
316 READWRITE(scriptPubKey);
322 scriptPubKey.clear();
327 return (nValue == -1);
330 uint256 GetHash() const
332 return SerializeHash(*this);
337 return ::IsMine(scriptPubKey);
340 int64 GetCredit() const
342 if (!MoneyRange(nValue))
343 throw runtime_error("CTxOut::GetCredit() : value out of range");
349 friend bool operator==(const CTxOut& a, const CTxOut& b)
351 return (a.nValue == b.nValue &&
352 a.scriptPubKey == b.scriptPubKey);
355 friend bool operator!=(const CTxOut& a, const CTxOut& b)
360 string ToString() const
362 if (scriptPubKey.size() < 6)
363 return "CTxOut(error)";
364 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
369 printf("%s\n", ToString().c_str());
377 // The basic transaction that is broadcasted on the network and contained in
378 // blocks. A transaction can contain multiple inputs and outputs.
386 unsigned int nLockTime;
396 READWRITE(this->nVersion);
397 nVersion = this->nVersion;
400 READWRITE(nLockTime);
413 return (vin.empty() && vout.empty());
416 uint256 GetHash() const
418 return SerializeHash(*this);
421 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
423 // Time based nLockTime implemented in 0.1.6
426 if (nBlockHeight == 0)
427 nBlockHeight = nBestHeight;
429 nBlockTime = GetAdjustedTime();
430 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
432 foreach(const CTxIn& txin, vin)
438 bool IsNewerThan(const CTransaction& old) const
440 if (vin.size() != old.vin.size())
442 for (int i = 0; i < vin.size(); i++)
443 if (vin[i].prevout != old.vin[i].prevout)
447 unsigned int nLowest = UINT_MAX;
448 for (int i = 0; i < vin.size(); i++)
450 if (vin[i].nSequence != old.vin[i].nSequence)
452 if (vin[i].nSequence <= nLowest)
455 nLowest = vin[i].nSequence;
457 if (old.vin[i].nSequence < nLowest)
460 nLowest = old.vin[i].nSequence;
467 bool IsCoinBase() const
469 return (vin.size() == 1 && vin[0].prevout.IsNull());
472 bool CheckTransaction() const
474 // Basic checks that don't depend on any context
475 if (vin.empty() || vout.empty())
476 return error("CTransaction::CheckTransaction() : vin or vout empty");
479 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
480 return error("CTransaction::CheckTransaction() : size limits failed");
482 // Check for negative or overflow output values
484 foreach(const CTxOut& txout, vout)
486 if (txout.nValue < 0)
487 return error("CTransaction::CheckTransaction() : txout.nValue negative");
488 if (txout.nValue > MAX_MONEY)
489 return error("CTransaction::CheckTransaction() : txout.nValue too high");
490 nValueOut += txout.nValue;
491 if (!MoneyRange(nValueOut))
492 return error("CTransaction::CheckTransaction() : txout total out of range");
497 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
498 return error("CTransaction::CheckTransaction() : coinbase script size");
502 foreach(const CTxIn& txin, vin)
503 if (txin.prevout.IsNull())
504 return error("CTransaction::CheckTransaction() : prevout is null");
510 int GetSigOpCount() const
513 foreach(const CTxIn& txin, vin)
514 n += txin.scriptSig.GetSigOpCount();
515 foreach(const CTxOut& txout, vout)
516 n += txout.scriptPubKey.GetSigOpCount();
522 foreach(const CTxOut& txout, vout)
528 int64 GetDebit() const
531 foreach(const CTxIn& txin, vin)
533 nDebit += txin.GetDebit();
534 if (!MoneyRange(nDebit))
535 throw runtime_error("CTransaction::GetDebit() : value out of range");
540 int64 GetCredit() const
543 foreach(const CTxOut& txout, vout)
545 nCredit += txout.GetCredit();
546 if (!MoneyRange(nCredit))
547 throw runtime_error("CTransaction::GetCredit() : value out of range");
552 int64 GetValueOut() const
555 foreach(const CTxOut& txout, vout)
557 nValueOut += txout.nValue;
558 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
559 throw runtime_error("CTransaction::GetValueOut() : value out of range");
564 int64 GetMinFee(unsigned int nBlockSize=1) const
566 // Base fee is 1 cent per kilobyte
567 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
568 unsigned int nNewBlockSize = nBlockSize + nBytes;
569 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
571 // Transactions under 25K are free as long as block size is under 40K
572 // (about 11,000bc if made of 50bc inputs)
573 if (nBytes < 25000 && nNewBlockSize < 40000)
576 // Transactions under 3K are free as long as block size is under 50K
577 if (nBytes < 3000 && nNewBlockSize < 50000)
580 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
582 foreach(const CTxOut& txout, vout)
583 if (txout.nValue < CENT)
586 // Raise the price as the block approaches full
587 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
589 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
591 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
594 if (!MoneyRange(nMinFee))
600 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
602 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
604 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
607 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
608 return error("CTransaction::ReadFromDisk() : fseek failed");
611 // Return file pointer
614 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
615 return error("CTransaction::ReadFromDisk() : second fseek failed");
616 *pfileRet = filein.release();
622 friend bool operator==(const CTransaction& a, const CTransaction& b)
624 return (a.nVersion == b.nVersion &&
627 a.nLockTime == b.nLockTime);
630 friend bool operator!=(const CTransaction& a, const CTransaction& b)
636 string ToString() const
639 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
640 GetHash().ToString().substr(0,6).c_str(),
645 for (int i = 0; i < vin.size(); i++)
646 str += " " + vin[i].ToString() + "\n";
647 for (int i = 0; i < vout.size(); i++)
648 str += " " + vout[i].ToString() + "\n";
654 printf("%s", ToString().c_str());
659 bool DisconnectInputs(CTxDB& txdb);
660 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
661 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
662 bool ClientConnectInputs();
664 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
666 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
669 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
673 bool AddToMemoryPoolUnchecked();
675 bool RemoveFromMemoryPool();
683 // A transaction with a merkle branch linking it to the block chain
685 class CMerkleTx : public CTransaction
689 vector<uint256> vMerkleBranch;
693 mutable bool fMerkleVerified;
694 mutable bool fGetCreditCached;
695 mutable int64 nGetCreditCached;
703 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
712 fMerkleVerified = false;
713 fGetCreditCached = false;
714 nGetCreditCached = 0;
719 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
720 nVersion = this->nVersion;
721 READWRITE(hashBlock);
722 READWRITE(vMerkleBranch);
726 int64 GetCredit(bool fUseCache=false) const
728 // Must wait until coinbase is safely deep enough in the chain before valuing it
729 if (IsCoinBase() && GetBlocksToMaturity() > 0)
732 // GetBalance can assume transactions in mapWallet won't change
733 if (fUseCache && fGetCreditCached)
734 return nGetCreditCached;
735 nGetCreditCached = CTransaction::GetCredit();
736 fGetCreditCached = true;
737 return nGetCreditCached;
741 int SetMerkleBranch(const CBlock* pblock=NULL);
742 int GetDepthInMainChain(int& nHeightRet) const;
743 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
744 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
745 int GetBlocksToMaturity() const;
746 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
747 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
754 // A transaction with a bunch of additional info that only the owner cares
755 // about. It includes any unrecorded transactions needed to link it back
756 // to the block chain.
758 class CWalletTx : public CMerkleTx
761 vector<CMerkleTx> vtxPrev;
762 map<string, string> mapValue;
763 vector<pair<string, string> > vOrderForm;
764 unsigned int fTimeReceivedIsTxTime;
765 unsigned int nTimeReceived; // time received by this node
768 //// probably need to sign the order info so know it came from payer
770 // memory only UI hints
771 mutable unsigned int nTimeDisplayed;
772 mutable int nLinesDisplayed;
780 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
785 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
792 fTimeReceivedIsTxTime = false;
802 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
803 nVersion = this->nVersion;
806 READWRITE(vOrderForm);
807 READWRITE(fTimeReceivedIsTxTime);
808 READWRITE(nTimeReceived);
815 return CWalletDB().WriteTx(GetHash(), *this);
819 int64 GetTxTime() const;
820 int GetRequestCount() const;
822 void AddSupportingTransactions(CTxDB& txdb);
824 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
825 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
827 void RelayWalletTransaction(CTxDB& txdb);
828 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
835 // A txdb record that contains the disk location of a transaction and the
836 // locations of transactions that spend its outputs. vSpent is really only
837 // used as a flag, but having the location is very helpful for debugging.
843 vector<CDiskTxPos> vSpent;
850 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
853 vSpent.resize(nOutputs);
858 if (!(nType & SER_GETHASH))
875 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
877 return (a.pos == b.pos &&
878 a.vSpent == b.vSpent);
881 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
892 // Nodes collect new transactions into a block, hash them into a hash tree,
893 // and scan through nonce values to make the block's hash satisfy proof-of-work
894 // requirements. When they solve the proof-of-work, they broadcast the block
895 // to everyone and the block is added to the block chain. The first transaction
896 // in the block is a special one that creates a new coin owned by the creator
899 // Blocks are appended to blk0001.dat files on disk. Their location on disk
900 // is indexed by CBlockIndex objects in memory.
907 uint256 hashPrevBlock;
908 uint256 hashMerkleRoot;
914 vector<CTransaction> vtx;
917 mutable vector<uint256> vMerkleTree;
927 READWRITE(this->nVersion);
928 nVersion = this->nVersion;
929 READWRITE(hashPrevBlock);
930 READWRITE(hashMerkleRoot);
935 // ConnectBlock depends on vtx being last so it can calculate offset
936 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
939 const_cast<CBlock*>(this)->vtx.clear();
959 uint256 GetHash() const
961 return Hash(BEGIN(nVersion), END(nNonce));
964 int64 GetBlockTime() const
969 int GetSigOpCount() const
972 foreach(const CTransaction& tx, vtx)
973 n += tx.GetSigOpCount();
978 uint256 BuildMerkleTree() const
981 foreach(const CTransaction& tx, vtx)
982 vMerkleTree.push_back(tx.GetHash());
984 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
986 for (int i = 0; i < nSize; i += 2)
988 int i2 = min(i+1, nSize-1);
989 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
990 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
994 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
997 vector<uint256> GetMerkleBranch(int nIndex) const
999 if (vMerkleTree.empty())
1001 vector<uint256> vMerkleBranch;
1003 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1005 int i = min(nIndex^1, nSize-1);
1006 vMerkleBranch.push_back(vMerkleTree[j+i]);
1010 return vMerkleBranch;
1013 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1017 foreach(const uint256& otherside, vMerkleBranch)
1020 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1022 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1029 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1031 // Open history file to append
1032 CAutoFile fileout = AppendBlockFile(nFileRet);
1034 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1035 if (!fWriteTransactions)
1036 fileout.nType |= SER_BLOCKHEADERONLY;
1038 // Write index header
1039 unsigned int nSize = fileout.GetSerializeSize(*this);
1040 fileout << FLATDATA(pchMessageStart) << nSize;
1043 nBlockPosRet = ftell(fileout);
1044 if (nBlockPosRet == -1)
1045 return error("CBlock::WriteToDisk() : ftell failed");
1048 // Flush stdio buffers and commit to disk before returning
1050 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1053 _commit(_fileno(fileout));
1055 fsync(fileno(fileout));
1062 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1066 // Open history file to read
1067 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1069 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1070 if (!fReadTransactions)
1071 filein.nType |= SER_BLOCKHEADERONLY;
1077 if (!CheckProofOfWork(GetHash(), nBits))
1078 return error("CBlock::ReadFromDisk() : errors in block header");
1087 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1088 GetHash().ToString().substr(0,20).c_str(),
1090 hashPrevBlock.ToString().substr(0,20).c_str(),
1091 hashMerkleRoot.ToString().substr(0,6).c_str(),
1092 nTime, nBits, nNonce,
1094 for (int i = 0; i < vtx.size(); i++)
1099 printf(" vMerkleTree: ");
1100 for (int i = 0; i < vMerkleTree.size(); i++)
1101 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
1106 int64 GetBlockValue(int nHeight, int64 nFees) const;
1107 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1108 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1109 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1110 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1111 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1112 bool CheckBlock() const;
1122 // The block chain is a tree shaped structure starting with the
1123 // genesis block at the root, with each block potentially having multiple
1124 // candidates to be the next block. pprev and pnext link a path through the
1125 // main/longest chain. A blockindex may have multiple pprev pointing back
1126 // to it, but pnext will only point forward to the longest branch, or will
1127 // be null if the block is not part of the longest chain.
1132 const uint256* phashBlock;
1136 unsigned int nBlockPos;
1138 CBigNum bnChainWork;
1142 uint256 hashMerkleRoot;
1145 unsigned int nNonce;
1165 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1171 nBlockPos = nBlockPosIn;
1175 nVersion = block.nVersion;
1176 hashMerkleRoot = block.hashMerkleRoot;
1177 nTime = block.nTime;
1178 nBits = block.nBits;
1179 nNonce = block.nNonce;
1182 uint256 GetBlockHash() const
1187 int64 GetBlockTime() const
1189 return (int64)nTime;
1192 CBigNum GetBlockWork() const
1195 bnTarget.SetCompact(nBits);
1198 return (CBigNum(1)<<256) / (bnTarget+1);
1201 bool IsInMainChain() const
1203 return (pnext || this == pindexBest);
1206 bool CheckIndex() const
1208 return CheckProofOfWork(GetBlockHash(), nBits);
1211 bool EraseBlockFromDisk()
1213 // Open history file
1214 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1218 // Overwrite with empty null block
1226 enum { nMedianTimeSpan=11 };
1228 int64 GetMedianTimePast() const
1230 int64 pmedian[nMedianTimeSpan];
1231 int64* pbegin = &pmedian[nMedianTimeSpan];
1232 int64* pend = &pmedian[nMedianTimeSpan];
1234 const CBlockIndex* pindex = this;
1235 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1236 *(--pbegin) = pindex->GetBlockTime();
1239 return pbegin[(pend - pbegin)/2];
1242 int64 GetMedianTime() const
1244 const CBlockIndex* pindex = this;
1245 for (int i = 0; i < nMedianTimeSpan/2; i++)
1248 return GetBlockTime();
1249 pindex = pindex->pnext;
1251 return pindex->GetMedianTimePast();
1256 string ToString() const
1258 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1259 pprev, pnext, nFile, nBlockPos, nHeight,
1260 hashMerkleRoot.ToString().substr(0,6).c_str(),
1261 GetBlockHash().ToString().substr(0,20).c_str());
1266 printf("%s\n", ToString().c_str());
1273 // Used to marshal pointers into hashes for db storage.
1275 class CDiskBlockIndex : public CBlockIndex
1287 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1289 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1290 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1295 if (!(nType & SER_GETHASH))
1296 READWRITE(nVersion);
1298 READWRITE(hashNext);
1300 READWRITE(nBlockPos);
1304 READWRITE(this->nVersion);
1305 READWRITE(hashPrev);
1306 READWRITE(hashMerkleRoot);
1312 uint256 GetBlockHash() const
1315 block.nVersion = nVersion;
1316 block.hashPrevBlock = hashPrev;
1317 block.hashMerkleRoot = hashMerkleRoot;
1318 block.nTime = nTime;
1319 block.nBits = nBits;
1320 block.nNonce = nNonce;
1321 return block.GetHash();
1325 string ToString() const
1327 string str = "CDiskBlockIndex(";
1328 str += CBlockIndex::ToString();
1329 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1330 GetBlockHash().ToString().c_str(),
1331 hashPrev.ToString().substr(0,20).c_str(),
1332 hashNext.ToString().substr(0,20).c_str());
1338 printf("%s\n", ToString().c_str());
1350 // Describes a place in the block chain to another node such that if the
1351 // other node doesn't have the same branch, it can find a recent common trunk.
1352 // The further back it is, the further before the fork it may be.
1357 vector<uint256> vHave;
1364 explicit CBlockLocator(const CBlockIndex* pindex)
1369 explicit CBlockLocator(uint256 hashBlock)
1371 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1372 if (mi != mapBlockIndex.end())
1378 if (!(nType & SER_GETHASH))
1379 READWRITE(nVersion);
1383 void Set(const CBlockIndex* pindex)
1389 vHave.push_back(pindex->GetBlockHash());
1391 // Exponentially larger steps back
1392 for (int i = 0; pindex && i < nStep; i++)
1393 pindex = pindex->pprev;
1394 if (vHave.size() > 10)
1397 vHave.push_back(hashGenesisBlock);
1400 int GetDistanceBack()
1402 // Retrace how far back it was in the sender's branch
1405 foreach(const uint256& hash, vHave)
1407 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1408 if (mi != mapBlockIndex.end())
1410 CBlockIndex* pindex = (*mi).second;
1411 if (pindex->IsInMainChain())
1421 CBlockIndex* GetBlockIndex()
1423 // Find the first block the caller has in the main chain
1424 foreach(const uint256& hash, vHave)
1426 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1427 if (mi != mapBlockIndex.end())
1429 CBlockIndex* pindex = (*mi).second;
1430 if (pindex->IsInMainChain())
1434 return pindexGenesisBlock;
1437 uint256 GetBlockHash()
1439 // Find the first block the caller has in the main chain
1440 foreach(const uint256& hash, vHave)
1442 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1443 if (mi != mapBlockIndex.end())
1445 CBlockIndex* pindex = (*mi).second;
1446 if (pindex->IsInMainChain())
1450 return hashGenesisBlock;
1455 CBlockIndex* pindex = GetBlockIndex();
1458 return pindex->nHeight;
1468 // Private key that includes an expiration date in case it never gets used.
1473 CPrivKey vchPrivKey;
1477 //// todo: add something to note what created it (user, getnewaddress, change)
1478 //// maybe should have a map<string, string> property map
1480 CWalletKey(int64 nExpires=0)
1482 nTimeCreated = (nExpires ? GetTime() : 0);
1483 nTimeExpires = nExpires;
1488 if (!(nType & SER_GETHASH))
1489 READWRITE(nVersion);
1490 READWRITE(vchPrivKey);
1491 READWRITE(nTimeCreated);
1492 READWRITE(nTimeExpires);
1493 READWRITE(strComment);
1503 // Alert messages are broadcast as a vector of signed data. Unserializing may
1504 // not read the entire buffer if the alert is for a newer version, but older
1505 // versions can still relay the original data.
1507 class CUnsignedAlert
1511 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1516 int nMinVer; // lowest version inclusive
1517 int nMaxVer; // highest version inclusive
1518 set<string> setSubVer; // empty matches all
1523 string strStatusBar;
1528 READWRITE(this->nVersion);
1529 nVersion = this->nVersion;
1530 READWRITE(nRelayUntil);
1531 READWRITE(nExpiration);
1534 READWRITE(setCancel);
1537 READWRITE(setSubVer);
1538 READWRITE(nPriority);
1540 READWRITE(strComment);
1541 READWRITE(strStatusBar);
1542 READWRITE(strRPCError);
1559 strStatusBar.clear();
1560 strRPCError.clear();
1563 string ToString() const
1565 string strSetCancel;
1566 foreach(int n, setCancel)
1567 strSetCancel += strprintf("%d ", n);
1568 string strSetSubVer;
1569 foreach(string str, setSubVer)
1570 strSetSubVer += "\"" + str + "\" ";
1574 " nRelayUntil = %"PRI64d"\n"
1575 " nExpiration = %"PRI64d"\n"
1583 " strComment = \"%s\"\n"
1584 " strStatusBar = \"%s\"\n"
1585 " strRPCError = \"%s\"\n"
1592 strSetCancel.c_str(),
1595 strSetSubVer.c_str(),
1598 strStatusBar.c_str(),
1599 strRPCError.c_str());
1604 printf("%s", ToString().c_str());
1608 class CAlert : public CUnsignedAlert
1611 vector<unsigned char> vchMsg;
1612 vector<unsigned char> vchSig;
1627 CUnsignedAlert::SetNull();
1634 return (nExpiration == 0);
1637 uint256 GetHash() const
1639 return SerializeHash(*this);
1642 bool IsInEffect() const
1644 return (GetAdjustedTime() < nExpiration);
1647 bool Cancels(const CAlert& alert) const
1651 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1654 bool AppliesTo(int nVersion, string strSubVerIn) const
1656 return (IsInEffect() &&
1657 nMinVer <= nVersion && nVersion <= nMaxVer &&
1658 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1661 bool AppliesToMe() const
1663 return AppliesTo(VERSION, ::pszSubVer);
1666 bool RelayTo(CNode* pnode) const
1670 // returns true if wasn't already contained in the set
1671 if (pnode->setKnown.insert(GetHash()).second)
1673 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1675 GetAdjustedTime() < nRelayUntil)
1677 pnode->PushMessage("alert", *this);
1684 bool CheckSignature()
1687 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1688 return error("CAlert::CheckSignature() : SetPubKey failed");
1689 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1690 return error("CAlert::CheckSignature() : verify signature failed");
1692 // Now unserialize the data
1693 CDataStream sMsg(vchMsg);
1694 sMsg >> *(CUnsignedAlert*)this;
1698 bool ProcessAlert();
1710 extern map<uint256, CTransaction> mapTransactions;
1711 extern map<uint256, CWalletTx> mapWallet;
1712 extern vector<uint256> vWalletUpdated;
1713 extern CCriticalSection cs_mapWallet;
1714 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1715 extern map<uint160, vector<unsigned char> > mapPubKeys;
1716 extern CCriticalSection cs_mapKeys;
1717 extern CKey keyUser;