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 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(int64 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 IsInitialBlockDownload();
103 unsigned int nBlockPos;
111 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
114 nBlockPos = nBlockPosIn;
118 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
119 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
120 bool IsNull() const { return (nFile == -1); }
122 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
124 return (a.nFile == b.nFile &&
125 a.nBlockPos == b.nBlockPos &&
126 a.nTxPos == b.nTxPos);
129 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
134 string ToString() const
137 return strprintf("null");
139 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
144 printf("%s", ToString().c_str());
157 CInPoint() { SetNull(); }
158 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
159 void SetNull() { ptx = NULL; n = -1; }
160 bool IsNull() const { return (ptx == NULL && n == -1); }
172 COutPoint() { SetNull(); }
173 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
174 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
175 void SetNull() { hash = 0; n = -1; }
176 bool IsNull() const { return (hash == 0 && n == -1); }
178 friend bool operator<(const COutPoint& a, const COutPoint& b)
180 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
183 friend bool operator==(const COutPoint& a, const COutPoint& b)
185 return (a.hash == b.hash && a.n == b.n);
188 friend bool operator!=(const COutPoint& a, const COutPoint& b)
193 string ToString() const
195 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
200 printf("%s\n", ToString().c_str());
208 // An input of a transaction. It contains the location of the previous
209 // transaction's output that it claims and a signature that matches the
210 // output's public key.
217 unsigned int nSequence;
221 nSequence = UINT_MAX;
224 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
227 scriptSig = scriptSigIn;
228 nSequence = nSequenceIn;
231 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
233 prevout = COutPoint(hashPrevTx, nOut);
234 scriptSig = scriptSigIn;
235 nSequence = nSequenceIn;
241 READWRITE(scriptSig);
242 READWRITE(nSequence);
247 return (nSequence == UINT_MAX);
250 friend bool operator==(const CTxIn& a, const CTxIn& b)
252 return (a.prevout == b.prevout &&
253 a.scriptSig == b.scriptSig &&
254 a.nSequence == b.nSequence);
257 friend bool operator!=(const CTxIn& a, const CTxIn& b)
262 string ToString() const
265 str += strprintf("CTxIn(");
266 str += prevout.ToString();
267 if (prevout.IsNull())
268 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
270 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
271 if (nSequence != UINT_MAX)
272 str += strprintf(", nSequence=%u", nSequence);
279 printf("%s\n", ToString().c_str());
283 int64 GetDebit() const;
290 // An output of a transaction. It contains the public key that the next input
291 // must be able to sign with to claim it.
297 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
345 friend bool operator==(const CTxOut& a, const CTxOut& b)
347 return (a.nValue == b.nValue &&
348 a.scriptPubKey == b.scriptPubKey);
351 friend bool operator!=(const CTxOut& a, const CTxOut& b)
356 string ToString() const
358 if (scriptPubKey.size() < 6)
359 return "CTxOut(error)";
360 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
365 printf("%s\n", ToString().c_str());
373 // The basic transaction that is broadcasted on the network and contained in
374 // blocks. A transaction can contain multiple inputs and outputs.
382 unsigned int nLockTime;
392 READWRITE(this->nVersion);
393 nVersion = this->nVersion;
396 READWRITE(nLockTime);
409 return (vin.empty() && vout.empty());
412 uint256 GetHash() const
414 return SerializeHash(*this);
417 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
419 // Time based nLockTime implemented in 0.1.6
422 if (nBlockHeight == 0)
423 nBlockHeight = nBestHeight;
425 nBlockTime = GetAdjustedTime();
426 if (nLockTime < (nLockTime < 500000000 ? nBlockHeight : nBlockTime))
428 foreach(const CTxIn& txin, vin)
434 bool IsNewerThan(const CTransaction& old) const
436 if (vin.size() != old.vin.size())
438 for (int i = 0; i < vin.size(); i++)
439 if (vin[i].prevout != old.vin[i].prevout)
443 unsigned int nLowest = UINT_MAX;
444 for (int i = 0; i < vin.size(); i++)
446 if (vin[i].nSequence != old.vin[i].nSequence)
448 if (vin[i].nSequence <= nLowest)
451 nLowest = vin[i].nSequence;
453 if (old.vin[i].nSequence < nLowest)
456 nLowest = old.vin[i].nSequence;
463 bool IsCoinBase() const
465 return (vin.size() == 1 && vin[0].prevout.IsNull());
468 bool CheckTransaction() const
470 // Basic checks that don't depend on any context
471 if (vin.empty() || vout.empty())
472 return error("CTransaction::CheckTransaction() : vin or vout empty");
474 // Check for negative values
475 foreach(const CTxOut& txout, vout)
476 if (txout.nValue < 0)
477 return error("CTransaction::CheckTransaction() : txout.nValue negative");
481 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
482 return error("CTransaction::CheckTransaction() : coinbase script size");
486 foreach(const CTxIn& txin, vin)
487 if (txin.prevout.IsNull())
488 return error("CTransaction::CheckTransaction() : prevout is null");
496 foreach(const CTxOut& txout, vout)
502 int64 GetDebit() const
505 foreach(const CTxIn& txin, vin)
506 nDebit += txin.GetDebit();
510 int64 GetCredit() const
513 foreach(const CTxOut& txout, vout)
514 nCredit += txout.GetCredit();
518 int64 GetValueOut() const
521 foreach(const CTxOut& txout, vout)
523 if (txout.nValue < 0)
524 throw runtime_error("CTransaction::GetValueOut() : negative value");
525 nValueOut += txout.nValue;
530 int64 GetMinFee(unsigned int nBlockSize=1) const
532 // Base fee is 1 cent per kilobyte
533 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
534 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
536 // Transactions under 60K are free as long as block size is under 80K
537 // (about 27,000bc if made of 50bc inputs)
538 if (nBytes < 60000 && nBlockSize < 80000)
541 // Transactions under 3K are free as long as block size is under 200K
542 if (nBytes < 3000 && nBlockSize < 200000)
545 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
547 foreach(const CTxOut& txout, vout)
548 if (txout.nValue < CENT)
556 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
558 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
560 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
563 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
564 return error("CTransaction::ReadFromDisk() : fseek failed");
567 // Return file pointer
570 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
571 return error("CTransaction::ReadFromDisk() : second fseek failed");
572 *pfileRet = filein.release();
578 friend bool operator==(const CTransaction& a, const CTransaction& b)
580 return (a.nVersion == b.nVersion &&
583 a.nLockTime == b.nLockTime);
586 friend bool operator!=(const CTransaction& a, const CTransaction& b)
592 string ToString() const
595 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
596 GetHash().ToString().substr(0,6).c_str(),
601 for (int i = 0; i < vin.size(); i++)
602 str += " " + vin[i].ToString() + "\n";
603 for (int i = 0; i < vout.size(); i++)
604 str += " " + vout[i].ToString() + "\n";
610 printf("%s", ToString().c_str());
615 bool DisconnectInputs(CTxDB& txdb);
616 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
617 bool ClientConnectInputs();
619 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
621 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
624 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
628 bool AddToMemoryPool();
630 bool RemoveFromMemoryPool();
638 // A transaction with a merkle branch linking it to the block chain
640 class CMerkleTx : public CTransaction
644 vector<uint256> vMerkleBranch;
648 mutable bool fMerkleVerified;
649 mutable bool fGetCreditCached;
650 mutable int64 nGetCreditCached;
658 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
667 fMerkleVerified = false;
668 fGetCreditCached = false;
669 nGetCreditCached = 0;
674 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
675 nVersion = this->nVersion;
676 READWRITE(hashBlock);
677 READWRITE(vMerkleBranch);
681 int64 GetCredit(bool fUseCache=false) const
683 // Must wait until coinbase is safely deep enough in the chain before valuing it
684 if (IsCoinBase() && GetBlocksToMaturity() > 0)
687 // GetBalance can assume transactions in mapWallet won't change
688 if (fUseCache && fGetCreditCached)
689 return nGetCreditCached;
690 nGetCreditCached = CTransaction::GetCredit();
691 fGetCreditCached = true;
692 return nGetCreditCached;
696 int SetMerkleBranch(const CBlock* pblock=NULL);
697 int GetDepthInMainChain(int& nHeightRet) const;
698 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
699 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
700 int GetBlocksToMaturity() const;
701 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
702 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
709 // A transaction with a bunch of additional info that only the owner cares
710 // about. It includes any unrecorded transactions needed to link it back
711 // to the block chain.
713 class CWalletTx : public CMerkleTx
716 vector<CMerkleTx> vtxPrev;
717 map<string, string> mapValue;
718 vector<pair<string, string> > vOrderForm;
719 unsigned int fTimeReceivedIsTxTime;
720 unsigned int nTimeReceived; // time received by this node
723 //// probably need to sign the order info so know it came from payer
725 // memory only UI hints
726 mutable unsigned int nTimeDisplayed;
727 mutable int nLinesDisplayed;
735 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
740 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
747 fTimeReceivedIsTxTime = false;
757 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
758 nVersion = this->nVersion;
761 READWRITE(vOrderForm);
762 READWRITE(fTimeReceivedIsTxTime);
763 READWRITE(nTimeReceived);
770 return CWalletDB().WriteTx(GetHash(), *this);
774 int64 GetTxTime() const;
775 int GetRequestCount() const;
777 void AddSupportingTransactions(CTxDB& txdb);
779 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
780 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
782 void RelayWalletTransaction(CTxDB& txdb);
783 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
790 // A txdb record that contains the disk location of a transaction and the
791 // locations of transactions that spend its outputs. vSpent is really only
792 // used as a flag, but having the location is very helpful for debugging.
798 vector<CDiskTxPos> vSpent;
805 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
808 vSpent.resize(nOutputs);
813 if (!(nType & SER_GETHASH))
830 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
832 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
834 for (int i = 0; i < a.vSpent.size(); i++)
835 if (a.vSpent[i] != b.vSpent[i])
840 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
851 // Nodes collect new transactions into a block, hash them into a hash tree,
852 // and scan through nonce values to make the block's hash satisfy proof-of-work
853 // requirements. When they solve the proof-of-work, they broadcast the block
854 // to everyone and the block is added to the block chain. The first transaction
855 // in the block is a special one that creates a new coin owned by the creator
858 // Blocks are appended to blk0001.dat files on disk. Their location on disk
859 // is indexed by CBlockIndex objects in memory.
866 uint256 hashPrevBlock;
867 uint256 hashMerkleRoot;
873 vector<CTransaction> vtx;
876 mutable vector<uint256> vMerkleTree;
886 READWRITE(this->nVersion);
887 nVersion = this->nVersion;
888 READWRITE(hashPrevBlock);
889 READWRITE(hashMerkleRoot);
894 // ConnectBlock depends on vtx being last so it can calculate offset
895 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
898 const_cast<CBlock*>(this)->vtx.clear();
918 uint256 GetHash() const
920 return Hash(BEGIN(nVersion), END(nNonce));
924 uint256 BuildMerkleTree() const
927 foreach(const CTransaction& tx, vtx)
928 vMerkleTree.push_back(tx.GetHash());
930 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
932 for (int i = 0; i < nSize; i += 2)
934 int i2 = min(i+1, nSize-1);
935 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
936 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
940 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
943 vector<uint256> GetMerkleBranch(int nIndex) const
945 if (vMerkleTree.empty())
947 vector<uint256> vMerkleBranch;
949 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
951 int i = min(nIndex^1, nSize-1);
952 vMerkleBranch.push_back(vMerkleTree[j+i]);
956 return vMerkleBranch;
959 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
963 foreach(const uint256& otherside, vMerkleBranch)
966 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
968 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
975 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
977 // Open history file to append
978 CAutoFile fileout = AppendBlockFile(nFileRet);
980 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
981 if (!fWriteTransactions)
982 fileout.nType |= SER_BLOCKHEADERONLY;
984 // Write index header
985 unsigned int nSize = fileout.GetSerializeSize(*this);
986 fileout << FLATDATA(pchMessageStart) << nSize;
989 nBlockPosRet = ftell(fileout);
990 if (nBlockPosRet == -1)
991 return error("CBlock::WriteToDisk() : ftell failed");
994 // Flush stdio buffers and commit to disk before returning
996 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
999 _commit(_fileno(fileout));
1001 fsync(fileno(fileout));
1008 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1012 // Open history file to read
1013 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1015 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1016 if (!fReadTransactions)
1017 filein.nType |= SER_BLOCKHEADERONLY;
1023 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
1024 return error("CBlock::ReadFromDisk() : nBits errors in block header");
1025 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
1026 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
1035 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1036 GetHash().ToString().substr(0,16).c_str(),
1038 hashPrevBlock.ToString().substr(0,16).c_str(),
1039 hashMerkleRoot.ToString().substr(0,6).c_str(),
1040 nTime, nBits, nNonce,
1042 for (int i = 0; i < vtx.size(); i++)
1047 printf(" vMerkleTree: ");
1048 for (int i = 0; i < vMerkleTree.size(); i++)
1049 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
1054 int64 GetBlockValue(int nHeight, int64 nFees) const;
1055 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1056 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1057 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);
1058 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1059 bool CheckBlock() const;
1069 // The block chain is a tree shaped structure starting with the
1070 // genesis block at the root, with each block potentially having multiple
1071 // candidates to be the next block. pprev and pnext link a path through the
1072 // main/longest chain. A blockindex may have multiple pprev pointing back
1073 // to it, but pnext will only point forward to the longest branch, or will
1074 // be null if the block is not part of the longest chain.
1079 const uint256* phashBlock;
1083 unsigned int nBlockPos;
1085 CBigNum bnChainWork;
1089 uint256 hashMerkleRoot;
1092 unsigned int nNonce;
1112 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1118 nBlockPos = nBlockPosIn;
1122 nVersion = block.nVersion;
1123 hashMerkleRoot = block.hashMerkleRoot;
1124 nTime = block.nTime;
1125 nBits = block.nBits;
1126 nNonce = block.nNonce;
1129 uint256 GetBlockHash() const
1134 CBigNum GetBlockWork() const
1136 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);
1139 bool IsInMainChain() const
1141 return (pnext || this == pindexBest);
1144 bool EraseBlockFromDisk()
1146 // Open history file
1147 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1151 // Overwrite with empty null block
1159 enum { nMedianTimeSpan=11 };
1161 int64 GetMedianTimePast() const
1163 unsigned int pmedian[nMedianTimeSpan];
1164 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
1165 unsigned int* pend = &pmedian[nMedianTimeSpan];
1167 const CBlockIndex* pindex = this;
1168 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1169 *(--pbegin) = pindex->nTime;
1172 return pbegin[(pend - pbegin)/2];
1175 int64 GetMedianTime() const
1177 const CBlockIndex* pindex = this;
1178 for (int i = 0; i < nMedianTimeSpan/2; i++)
1182 pindex = pindex->pnext;
1184 return pindex->GetMedianTimePast();
1189 string ToString() const
1191 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1192 pprev, pnext, nFile, nBlockPos, nHeight,
1193 hashMerkleRoot.ToString().substr(0,6).c_str(),
1194 GetBlockHash().ToString().substr(0,16).c_str());
1199 printf("%s\n", ToString().c_str());
1206 // Used to marshal pointers into hashes for db storage.
1208 class CDiskBlockIndex : public CBlockIndex
1220 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1222 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1223 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1228 if (!(nType & SER_GETHASH))
1229 READWRITE(nVersion);
1231 READWRITE(hashNext);
1233 READWRITE(nBlockPos);
1237 READWRITE(this->nVersion);
1238 READWRITE(hashPrev);
1239 READWRITE(hashMerkleRoot);
1245 uint256 GetBlockHash() const
1248 block.nVersion = nVersion;
1249 block.hashPrevBlock = hashPrev;
1250 block.hashMerkleRoot = hashMerkleRoot;
1251 block.nTime = nTime;
1252 block.nBits = nBits;
1253 block.nNonce = nNonce;
1254 return block.GetHash();
1258 string ToString() const
1260 string str = "CDiskBlockIndex(";
1261 str += CBlockIndex::ToString();
1262 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1263 GetBlockHash().ToString().c_str(),
1264 hashPrev.ToString().substr(0,16).c_str(),
1265 hashNext.ToString().substr(0,16).c_str());
1271 printf("%s\n", ToString().c_str());
1283 // Describes a place in the block chain to another node such that if the
1284 // other node doesn't have the same branch, it can find a recent common trunk.
1285 // The further back it is, the further before the fork it may be.
1290 vector<uint256> vHave;
1297 explicit CBlockLocator(const CBlockIndex* pindex)
1302 explicit CBlockLocator(uint256 hashBlock)
1304 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1305 if (mi != mapBlockIndex.end())
1311 if (!(nType & SER_GETHASH))
1312 READWRITE(nVersion);
1316 void Set(const CBlockIndex* pindex)
1322 vHave.push_back(pindex->GetBlockHash());
1324 // Exponentially larger steps back
1325 for (int i = 0; pindex && i < nStep; i++)
1326 pindex = pindex->pprev;
1327 if (vHave.size() > 10)
1330 vHave.push_back(hashGenesisBlock);
1333 int GetDistanceBack()
1335 // Retrace how far back it was in the sender's branch
1338 foreach(const uint256& hash, vHave)
1340 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1341 if (mi != mapBlockIndex.end())
1343 CBlockIndex* pindex = (*mi).second;
1344 if (pindex->IsInMainChain())
1354 CBlockIndex* GetBlockIndex()
1356 // Find the first block the caller has in the main chain
1357 foreach(const uint256& hash, vHave)
1359 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1360 if (mi != mapBlockIndex.end())
1362 CBlockIndex* pindex = (*mi).second;
1363 if (pindex->IsInMainChain())
1367 return pindexGenesisBlock;
1370 uint256 GetBlockHash()
1372 // Find the first block the caller has in the main chain
1373 foreach(const uint256& hash, vHave)
1375 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1376 if (mi != mapBlockIndex.end())
1378 CBlockIndex* pindex = (*mi).second;
1379 if (pindex->IsInMainChain())
1383 return hashGenesisBlock;
1388 CBlockIndex* pindex = GetBlockIndex();
1391 return pindex->nHeight;
1401 // Private key that includes an expiration date in case it never gets used.
1406 CPrivKey vchPrivKey;
1410 //// todo: add something to note what created it (user, getnewaddress, change)
1411 //// maybe should have a map<string, string> property map
1413 CWalletKey(int64 nTimeExpiresIn=0)
1415 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
1416 nTimeExpires = nTimeExpiresIn;
1421 if (!(nType & SER_GETHASH))
1422 READWRITE(nVersion);
1423 READWRITE(vchPrivKey);
1424 READWRITE(nTimeCreated);
1425 READWRITE(nTimeExpires);
1426 READWRITE(strComment);
1435 extern map<uint256, CTransaction> mapTransactions;
1436 extern map<uint256, CWalletTx> mapWallet;
1437 extern vector<uint256> vWalletUpdated;
1438 extern CCriticalSection cs_mapWallet;
1439 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1440 extern map<uint160, vector<unsigned char> > mapPubKeys;
1441 extern CCriticalSection cs_mapKeys;
1442 extern CKey keyUser;