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 int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
19 static const int64 COIN = 100000000;
20 static const int64 CENT = 1000000;
21 static const int64 MAX_MONEY = 21000000 * COIN;
22 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
23 static const int COINBASE_MATURITY = 100;
24 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
31 extern CCriticalSection cs_main;
32 extern map<uint256, CBlockIndex*> mapBlockIndex;
33 extern const uint256 hashGenesisBlock;
34 extern CBlockIndex* pindexGenesisBlock;
35 extern int nBestHeight;
36 extern CBigNum bnBestChainWork;
37 extern CBigNum bnBestInvalidWork;
38 extern uint256 hashBestChain;
39 extern CBlockIndex* pindexBest;
40 extern unsigned int nTransactionsUpdated;
41 extern map<uint256, int> mapRequestCount;
42 extern CCriticalSection cs_mapRequestCount;
43 extern map<string, string> mapAddressBook;
44 extern CCriticalSection cs_mapAddressBook;
45 extern vector<unsigned char> vchDefaultKey;
46 extern double dHashesPerSec;
47 extern int64 nHPSTimerStart;
50 extern int fGenerateBitcoins;
51 extern int64 nTransactionFee;
52 extern CAddress addrIncoming;
53 extern int fLimitProcessors;
54 extern int nLimitProcessors;
55 extern int fMinimizeToTray;
56 extern int fMinimizeOnClose;
64 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
65 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
66 FILE* AppendBlockFile(unsigned int& nFileRet);
67 bool AddKey(const CKey& key);
68 vector<unsigned char> GenerateNewKey();
69 bool AddToWallet(const CWalletTx& wtxIn);
70 void WalletUpdateSpent(const COutPoint& prevout);
71 void ReacceptWalletTransactions();
72 bool LoadBlockIndex(bool fAllowNew=true);
73 void PrintBlockTree();
74 bool ProcessMessages(CNode* pfrom);
75 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
76 bool SendMessages(CNode* pto, bool fSendTrickle);
78 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
79 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);
80 bool BroadcastTransaction(CWalletTx& wtxNew);
81 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
82 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
83 void GenerateBitcoins(bool fGenerate);
84 void ThreadBitcoinMiner(void* parg);
86 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
87 bool IsInitialBlockDownload();
88 string GetWarnings(string strFor);
105 unsigned int nBlockPos;
113 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
116 nBlockPos = nBlockPosIn;
120 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
121 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
122 bool IsNull() const { return (nFile == -1); }
124 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
126 return (a.nFile == b.nFile &&
127 a.nBlockPos == b.nBlockPos &&
128 a.nTxPos == b.nTxPos);
131 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
136 string ToString() const
139 return strprintf("null");
141 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
146 printf("%s", ToString().c_str());
159 CInPoint() { SetNull(); }
160 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
161 void SetNull() { ptx = NULL; n = -1; }
162 bool IsNull() const { return (ptx == NULL && n == -1); }
174 COutPoint() { SetNull(); }
175 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
176 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
177 void SetNull() { hash = 0; n = -1; }
178 bool IsNull() const { return (hash == 0 && n == -1); }
180 friend bool operator<(const COutPoint& a, const COutPoint& b)
182 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
185 friend bool operator==(const COutPoint& a, const COutPoint& b)
187 return (a.hash == b.hash && a.n == b.n);
190 friend bool operator!=(const COutPoint& a, const COutPoint& b)
195 string ToString() const
197 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
202 printf("%s\n", ToString().c_str());
210 // An input of a transaction. It contains the location of the previous
211 // transaction's output that it claims and a signature that matches the
212 // output's public key.
219 unsigned int nSequence;
223 nSequence = UINT_MAX;
226 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
229 scriptSig = scriptSigIn;
230 nSequence = nSequenceIn;
233 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
235 prevout = COutPoint(hashPrevTx, nOut);
236 scriptSig = scriptSigIn;
237 nSequence = nSequenceIn;
243 READWRITE(scriptSig);
244 READWRITE(nSequence);
249 return (nSequence == UINT_MAX);
252 friend bool operator==(const CTxIn& a, const CTxIn& b)
254 return (a.prevout == b.prevout &&
255 a.scriptSig == b.scriptSig &&
256 a.nSequence == b.nSequence);
259 friend bool operator!=(const CTxIn& a, const CTxIn& b)
264 string ToString() const
267 str += strprintf("CTxIn(");
268 str += prevout.ToString();
269 if (prevout.IsNull())
270 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
272 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
273 if (nSequence != UINT_MAX)
274 str += strprintf(", nSequence=%u", nSequence);
281 printf("%s\n", ToString().c_str());
285 int64 GetDebit() const;
292 // An output of a transaction. It contains the public key that the next input
293 // must be able to sign with to claim it.
299 CScript scriptPubKey;
306 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
309 scriptPubKey = scriptPubKeyIn;
315 READWRITE(scriptPubKey);
321 scriptPubKey.clear();
326 return (nValue == -1);
329 uint256 GetHash() const
331 return SerializeHash(*this);
336 return ::IsMine(scriptPubKey);
339 int64 GetCredit() const
341 if (!MoneyRange(nValue))
342 throw runtime_error("CTxOut::GetCredit() : value out of range");
348 friend bool operator==(const CTxOut& a, const CTxOut& b)
350 return (a.nValue == b.nValue &&
351 a.scriptPubKey == b.scriptPubKey);
354 friend bool operator!=(const CTxOut& a, const CTxOut& b)
359 string ToString() const
361 if (scriptPubKey.size() < 6)
362 return "CTxOut(error)";
363 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
368 printf("%s\n", ToString().c_str());
376 // The basic transaction that is broadcasted on the network and contained in
377 // blocks. A transaction can contain multiple inputs and outputs.
385 unsigned int nLockTime;
395 READWRITE(this->nVersion);
396 nVersion = this->nVersion;
399 READWRITE(nLockTime);
412 return (vin.empty() && vout.empty());
415 uint256 GetHash() const
417 return SerializeHash(*this);
420 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
422 // Time based nLockTime implemented in 0.1.6
425 if (nBlockHeight == 0)
426 nBlockHeight = nBestHeight;
428 nBlockTime = GetAdjustedTime();
429 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
431 foreach(const CTxIn& txin, vin)
437 bool IsNewerThan(const CTransaction& old) const
439 if (vin.size() != old.vin.size())
441 for (int i = 0; i < vin.size(); i++)
442 if (vin[i].prevout != old.vin[i].prevout)
446 unsigned int nLowest = UINT_MAX;
447 for (int i = 0; i < vin.size(); i++)
449 if (vin[i].nSequence != old.vin[i].nSequence)
451 if (vin[i].nSequence <= nLowest)
454 nLowest = vin[i].nSequence;
456 if (old.vin[i].nSequence < nLowest)
459 nLowest = old.vin[i].nSequence;
466 bool IsCoinBase() const
468 return (vin.size() == 1 && vin[0].prevout.IsNull());
471 bool CheckTransaction() const
473 // Basic checks that don't depend on any context
474 if (vin.empty() || vout.empty())
475 return error("CTransaction::CheckTransaction() : vin or vout empty");
478 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_SIZE)
479 return error("CTransaction::CheckTransaction() : size limits failed");
481 // Check for negative or overflow output values
483 foreach(const CTxOut& txout, vout)
485 if (txout.nValue < 0)
486 return error("CTransaction::CheckTransaction() : txout.nValue negative");
487 if (txout.nValue > MAX_MONEY)
488 return error("CTransaction::CheckTransaction() : txout.nValue too high");
489 nValueOut += txout.nValue;
490 if (!MoneyRange(nValueOut))
491 return error("CTransaction::CheckTransaction() : txout total out of range");
496 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
497 return error("CTransaction::CheckTransaction() : coinbase script size");
501 foreach(const CTxIn& txin, vin)
502 if (txin.prevout.IsNull())
503 return error("CTransaction::CheckTransaction() : prevout is null");
509 int GetSigOpCount() const
512 foreach(const CTxIn& txin, vin)
513 n += txin.scriptSig.GetSigOpCount();
514 foreach(const CTxOut& txout, vout)
515 n += txout.scriptPubKey.GetSigOpCount();
521 foreach(const CTxOut& txout, vout)
527 int64 GetDebit() const
530 foreach(const CTxIn& txin, vin)
532 nDebit += txin.GetDebit();
533 if (!MoneyRange(nDebit))
534 throw runtime_error("CTransaction::GetDebit() : value out of range");
539 int64 GetCredit() const
542 foreach(const CTxOut& txout, vout)
544 nCredit += txout.GetCredit();
545 if (!MoneyRange(nCredit))
546 throw runtime_error("CTransaction::GetCredit() : value out of range");
551 int64 GetValueOut() const
554 foreach(const CTxOut& txout, vout)
556 nValueOut += txout.nValue;
557 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
558 throw runtime_error("CTransaction::GetValueOut() : value out of range");
563 int64 GetMinFee(unsigned int nBlockSize=1) const
565 // Base fee is 1 cent per kilobyte
566 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
567 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
569 // Transactions under 60K are free as long as block size is under 80K
570 // (about 27,000bc if made of 50bc inputs)
571 if (nBytes < 60000 && nBlockSize < 80000)
574 // Transactions under 3K are free as long as block size is under 200K
575 if (nBytes < 3000 && nBlockSize < 200000)
578 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
580 foreach(const CTxOut& txout, vout)
581 if (txout.nValue < CENT)
584 // Raise the price as the block approaches full
585 if (MAX_BLOCK_SIZE/2 <= nBlockSize && nBlockSize < MAX_BLOCK_SIZE)
586 nMinFee *= MAX_BLOCK_SIZE / (MAX_BLOCK_SIZE - nBlockSize);
587 if (!MoneyRange(nMinFee))
594 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
596 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
598 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
601 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
602 return error("CTransaction::ReadFromDisk() : fseek failed");
605 // Return file pointer
608 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
609 return error("CTransaction::ReadFromDisk() : second fseek failed");
610 *pfileRet = filein.release();
616 friend bool operator==(const CTransaction& a, const CTransaction& b)
618 return (a.nVersion == b.nVersion &&
621 a.nLockTime == b.nLockTime);
624 friend bool operator!=(const CTransaction& a, const CTransaction& b)
630 string ToString() const
633 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
634 GetHash().ToString().substr(0,6).c_str(),
639 for (int i = 0; i < vin.size(); i++)
640 str += " " + vin[i].ToString() + "\n";
641 for (int i = 0; i < vout.size(); i++)
642 str += " " + vout[i].ToString() + "\n";
648 printf("%s", ToString().c_str());
653 bool DisconnectInputs(CTxDB& txdb);
654 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
655 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
656 bool ClientConnectInputs();
658 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
660 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
663 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
667 bool AddToMemoryPoolUnchecked();
669 bool RemoveFromMemoryPool();
677 // A transaction with a merkle branch linking it to the block chain
679 class CMerkleTx : public CTransaction
683 vector<uint256> vMerkleBranch;
687 mutable bool fMerkleVerified;
688 mutable bool fGetCreditCached;
689 mutable int64 nGetCreditCached;
697 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
706 fMerkleVerified = false;
707 fGetCreditCached = false;
708 nGetCreditCached = 0;
713 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
714 nVersion = this->nVersion;
715 READWRITE(hashBlock);
716 READWRITE(vMerkleBranch);
720 int64 GetCredit(bool fUseCache=false) const
722 // Must wait until coinbase is safely deep enough in the chain before valuing it
723 if (IsCoinBase() && GetBlocksToMaturity() > 0)
726 // GetBalance can assume transactions in mapWallet won't change
727 if (fUseCache && fGetCreditCached)
728 return nGetCreditCached;
729 nGetCreditCached = CTransaction::GetCredit();
730 fGetCreditCached = true;
731 return nGetCreditCached;
735 int SetMerkleBranch(const CBlock* pblock=NULL);
736 int GetDepthInMainChain(int& nHeightRet) const;
737 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
738 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
739 int GetBlocksToMaturity() const;
740 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
741 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
748 // A transaction with a bunch of additional info that only the owner cares
749 // about. It includes any unrecorded transactions needed to link it back
750 // to the block chain.
752 class CWalletTx : public CMerkleTx
755 vector<CMerkleTx> vtxPrev;
756 map<string, string> mapValue;
757 vector<pair<string, string> > vOrderForm;
758 unsigned int fTimeReceivedIsTxTime;
759 unsigned int nTimeReceived; // time received by this node
762 //// probably need to sign the order info so know it came from payer
764 // memory only UI hints
765 mutable unsigned int nTimeDisplayed;
766 mutable int nLinesDisplayed;
774 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
779 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
786 fTimeReceivedIsTxTime = false;
796 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
797 nVersion = this->nVersion;
800 READWRITE(vOrderForm);
801 READWRITE(fTimeReceivedIsTxTime);
802 READWRITE(nTimeReceived);
809 return CWalletDB().WriteTx(GetHash(), *this);
813 int64 GetTxTime() const;
814 int GetRequestCount() const;
816 void AddSupportingTransactions(CTxDB& txdb);
818 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
819 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
821 void RelayWalletTransaction(CTxDB& txdb);
822 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
829 // A txdb record that contains the disk location of a transaction and the
830 // locations of transactions that spend its outputs. vSpent is really only
831 // used as a flag, but having the location is very helpful for debugging.
837 vector<CDiskTxPos> vSpent;
844 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
847 vSpent.resize(nOutputs);
852 if (!(nType & SER_GETHASH))
869 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
871 return (a.pos == b.pos &&
872 a.vSpent == b.vSpent);
875 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
886 // Nodes collect new transactions into a block, hash them into a hash tree,
887 // and scan through nonce values to make the block's hash satisfy proof-of-work
888 // requirements. When they solve the proof-of-work, they broadcast the block
889 // to everyone and the block is added to the block chain. The first transaction
890 // in the block is a special one that creates a new coin owned by the creator
893 // Blocks are appended to blk0001.dat files on disk. Their location on disk
894 // is indexed by CBlockIndex objects in memory.
901 uint256 hashPrevBlock;
902 uint256 hashMerkleRoot;
908 vector<CTransaction> vtx;
911 mutable vector<uint256> vMerkleTree;
921 READWRITE(this->nVersion);
922 nVersion = this->nVersion;
923 READWRITE(hashPrevBlock);
924 READWRITE(hashMerkleRoot);
929 // ConnectBlock depends on vtx being last so it can calculate offset
930 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
933 const_cast<CBlock*>(this)->vtx.clear();
953 uint256 GetHash() const
955 return Hash(BEGIN(nVersion), END(nNonce));
958 int64 GetBlockTime() const
963 int GetSigOpCount() const
966 foreach(const CTransaction& tx, vtx)
967 n += tx.GetSigOpCount();
972 uint256 BuildMerkleTree() const
975 foreach(const CTransaction& tx, vtx)
976 vMerkleTree.push_back(tx.GetHash());
978 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
980 for (int i = 0; i < nSize; i += 2)
982 int i2 = min(i+1, nSize-1);
983 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
984 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
988 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
991 vector<uint256> GetMerkleBranch(int nIndex) const
993 if (vMerkleTree.empty())
995 vector<uint256> vMerkleBranch;
997 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
999 int i = min(nIndex^1, nSize-1);
1000 vMerkleBranch.push_back(vMerkleTree[j+i]);
1004 return vMerkleBranch;
1007 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1011 foreach(const uint256& otherside, vMerkleBranch)
1014 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1016 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1023 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1025 // Open history file to append
1026 CAutoFile fileout = AppendBlockFile(nFileRet);
1028 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1029 if (!fWriteTransactions)
1030 fileout.nType |= SER_BLOCKHEADERONLY;
1032 // Write index header
1033 unsigned int nSize = fileout.GetSerializeSize(*this);
1034 fileout << FLATDATA(pchMessageStart) << nSize;
1037 nBlockPosRet = ftell(fileout);
1038 if (nBlockPosRet == -1)
1039 return error("CBlock::WriteToDisk() : ftell failed");
1042 // Flush stdio buffers and commit to disk before returning
1044 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1047 _commit(_fileno(fileout));
1049 fsync(fileno(fileout));
1056 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1060 // Open history file to read
1061 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1063 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1064 if (!fReadTransactions)
1065 filein.nType |= SER_BLOCKHEADERONLY;
1071 if (!CheckProofOfWork(GetHash(), nBits))
1072 return error("CBlock::ReadFromDisk() : errors in block header");
1081 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1082 GetHash().ToString().substr(0,20).c_str(),
1084 hashPrevBlock.ToString().substr(0,20).c_str(),
1085 hashMerkleRoot.ToString().substr(0,6).c_str(),
1086 nTime, nBits, nNonce,
1088 for (int i = 0; i < vtx.size(); i++)
1093 printf(" vMerkleTree: ");
1094 for (int i = 0; i < vMerkleTree.size(); i++)
1095 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
1100 int64 GetBlockValue(int nHeight, int64 nFees) const;
1101 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1102 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1103 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1104 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1105 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1106 bool CheckBlock() const;
1116 // The block chain is a tree shaped structure starting with the
1117 // genesis block at the root, with each block potentially having multiple
1118 // candidates to be the next block. pprev and pnext link a path through the
1119 // main/longest chain. A blockindex may have multiple pprev pointing back
1120 // to it, but pnext will only point forward to the longest branch, or will
1121 // be null if the block is not part of the longest chain.
1126 const uint256* phashBlock;
1130 unsigned int nBlockPos;
1132 CBigNum bnChainWork;
1136 uint256 hashMerkleRoot;
1139 unsigned int nNonce;
1159 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1165 nBlockPos = nBlockPosIn;
1169 nVersion = block.nVersion;
1170 hashMerkleRoot = block.hashMerkleRoot;
1171 nTime = block.nTime;
1172 nBits = block.nBits;
1173 nNonce = block.nNonce;
1176 uint256 GetBlockHash() const
1181 int64 GetBlockTime() const
1183 return (int64)nTime;
1186 CBigNum GetBlockWork() const
1188 if (CBigNum().SetCompact(nBits) <= 0)
1190 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);
1193 bool IsInMainChain() const
1195 return (pnext || this == pindexBest);
1198 bool CheckIndex() const
1200 return CheckProofOfWork(GetBlockHash(), nBits);
1203 bool EraseBlockFromDisk()
1205 // Open history file
1206 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1210 // Overwrite with empty null block
1218 enum { nMedianTimeSpan=11 };
1220 int64 GetMedianTimePast() const
1222 int64 pmedian[nMedianTimeSpan];
1223 int64* pbegin = &pmedian[nMedianTimeSpan];
1224 int64* pend = &pmedian[nMedianTimeSpan];
1226 const CBlockIndex* pindex = this;
1227 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1228 *(--pbegin) = pindex->GetBlockTime();
1231 return pbegin[(pend - pbegin)/2];
1234 int64 GetMedianTime() const
1236 const CBlockIndex* pindex = this;
1237 for (int i = 0; i < nMedianTimeSpan/2; i++)
1240 return GetBlockTime();
1241 pindex = pindex->pnext;
1243 return pindex->GetMedianTimePast();
1248 string ToString() const
1250 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1251 pprev, pnext, nFile, nBlockPos, nHeight,
1252 hashMerkleRoot.ToString().substr(0,6).c_str(),
1253 GetBlockHash().ToString().substr(0,20).c_str());
1258 printf("%s\n", ToString().c_str());
1265 // Used to marshal pointers into hashes for db storage.
1267 class CDiskBlockIndex : public CBlockIndex
1279 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1281 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1282 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1287 if (!(nType & SER_GETHASH))
1288 READWRITE(nVersion);
1290 READWRITE(hashNext);
1292 READWRITE(nBlockPos);
1296 READWRITE(this->nVersion);
1297 READWRITE(hashPrev);
1298 READWRITE(hashMerkleRoot);
1304 uint256 GetBlockHash() const
1307 block.nVersion = nVersion;
1308 block.hashPrevBlock = hashPrev;
1309 block.hashMerkleRoot = hashMerkleRoot;
1310 block.nTime = nTime;
1311 block.nBits = nBits;
1312 block.nNonce = nNonce;
1313 return block.GetHash();
1317 string ToString() const
1319 string str = "CDiskBlockIndex(";
1320 str += CBlockIndex::ToString();
1321 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1322 GetBlockHash().ToString().c_str(),
1323 hashPrev.ToString().substr(0,20).c_str(),
1324 hashNext.ToString().substr(0,20).c_str());
1330 printf("%s\n", ToString().c_str());
1342 // Describes a place in the block chain to another node such that if the
1343 // other node doesn't have the same branch, it can find a recent common trunk.
1344 // The further back it is, the further before the fork it may be.
1349 vector<uint256> vHave;
1356 explicit CBlockLocator(const CBlockIndex* pindex)
1361 explicit CBlockLocator(uint256 hashBlock)
1363 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1364 if (mi != mapBlockIndex.end())
1370 if (!(nType & SER_GETHASH))
1371 READWRITE(nVersion);
1375 void Set(const CBlockIndex* pindex)
1381 vHave.push_back(pindex->GetBlockHash());
1383 // Exponentially larger steps back
1384 for (int i = 0; pindex && i < nStep; i++)
1385 pindex = pindex->pprev;
1386 if (vHave.size() > 10)
1389 vHave.push_back(hashGenesisBlock);
1392 int GetDistanceBack()
1394 // Retrace how far back it was in the sender's branch
1397 foreach(const uint256& hash, vHave)
1399 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1400 if (mi != mapBlockIndex.end())
1402 CBlockIndex* pindex = (*mi).second;
1403 if (pindex->IsInMainChain())
1413 CBlockIndex* GetBlockIndex()
1415 // Find the first block the caller has in the main chain
1416 foreach(const uint256& hash, vHave)
1418 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1419 if (mi != mapBlockIndex.end())
1421 CBlockIndex* pindex = (*mi).second;
1422 if (pindex->IsInMainChain())
1426 return pindexGenesisBlock;
1429 uint256 GetBlockHash()
1431 // Find the first block the caller has in the main chain
1432 foreach(const uint256& hash, vHave)
1434 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1435 if (mi != mapBlockIndex.end())
1437 CBlockIndex* pindex = (*mi).second;
1438 if (pindex->IsInMainChain())
1442 return hashGenesisBlock;
1447 CBlockIndex* pindex = GetBlockIndex();
1450 return pindex->nHeight;
1460 // Private key that includes an expiration date in case it never gets used.
1465 CPrivKey vchPrivKey;
1469 //// todo: add something to note what created it (user, getnewaddress, change)
1470 //// maybe should have a map<string, string> property map
1472 CWalletKey(int64 nTimeExpiresIn=0)
1474 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
1475 nTimeExpires = nTimeExpiresIn;
1480 if (!(nType & SER_GETHASH))
1481 READWRITE(nVersion);
1482 READWRITE(vchPrivKey);
1483 READWRITE(nTimeCreated);
1484 READWRITE(nTimeExpires);
1485 READWRITE(strComment);
1495 // Alert messages are broadcast as a vector of signed data. Unserializing may
1496 // not read the entire buffer if the alert is for a newer version, but older
1497 // versions can still relay the original data.
1499 class CUnsignedAlert
1503 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1508 int nMinVer; // lowest version inclusive
1509 int nMaxVer; // highest version inclusive
1510 set<string> setSubVer; // empty matches all
1515 string strStatusBar;
1520 READWRITE(this->nVersion);
1521 nVersion = this->nVersion;
1522 READWRITE(nRelayUntil);
1523 READWRITE(nExpiration);
1526 READWRITE(setCancel);
1529 READWRITE(setSubVer);
1530 READWRITE(nPriority);
1532 READWRITE(strComment);
1533 READWRITE(strStatusBar);
1534 READWRITE(strRPCError);
1551 strStatusBar.clear();
1552 strRPCError.clear();
1555 string ToString() const
1557 string strSetCancel;
1558 foreach(int n, setCancel)
1559 strSetCancel += strprintf("%d ", n);
1560 string strSetSubVer;
1561 foreach(string str, setSubVer)
1562 strSetSubVer += "\"" + str + "\" ";
1566 " nRelayUntil = %"PRI64d"\n"
1567 " nExpiration = %"PRI64d"\n"
1575 " strComment = \"%s\"\n"
1576 " strStatusBar = \"%s\"\n"
1577 " strRPCError = \"%s\"\n"
1584 strSetCancel.c_str(),
1587 strSetSubVer.c_str(),
1590 strStatusBar.c_str(),
1591 strRPCError.c_str());
1596 printf("%s", ToString().c_str());
1600 class CAlert : public CUnsignedAlert
1603 vector<unsigned char> vchMsg;
1604 vector<unsigned char> vchSig;
1619 CUnsignedAlert::SetNull();
1626 return (nExpiration == 0);
1629 uint256 GetHash() const
1631 return SerializeHash(*this);
1634 bool IsInEffect() const
1636 return (GetAdjustedTime() < nExpiration);
1639 bool Cancels(const CAlert& alert) const
1643 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1646 bool AppliesTo(int nVersion, string strSubVerIn) const
1648 return (IsInEffect() &&
1649 nMinVer <= nVersion && nVersion <= nMaxVer &&
1650 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1653 bool AppliesToMe() const
1655 return AppliesTo(VERSION, ::pszSubVer);
1658 bool RelayTo(CNode* pnode) const
1662 // returns true if wasn't already contained in the set
1663 if (pnode->setKnown.insert(GetHash()).second)
1665 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1667 GetAdjustedTime() < nRelayUntil)
1669 pnode->PushMessage("alert", *this);
1676 bool CheckSignature()
1679 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1680 return error("CAlert::CheckSignature() : SetPubKey failed");
1681 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1682 return error("CAlert::CheckSignature() : verify signature failed");
1684 // Now unserialize the data
1685 CDataStream sMsg(vchMsg);
1686 sMsg >> *(CUnsignedAlert*)this;
1690 bool ProcessAlert();
1702 extern map<uint256, CTransaction> mapTransactions;
1703 extern map<uint256, CWalletTx> mapWallet;
1704 extern vector<uint256> vWalletUpdated;
1705 extern CCriticalSection cs_mapWallet;
1706 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1707 extern map<uint160, vector<unsigned char> > mapPubKeys;
1708 extern CCriticalSection cs_mapKeys;
1709 extern CKey keyUser;