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_SIZE = 0x02000000;
18 static const unsigned int MAX_BLOCK_SIZE = 1000000;
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(int64 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();
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.begin(), scriptSig.end(), false).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;
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");
478 // Check for negative or overflow output values
480 foreach(const CTxOut& txout, vout)
482 if (txout.nValue < 0)
483 return error("CTransaction::CheckTransaction() : txout.nValue negative");
484 if (txout.nValue > MAX_MONEY)
485 return error("CTransaction::CheckTransaction() : txout.nValue too high");
486 nValueOut += txout.nValue;
487 if (!MoneyRange(nValueOut))
488 return error("CTransaction::CheckTransaction() : txout total out of range");
493 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
494 return error("CTransaction::CheckTransaction() : coinbase script size");
498 foreach(const CTxIn& txin, vin)
499 if (txin.prevout.IsNull())
500 return error("CTransaction::CheckTransaction() : prevout is null");
508 foreach(const CTxOut& txout, vout)
514 int64 GetDebit() const
517 foreach(const CTxIn& txin, vin)
519 nDebit += txin.GetDebit();
520 if (!MoneyRange(nDebit))
521 throw runtime_error("CTransaction::GetDebit() : value out of range");
526 int64 GetCredit() const
529 foreach(const CTxOut& txout, vout)
531 nCredit += txout.GetCredit();
532 if (!MoneyRange(nCredit))
533 throw runtime_error("CTransaction::GetCredit() : value out of range");
538 int64 GetValueOut() const
541 foreach(const CTxOut& txout, vout)
543 nValueOut += txout.nValue;
544 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
545 throw runtime_error("CTransaction::GetValueOut() : value out of range");
550 int64 GetMinFee(unsigned int nBlockSize=1) const
552 // Base fee is 1 cent per kilobyte
553 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
554 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
556 // Transactions under 60K are free as long as block size is under 80K
557 // (about 27,000bc if made of 50bc inputs)
558 if (nBytes < 60000 && nBlockSize < 80000)
561 // Transactions under 3K are free as long as block size is under 200K
562 if (nBytes < 3000 && nBlockSize < 200000)
565 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
567 foreach(const CTxOut& txout, vout)
568 if (txout.nValue < CENT)
576 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
578 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
580 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
583 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
584 return error("CTransaction::ReadFromDisk() : fseek failed");
587 // Return file pointer
590 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
591 return error("CTransaction::ReadFromDisk() : second fseek failed");
592 *pfileRet = filein.release();
598 friend bool operator==(const CTransaction& a, const CTransaction& b)
600 return (a.nVersion == b.nVersion &&
603 a.nLockTime == b.nLockTime);
606 friend bool operator!=(const CTransaction& a, const CTransaction& b)
612 string ToString() const
615 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
616 GetHash().ToString().substr(0,6).c_str(),
621 for (int i = 0; i < vin.size(); i++)
622 str += " " + vin[i].ToString() + "\n";
623 for (int i = 0; i < vout.size(); i++)
624 str += " " + vout[i].ToString() + "\n";
630 printf("%s", ToString().c_str());
635 bool DisconnectInputs(CTxDB& txdb);
636 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
637 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
638 bool ClientConnectInputs();
640 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
642 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
645 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
649 bool AddToMemoryPool();
651 bool RemoveFromMemoryPool();
659 // A transaction with a merkle branch linking it to the block chain
661 class CMerkleTx : public CTransaction
665 vector<uint256> vMerkleBranch;
669 mutable bool fMerkleVerified;
670 mutable bool fGetCreditCached;
671 mutable int64 nGetCreditCached;
679 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
688 fMerkleVerified = false;
689 fGetCreditCached = false;
690 nGetCreditCached = 0;
695 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
696 nVersion = this->nVersion;
697 READWRITE(hashBlock);
698 READWRITE(vMerkleBranch);
702 int64 GetCredit(bool fUseCache=false) const
704 // Must wait until coinbase is safely deep enough in the chain before valuing it
705 if (IsCoinBase() && GetBlocksToMaturity() > 0)
708 // GetBalance can assume transactions in mapWallet won't change
709 if (fUseCache && fGetCreditCached)
710 return nGetCreditCached;
711 nGetCreditCached = CTransaction::GetCredit();
712 fGetCreditCached = true;
713 return nGetCreditCached;
717 int SetMerkleBranch(const CBlock* pblock=NULL);
718 int GetDepthInMainChain(int& nHeightRet) const;
719 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
720 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
721 int GetBlocksToMaturity() const;
722 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
723 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
730 // A transaction with a bunch of additional info that only the owner cares
731 // about. It includes any unrecorded transactions needed to link it back
732 // to the block chain.
734 class CWalletTx : public CMerkleTx
737 vector<CMerkleTx> vtxPrev;
738 map<string, string> mapValue;
739 vector<pair<string, string> > vOrderForm;
740 unsigned int fTimeReceivedIsTxTime;
741 unsigned int nTimeReceived; // time received by this node
744 //// probably need to sign the order info so know it came from payer
746 // memory only UI hints
747 mutable unsigned int nTimeDisplayed;
748 mutable int nLinesDisplayed;
756 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
761 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
768 fTimeReceivedIsTxTime = false;
778 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
779 nVersion = this->nVersion;
782 READWRITE(vOrderForm);
783 READWRITE(fTimeReceivedIsTxTime);
784 READWRITE(nTimeReceived);
791 return CWalletDB().WriteTx(GetHash(), *this);
795 int64 GetTxTime() const;
796 int GetRequestCount() const;
798 void AddSupportingTransactions(CTxDB& txdb);
800 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
801 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
803 void RelayWalletTransaction(CTxDB& txdb);
804 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
811 // A txdb record that contains the disk location of a transaction and the
812 // locations of transactions that spend its outputs. vSpent is really only
813 // used as a flag, but having the location is very helpful for debugging.
819 vector<CDiskTxPos> vSpent;
826 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
829 vSpent.resize(nOutputs);
834 if (!(nType & SER_GETHASH))
851 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
853 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
855 for (int i = 0; i < a.vSpent.size(); i++)
856 if (a.vSpent[i] != b.vSpent[i])
861 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
872 // Nodes collect new transactions into a block, hash them into a hash tree,
873 // and scan through nonce values to make the block's hash satisfy proof-of-work
874 // requirements. When they solve the proof-of-work, they broadcast the block
875 // to everyone and the block is added to the block chain. The first transaction
876 // in the block is a special one that creates a new coin owned by the creator
879 // Blocks are appended to blk0001.dat files on disk. Their location on disk
880 // is indexed by CBlockIndex objects in memory.
887 uint256 hashPrevBlock;
888 uint256 hashMerkleRoot;
894 vector<CTransaction> vtx;
897 mutable vector<uint256> vMerkleTree;
907 READWRITE(this->nVersion);
908 nVersion = this->nVersion;
909 READWRITE(hashPrevBlock);
910 READWRITE(hashMerkleRoot);
915 // ConnectBlock depends on vtx being last so it can calculate offset
916 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
919 const_cast<CBlock*>(this)->vtx.clear();
939 uint256 GetHash() const
941 return Hash(BEGIN(nVersion), END(nNonce));
944 int64 GetBlockTime() const
950 uint256 BuildMerkleTree() const
953 foreach(const CTransaction& tx, vtx)
954 vMerkleTree.push_back(tx.GetHash());
956 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
958 for (int i = 0; i < nSize; i += 2)
960 int i2 = min(i+1, nSize-1);
961 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
962 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
966 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
969 vector<uint256> GetMerkleBranch(int nIndex) const
971 if (vMerkleTree.empty())
973 vector<uint256> vMerkleBranch;
975 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
977 int i = min(nIndex^1, nSize-1);
978 vMerkleBranch.push_back(vMerkleTree[j+i]);
982 return vMerkleBranch;
985 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
989 foreach(const uint256& otherside, vMerkleBranch)
992 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
994 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1001 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1003 // Open history file to append
1004 CAutoFile fileout = AppendBlockFile(nFileRet);
1006 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1007 if (!fWriteTransactions)
1008 fileout.nType |= SER_BLOCKHEADERONLY;
1010 // Write index header
1011 unsigned int nSize = fileout.GetSerializeSize(*this);
1012 fileout << FLATDATA(pchMessageStart) << nSize;
1015 nBlockPosRet = ftell(fileout);
1016 if (nBlockPosRet == -1)
1017 return error("CBlock::WriteToDisk() : ftell failed");
1020 // Flush stdio buffers and commit to disk before returning
1022 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1025 _commit(_fileno(fileout));
1027 fsync(fileno(fileout));
1034 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1038 // Open history file to read
1039 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1041 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1042 if (!fReadTransactions)
1043 filein.nType |= SER_BLOCKHEADERONLY;
1049 if (!CheckProofOfWork(GetHash(), nBits))
1050 return error("CBlock::ReadFromDisk() : errors in block header");
1059 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1060 GetHash().ToString().substr(0,20).c_str(),
1062 hashPrevBlock.ToString().substr(0,20).c_str(),
1063 hashMerkleRoot.ToString().substr(0,6).c_str(),
1064 nTime, nBits, nNonce,
1066 for (int i = 0; i < vtx.size(); i++)
1071 printf(" vMerkleTree: ");
1072 for (int i = 0; i < vMerkleTree.size(); i++)
1073 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
1078 int64 GetBlockValue(int nHeight, int64 nFees) const;
1079 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1080 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1081 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1082 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1083 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1084 bool CheckBlock() const;
1094 // The block chain is a tree shaped structure starting with the
1095 // genesis block at the root, with each block potentially having multiple
1096 // candidates to be the next block. pprev and pnext link a path through the
1097 // main/longest chain. A blockindex may have multiple pprev pointing back
1098 // to it, but pnext will only point forward to the longest branch, or will
1099 // be null if the block is not part of the longest chain.
1104 const uint256* phashBlock;
1108 unsigned int nBlockPos;
1110 CBigNum bnChainWork;
1114 uint256 hashMerkleRoot;
1117 unsigned int nNonce;
1137 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1143 nBlockPos = nBlockPosIn;
1147 nVersion = block.nVersion;
1148 hashMerkleRoot = block.hashMerkleRoot;
1149 nTime = block.nTime;
1150 nBits = block.nBits;
1151 nNonce = block.nNonce;
1154 uint256 GetBlockHash() const
1159 int64 GetBlockTime() const
1161 return (int64)nTime;
1164 CBigNum GetBlockWork() const
1166 if (CBigNum().SetCompact(nBits) <= 0)
1168 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);
1171 bool IsInMainChain() const
1173 return (pnext || this == pindexBest);
1176 bool CheckIndex() const
1178 return CheckProofOfWork(GetBlockHash(), nBits);
1181 bool EraseBlockFromDisk()
1183 // Open history file
1184 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1188 // Overwrite with empty null block
1196 enum { nMedianTimeSpan=11 };
1198 int64 GetMedianTimePast() const
1200 int64 pmedian[nMedianTimeSpan];
1201 int64* pbegin = &pmedian[nMedianTimeSpan];
1202 int64* pend = &pmedian[nMedianTimeSpan];
1204 const CBlockIndex* pindex = this;
1205 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1206 *(--pbegin) = pindex->GetBlockTime();
1209 return pbegin[(pend - pbegin)/2];
1212 int64 GetMedianTime() const
1214 const CBlockIndex* pindex = this;
1215 for (int i = 0; i < nMedianTimeSpan/2; i++)
1218 return GetBlockTime();
1219 pindex = pindex->pnext;
1221 return pindex->GetMedianTimePast();
1226 string ToString() const
1228 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1229 pprev, pnext, nFile, nBlockPos, nHeight,
1230 hashMerkleRoot.ToString().substr(0,6).c_str(),
1231 GetBlockHash().ToString().substr(0,20).c_str());
1236 printf("%s\n", ToString().c_str());
1243 // Used to marshal pointers into hashes for db storage.
1245 class CDiskBlockIndex : public CBlockIndex
1257 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1259 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1260 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1265 if (!(nType & SER_GETHASH))
1266 READWRITE(nVersion);
1268 READWRITE(hashNext);
1270 READWRITE(nBlockPos);
1274 READWRITE(this->nVersion);
1275 READWRITE(hashPrev);
1276 READWRITE(hashMerkleRoot);
1282 uint256 GetBlockHash() const
1285 block.nVersion = nVersion;
1286 block.hashPrevBlock = hashPrev;
1287 block.hashMerkleRoot = hashMerkleRoot;
1288 block.nTime = nTime;
1289 block.nBits = nBits;
1290 block.nNonce = nNonce;
1291 return block.GetHash();
1295 string ToString() const
1297 string str = "CDiskBlockIndex(";
1298 str += CBlockIndex::ToString();
1299 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1300 GetBlockHash().ToString().c_str(),
1301 hashPrev.ToString().substr(0,20).c_str(),
1302 hashNext.ToString().substr(0,20).c_str());
1308 printf("%s\n", ToString().c_str());
1320 // Describes a place in the block chain to another node such that if the
1321 // other node doesn't have the same branch, it can find a recent common trunk.
1322 // The further back it is, the further before the fork it may be.
1327 vector<uint256> vHave;
1334 explicit CBlockLocator(const CBlockIndex* pindex)
1339 explicit CBlockLocator(uint256 hashBlock)
1341 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1342 if (mi != mapBlockIndex.end())
1348 if (!(nType & SER_GETHASH))
1349 READWRITE(nVersion);
1353 void Set(const CBlockIndex* pindex)
1359 vHave.push_back(pindex->GetBlockHash());
1361 // Exponentially larger steps back
1362 for (int i = 0; pindex && i < nStep; i++)
1363 pindex = pindex->pprev;
1364 if (vHave.size() > 10)
1367 vHave.push_back(hashGenesisBlock);
1370 int GetDistanceBack()
1372 // Retrace how far back it was in the sender's branch
1375 foreach(const uint256& hash, vHave)
1377 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1378 if (mi != mapBlockIndex.end())
1380 CBlockIndex* pindex = (*mi).second;
1381 if (pindex->IsInMainChain())
1391 CBlockIndex* GetBlockIndex()
1393 // Find the first block the caller has in the main chain
1394 foreach(const uint256& hash, vHave)
1396 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1397 if (mi != mapBlockIndex.end())
1399 CBlockIndex* pindex = (*mi).second;
1400 if (pindex->IsInMainChain())
1404 return pindexGenesisBlock;
1407 uint256 GetBlockHash()
1409 // Find the first block the caller has in the main chain
1410 foreach(const uint256& hash, vHave)
1412 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1413 if (mi != mapBlockIndex.end())
1415 CBlockIndex* pindex = (*mi).second;
1416 if (pindex->IsInMainChain())
1420 return hashGenesisBlock;
1425 CBlockIndex* pindex = GetBlockIndex();
1428 return pindex->nHeight;
1438 // Private key that includes an expiration date in case it never gets used.
1443 CPrivKey vchPrivKey;
1447 //// todo: add something to note what created it (user, getnewaddress, change)
1448 //// maybe should have a map<string, string> property map
1450 CWalletKey(int64 nTimeExpiresIn=0)
1452 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
1453 nTimeExpires = nTimeExpiresIn;
1458 if (!(nType & SER_GETHASH))
1459 READWRITE(nVersion);
1460 READWRITE(vchPrivKey);
1461 READWRITE(nTimeCreated);
1462 READWRITE(nTimeExpires);
1463 READWRITE(strComment);
1472 extern map<uint256, CTransaction> mapTransactions;
1473 extern map<uint256, CWalletTx> mapWallet;
1474 extern vector<uint256> vWalletUpdated;
1475 extern CCriticalSection cs_mapWallet;
1476 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1477 extern map<uint160, vector<unsigned char> > mapPubKeys;
1478 extern CCriticalSection cs_mapKeys;
1479 extern CKey keyUser;