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;
31 extern CCriticalSection cs_main;
32 extern map<uint256, CBlockIndex*> mapBlockIndex;
33 extern uint256 hashGenesisBlock;
34 extern CBigNum bnProofOfWorkLimit;
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, CReserveKey& reservekey, int64& nFeeRequiredRet);
80 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
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,10).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,30).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 int GetSigOpCount() const
475 foreach(const CTxIn& txin, vin)
476 n += txin.scriptSig.GetSigOpCount();
477 foreach(const CTxOut& txout, vout)
478 n += txout.scriptPubKey.GetSigOpCount();
484 foreach(const CTxOut& txout, vout)
490 int64 GetDebit() const
493 foreach(const CTxIn& txin, vin)
495 nDebit += txin.GetDebit();
496 if (!MoneyRange(nDebit))
497 throw runtime_error("CTransaction::GetDebit() : value out of range");
502 int64 GetCredit() const
505 foreach(const CTxOut& txout, vout)
507 nCredit += txout.GetCredit();
508 if (!MoneyRange(nCredit))
509 throw runtime_error("CTransaction::GetCredit() : value out of range");
514 int64 GetValueOut() const
517 foreach(const CTxOut& txout, vout)
519 nValueOut += txout.nValue;
520 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
521 throw runtime_error("CTransaction::GetValueOut() : value out of range");
526 int64 GetMinFee(unsigned int nBlockSize=1) const
528 // Base fee is 1 cent per kilobyte
529 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
530 unsigned int nNewBlockSize = nBlockSize + nBytes;
531 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
533 // Transactions under 25K are free as long as block size is under 40K
534 // (about 11,000bc if made of 50bc inputs)
535 if (nBytes < 25000 && nNewBlockSize < 40000)
538 // Transactions under 3K are free as long as block size is under 50K
539 if (nBytes < 3000 && nNewBlockSize < 50000)
542 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
544 foreach(const CTxOut& txout, vout)
545 if (txout.nValue < CENT)
548 // Raise the price as the block approaches full
549 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
551 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
553 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
556 if (!MoneyRange(nMinFee))
562 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
564 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
566 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
569 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
570 return error("CTransaction::ReadFromDisk() : fseek failed");
573 // Return file pointer
576 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
577 return error("CTransaction::ReadFromDisk() : second fseek failed");
578 *pfileRet = filein.release();
584 friend bool operator==(const CTransaction& a, const CTransaction& b)
586 return (a.nVersion == b.nVersion &&
589 a.nLockTime == b.nLockTime);
592 friend bool operator!=(const CTransaction& a, const CTransaction& b)
598 string ToString() const
601 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
602 GetHash().ToString().substr(0,10).c_str(),
607 for (int i = 0; i < vin.size(); i++)
608 str += " " + vin[i].ToString() + "\n";
609 for (int i = 0; i < vout.size(); i++)
610 str += " " + vout[i].ToString() + "\n";
616 printf("%s", ToString().c_str());
620 bool DisconnectInputs(CTxDB& txdb);
621 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
622 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
623 bool ClientConnectInputs();
624 bool CheckTransaction() const;
625 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
626 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
629 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
632 bool AddToMemoryPoolUnchecked();
634 bool RemoveFromMemoryPool();
642 // A transaction with a merkle branch linking it to the block chain
644 class CMerkleTx : public CTransaction
648 vector<uint256> vMerkleBranch;
652 mutable char fMerkleVerified;
660 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
669 fMerkleVerified = false;
674 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
675 nVersion = this->nVersion;
676 READWRITE(hashBlock);
677 READWRITE(vMerkleBranch);
682 int SetMerkleBranch(const CBlock* pblock=NULL);
683 int GetDepthInMainChain(int& nHeightRet) const;
684 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
685 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
686 int GetBlocksToMaturity() const;
687 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
688 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
695 // A transaction with a bunch of additional info that only the owner cares
696 // about. It includes any unrecorded transactions needed to link it back
697 // to the block chain.
699 class CWalletTx : public CMerkleTx
702 vector<CMerkleTx> vtxPrev;
703 map<string, string> mapValue;
704 vector<pair<string, string> > vOrderForm;
705 unsigned int fTimeReceivedIsTxTime;
706 unsigned int nTimeReceived; // time received by this node
709 //// probably need to sign the order info so know it came from payer
712 mutable char fDebitCached;
713 mutable char fCreditCached;
714 mutable int64 nDebitCached;
715 mutable int64 nCreditCached;
717 // memory only UI hints
718 mutable unsigned int nTimeDisplayed;
719 mutable int nLinesDisplayed;
720 mutable char fConfirmedDisplayed;
728 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
733 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
740 fTimeReceivedIsTxTime = false;
744 fDebitCached = false;
745 fCreditCached = false;
754 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
755 nVersion = this->nVersion;
758 READWRITE(vOrderForm);
759 READWRITE(fTimeReceivedIsTxTime);
760 READWRITE(nTimeReceived);
765 int64 GetDebit() const
771 nDebitCached = CTransaction::GetDebit();
776 int64 GetCredit(bool fUseCache=false) const
778 // Must wait until coinbase is safely deep enough in the chain before valuing it
779 if (IsCoinBase() && GetBlocksToMaturity() > 0)
782 // GetBalance can assume transactions in mapWallet won't change
783 if (fUseCache && fCreditCached)
784 return nCreditCached;
785 nCreditCached = CTransaction::GetCredit();
786 fCreditCached = true;
787 return nCreditCached;
790 bool IsConfirmed() const
792 map<uint256, const CMerkleTx*> mapPrev;
793 vector<const CMerkleTx*> vWorkQueue;
794 vWorkQueue.reserve(vtxPrev.size()+1);
795 vWorkQueue.push_back(this);
796 for (int i = 0; i < vWorkQueue.size(); i++)
798 const CMerkleTx* ptx = vWorkQueue[i];
802 if (ptx->GetDepthInMainChain() >= 1)
804 if (ptx->GetDebit() <= 0)
808 foreach(const CMerkleTx& tx, vtxPrev)
809 mapPrev[tx.GetHash()] = &tx;
811 foreach(const CTxIn& txin, ptx->vin)
813 if (!mapPrev.count(txin.prevout.hash))
815 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
823 return CWalletDB().WriteTx(GetHash(), *this);
827 int64 GetTxTime() const;
828 int GetRequestCount() const;
830 void AddSupportingTransactions(CTxDB& txdb);
832 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
833 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
835 void RelayWalletTransaction(CTxDB& txdb);
836 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
843 // A txdb record that contains the disk location of a transaction and the
844 // locations of transactions that spend its outputs. vSpent is really only
845 // used as a flag, but having the location is very helpful for debugging.
851 vector<CDiskTxPos> vSpent;
858 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
861 vSpent.resize(nOutputs);
866 if (!(nType & SER_GETHASH))
883 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
885 return (a.pos == b.pos &&
886 a.vSpent == b.vSpent);
889 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
900 // Nodes collect new transactions into a block, hash them into a hash tree,
901 // and scan through nonce values to make the block's hash satisfy proof-of-work
902 // requirements. When they solve the proof-of-work, they broadcast the block
903 // to everyone and the block is added to the block chain. The first transaction
904 // in the block is a special one that creates a new coin owned by the creator
907 // Blocks are appended to blk0001.dat files on disk. Their location on disk
908 // is indexed by CBlockIndex objects in memory.
915 uint256 hashPrevBlock;
916 uint256 hashMerkleRoot;
922 vector<CTransaction> vtx;
925 mutable vector<uint256> vMerkleTree;
935 READWRITE(this->nVersion);
936 nVersion = this->nVersion;
937 READWRITE(hashPrevBlock);
938 READWRITE(hashMerkleRoot);
943 // ConnectBlock depends on vtx being last so it can calculate offset
944 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
947 const_cast<CBlock*>(this)->vtx.clear();
967 uint256 GetHash() const
969 return Hash(BEGIN(nVersion), END(nNonce));
972 int64 GetBlockTime() const
977 int GetSigOpCount() const
980 foreach(const CTransaction& tx, vtx)
981 n += tx.GetSigOpCount();
986 uint256 BuildMerkleTree() const
989 foreach(const CTransaction& tx, vtx)
990 vMerkleTree.push_back(tx.GetHash());
992 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
994 for (int i = 0; i < nSize; i += 2)
996 int i2 = min(i+1, nSize-1);
997 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
998 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1002 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1005 vector<uint256> GetMerkleBranch(int nIndex) const
1007 if (vMerkleTree.empty())
1009 vector<uint256> vMerkleBranch;
1011 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1013 int i = min(nIndex^1, nSize-1);
1014 vMerkleBranch.push_back(vMerkleTree[j+i]);
1018 return vMerkleBranch;
1021 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1025 foreach(const uint256& otherside, vMerkleBranch)
1028 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1030 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1037 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1039 // Open history file to append
1040 CAutoFile fileout = AppendBlockFile(nFileRet);
1042 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1043 if (!fWriteTransactions)
1044 fileout.nType |= SER_BLOCKHEADERONLY;
1046 // Write index header
1047 unsigned int nSize = fileout.GetSerializeSize(*this);
1048 fileout << FLATDATA(pchMessageStart) << nSize;
1051 nBlockPosRet = ftell(fileout);
1052 if (nBlockPosRet == -1)
1053 return error("CBlock::WriteToDisk() : ftell failed");
1056 // Flush stdio buffers and commit to disk before returning
1058 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1061 _commit(_fileno(fileout));
1063 fsync(fileno(fileout));
1070 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1074 // Open history file to read
1075 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1077 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1078 if (!fReadTransactions)
1079 filein.nType |= SER_BLOCKHEADERONLY;
1085 if (!CheckProofOfWork(GetHash(), nBits))
1086 return error("CBlock::ReadFromDisk() : errors in block header");
1095 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1096 GetHash().ToString().substr(0,20).c_str(),
1098 hashPrevBlock.ToString().substr(0,20).c_str(),
1099 hashMerkleRoot.ToString().substr(0,10).c_str(),
1100 nTime, nBits, nNonce,
1102 for (int i = 0; i < vtx.size(); i++)
1107 printf(" vMerkleTree: ");
1108 for (int i = 0; i < vMerkleTree.size(); i++)
1109 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1114 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1115 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1116 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1117 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1118 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1119 bool CheckBlock() const;
1129 // The block chain is a tree shaped structure starting with the
1130 // genesis block at the root, with each block potentially having multiple
1131 // candidates to be the next block. pprev and pnext link a path through the
1132 // main/longest chain. A blockindex may have multiple pprev pointing back
1133 // to it, but pnext will only point forward to the longest branch, or will
1134 // be null if the block is not part of the longest chain.
1139 const uint256* phashBlock;
1143 unsigned int nBlockPos;
1145 CBigNum bnChainWork;
1149 uint256 hashMerkleRoot;
1152 unsigned int nNonce;
1172 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1178 nBlockPos = nBlockPosIn;
1182 nVersion = block.nVersion;
1183 hashMerkleRoot = block.hashMerkleRoot;
1184 nTime = block.nTime;
1185 nBits = block.nBits;
1186 nNonce = block.nNonce;
1189 uint256 GetBlockHash() const
1194 int64 GetBlockTime() const
1196 return (int64)nTime;
1199 CBigNum GetBlockWork() const
1202 bnTarget.SetCompact(nBits);
1205 return (CBigNum(1)<<256) / (bnTarget+1);
1208 bool IsInMainChain() const
1210 return (pnext || this == pindexBest);
1213 bool CheckIndex() const
1215 return CheckProofOfWork(GetBlockHash(), nBits);
1218 bool EraseBlockFromDisk()
1220 // Open history file
1221 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1225 // Overwrite with empty null block
1233 enum { nMedianTimeSpan=11 };
1235 int64 GetMedianTimePast() const
1237 int64 pmedian[nMedianTimeSpan];
1238 int64* pbegin = &pmedian[nMedianTimeSpan];
1239 int64* pend = &pmedian[nMedianTimeSpan];
1241 const CBlockIndex* pindex = this;
1242 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1243 *(--pbegin) = pindex->GetBlockTime();
1246 return pbegin[(pend - pbegin)/2];
1249 int64 GetMedianTime() const
1251 const CBlockIndex* pindex = this;
1252 for (int i = 0; i < nMedianTimeSpan/2; i++)
1255 return GetBlockTime();
1256 pindex = pindex->pnext;
1258 return pindex->GetMedianTimePast();
1263 string ToString() const
1265 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1266 pprev, pnext, nFile, nBlockPos, nHeight,
1267 hashMerkleRoot.ToString().substr(0,10).c_str(),
1268 GetBlockHash().ToString().substr(0,20).c_str());
1273 printf("%s\n", ToString().c_str());
1280 // Used to marshal pointers into hashes for db storage.
1282 class CDiskBlockIndex : public CBlockIndex
1294 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1296 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1297 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1302 if (!(nType & SER_GETHASH))
1303 READWRITE(nVersion);
1305 READWRITE(hashNext);
1307 READWRITE(nBlockPos);
1311 READWRITE(this->nVersion);
1312 READWRITE(hashPrev);
1313 READWRITE(hashMerkleRoot);
1319 uint256 GetBlockHash() const
1322 block.nVersion = nVersion;
1323 block.hashPrevBlock = hashPrev;
1324 block.hashMerkleRoot = hashMerkleRoot;
1325 block.nTime = nTime;
1326 block.nBits = nBits;
1327 block.nNonce = nNonce;
1328 return block.GetHash();
1332 string ToString() const
1334 string str = "CDiskBlockIndex(";
1335 str += CBlockIndex::ToString();
1336 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1337 GetBlockHash().ToString().c_str(),
1338 hashPrev.ToString().substr(0,20).c_str(),
1339 hashNext.ToString().substr(0,20).c_str());
1345 printf("%s\n", ToString().c_str());
1357 // Describes a place in the block chain to another node such that if the
1358 // other node doesn't have the same branch, it can find a recent common trunk.
1359 // The further back it is, the further before the fork it may be.
1364 vector<uint256> vHave;
1371 explicit CBlockLocator(const CBlockIndex* pindex)
1376 explicit CBlockLocator(uint256 hashBlock)
1378 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1379 if (mi != mapBlockIndex.end())
1385 if (!(nType & SER_GETHASH))
1386 READWRITE(nVersion);
1390 void Set(const CBlockIndex* pindex)
1396 vHave.push_back(pindex->GetBlockHash());
1398 // Exponentially larger steps back
1399 for (int i = 0; pindex && i < nStep; i++)
1400 pindex = pindex->pprev;
1401 if (vHave.size() > 10)
1404 vHave.push_back(hashGenesisBlock);
1407 int GetDistanceBack()
1409 // Retrace how far back it was in the sender's branch
1412 foreach(const uint256& hash, vHave)
1414 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1415 if (mi != mapBlockIndex.end())
1417 CBlockIndex* pindex = (*mi).second;
1418 if (pindex->IsInMainChain())
1428 CBlockIndex* GetBlockIndex()
1430 // Find the first block the caller has in the main chain
1431 foreach(const uint256& hash, vHave)
1433 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1434 if (mi != mapBlockIndex.end())
1436 CBlockIndex* pindex = (*mi).second;
1437 if (pindex->IsInMainChain())
1441 return pindexGenesisBlock;
1444 uint256 GetBlockHash()
1446 // Find the first block the caller has in the main chain
1447 foreach(const uint256& hash, vHave)
1449 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1450 if (mi != mapBlockIndex.end())
1452 CBlockIndex* pindex = (*mi).second;
1453 if (pindex->IsInMainChain())
1457 return hashGenesisBlock;
1462 CBlockIndex* pindex = GetBlockIndex();
1465 return pindex->nHeight;
1475 // Private key that includes an expiration date in case it never gets used.
1480 CPrivKey vchPrivKey;
1484 //// todo: add something to note what created it (user, getnewaddress, change)
1485 //// maybe should have a map<string, string> property map
1487 CWalletKey(int64 nExpires=0)
1489 nTimeCreated = (nExpires ? GetTime() : 0);
1490 nTimeExpires = nExpires;
1495 if (!(nType & SER_GETHASH))
1496 READWRITE(nVersion);
1497 READWRITE(vchPrivKey);
1498 READWRITE(nTimeCreated);
1499 READWRITE(nTimeExpires);
1500 READWRITE(strComment);
1510 // Alert messages are broadcast as a vector of signed data. Unserializing may
1511 // not read the entire buffer if the alert is for a newer version, but older
1512 // versions can still relay the original data.
1514 class CUnsignedAlert
1518 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1523 int nMinVer; // lowest version inclusive
1524 int nMaxVer; // highest version inclusive
1525 set<string> setSubVer; // empty matches all
1530 string strStatusBar;
1535 READWRITE(this->nVersion);
1536 nVersion = this->nVersion;
1537 READWRITE(nRelayUntil);
1538 READWRITE(nExpiration);
1541 READWRITE(setCancel);
1544 READWRITE(setSubVer);
1545 READWRITE(nPriority);
1547 READWRITE(strComment);
1548 READWRITE(strStatusBar);
1549 READWRITE(strRPCError);
1566 strStatusBar.clear();
1567 strRPCError.clear();
1570 string ToString() const
1572 string strSetCancel;
1573 foreach(int n, setCancel)
1574 strSetCancel += strprintf("%d ", n);
1575 string strSetSubVer;
1576 foreach(string str, setSubVer)
1577 strSetSubVer += "\"" + str + "\" ";
1581 " nRelayUntil = %"PRI64d"\n"
1582 " nExpiration = %"PRI64d"\n"
1590 " strComment = \"%s\"\n"
1591 " strStatusBar = \"%s\"\n"
1592 " strRPCError = \"%s\"\n"
1599 strSetCancel.c_str(),
1602 strSetSubVer.c_str(),
1605 strStatusBar.c_str(),
1606 strRPCError.c_str());
1611 printf("%s", ToString().c_str());
1615 class CAlert : public CUnsignedAlert
1618 vector<unsigned char> vchMsg;
1619 vector<unsigned char> vchSig;
1634 CUnsignedAlert::SetNull();
1641 return (nExpiration == 0);
1644 uint256 GetHash() const
1646 return SerializeHash(*this);
1649 bool IsInEffect() const
1651 return (GetAdjustedTime() < nExpiration);
1654 bool Cancels(const CAlert& alert) const
1658 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1661 bool AppliesTo(int nVersion, string strSubVerIn) const
1663 return (IsInEffect() &&
1664 nMinVer <= nVersion && nVersion <= nMaxVer &&
1665 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1668 bool AppliesToMe() const
1670 return AppliesTo(VERSION, ::pszSubVer);
1673 bool RelayTo(CNode* pnode) const
1677 // returns true if wasn't already contained in the set
1678 if (pnode->setKnown.insert(GetHash()).second)
1680 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1682 GetAdjustedTime() < nRelayUntil)
1684 pnode->PushMessage("alert", *this);
1691 bool CheckSignature()
1694 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1695 return error("CAlert::CheckSignature() : SetPubKey failed");
1696 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1697 return error("CAlert::CheckSignature() : verify signature failed");
1699 // Now unserialize the data
1700 CDataStream sMsg(vchMsg);
1701 sMsg >> *(CUnsignedAlert*)this;
1705 bool ProcessAlert();
1717 extern map<uint256, CTransaction> mapTransactions;
1718 extern map<uint256, CWalletTx> mapWallet;
1719 extern vector<uint256> vWalletUpdated;
1720 extern CCriticalSection cs_mapWallet;
1721 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1722 extern map<uint160, vector<unsigned char> > mapPubKeys;
1723 extern CCriticalSection cs_mapKeys;
1724 extern CKey keyUser;