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& nFeeRet);
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();
583 friend bool operator==(const CTransaction& a, const CTransaction& b)
585 return (a.nVersion == b.nVersion &&
588 a.nLockTime == b.nLockTime);
591 friend bool operator!=(const CTransaction& a, const CTransaction& b)
597 string ToString() const
600 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
601 GetHash().ToString().substr(0,10).c_str(),
606 for (int i = 0; i < vin.size(); i++)
607 str += " " + vin[i].ToString() + "\n";
608 for (int i = 0; i < vout.size(); i++)
609 str += " " + vout[i].ToString() + "\n";
615 printf("%s", ToString().c_str());
619 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
620 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
621 bool ReadFromDisk(COutPoint prevout);
622 bool DisconnectInputs(CTxDB& txdb);
623 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
624 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
625 bool ClientConnectInputs();
626 bool CheckTransaction() const;
627 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
628 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
631 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
634 bool AddToMemoryPoolUnchecked();
636 bool RemoveFromMemoryPool();
644 // A transaction with a merkle branch linking it to the block chain
646 class CMerkleTx : public CTransaction
650 vector<uint256> vMerkleBranch;
654 mutable char fMerkleVerified;
662 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
671 fMerkleVerified = false;
676 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
677 nVersion = this->nVersion;
678 READWRITE(hashBlock);
679 READWRITE(vMerkleBranch);
684 int SetMerkleBranch(const CBlock* pblock=NULL);
685 int GetDepthInMainChain(int& nHeightRet) const;
686 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
687 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
688 int GetBlocksToMaturity() const;
689 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
690 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
697 // A transaction with a bunch of additional info that only the owner cares
698 // about. It includes any unrecorded transactions needed to link it back
699 // to the block chain.
701 class CWalletTx : public CMerkleTx
704 vector<CMerkleTx> vtxPrev;
705 map<string, string> mapValue;
706 vector<pair<string, string> > vOrderForm;
707 unsigned int fTimeReceivedIsTxTime;
708 unsigned int nTimeReceived; // time received by this node
711 //// probably need to sign the order info so know it came from payer
714 mutable char fDebitCached;
715 mutable char fCreditCached;
716 mutable int64 nDebitCached;
717 mutable int64 nCreditCached;
719 // memory only UI hints
720 mutable unsigned int nTimeDisplayed;
721 mutable int nLinesDisplayed;
722 mutable char fConfirmedDisplayed;
730 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
735 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
742 fTimeReceivedIsTxTime = false;
746 fDebitCached = false;
747 fCreditCached = false;
756 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
757 nVersion = this->nVersion;
760 READWRITE(vOrderForm);
761 READWRITE(fTimeReceivedIsTxTime);
762 READWRITE(nTimeReceived);
767 int64 GetDebit() const
773 nDebitCached = CTransaction::GetDebit();
778 int64 GetCredit(bool fUseCache=false) const
780 // Must wait until coinbase is safely deep enough in the chain before valuing it
781 if (IsCoinBase() && GetBlocksToMaturity() > 0)
784 // GetBalance can assume transactions in mapWallet won't change
785 if (fUseCache && fCreditCached)
786 return nCreditCached;
787 nCreditCached = CTransaction::GetCredit();
788 fCreditCached = true;
789 return nCreditCached;
792 bool IsConfirmed() const
794 map<uint256, const CMerkleTx*> mapPrev;
795 vector<const CMerkleTx*> vWorkQueue;
796 vWorkQueue.reserve(vtxPrev.size()+1);
797 vWorkQueue.push_back(this);
798 for (int i = 0; i < vWorkQueue.size(); i++)
800 const CMerkleTx* ptx = vWorkQueue[i];
804 if (ptx->GetDepthInMainChain() >= 1)
806 if (ptx->GetDebit() <= 0)
810 foreach(const CMerkleTx& tx, vtxPrev)
811 mapPrev[tx.GetHash()] = &tx;
813 foreach(const CTxIn& txin, ptx->vin)
815 if (!mapPrev.count(txin.prevout.hash))
817 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
825 return CWalletDB().WriteTx(GetHash(), *this);
829 int64 GetTxTime() const;
830 int GetRequestCount() const;
832 void AddSupportingTransactions(CTxDB& txdb);
834 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
835 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
837 void RelayWalletTransaction(CTxDB& txdb);
838 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
845 // A txdb record that contains the disk location of a transaction and the
846 // locations of transactions that spend its outputs. vSpent is really only
847 // used as a flag, but having the location is very helpful for debugging.
853 vector<CDiskTxPos> vSpent;
860 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
863 vSpent.resize(nOutputs);
868 if (!(nType & SER_GETHASH))
885 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
887 return (a.pos == b.pos &&
888 a.vSpent == b.vSpent);
891 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
902 // Nodes collect new transactions into a block, hash them into a hash tree,
903 // and scan through nonce values to make the block's hash satisfy proof-of-work
904 // requirements. When they solve the proof-of-work, they broadcast the block
905 // to everyone and the block is added to the block chain. The first transaction
906 // in the block is a special one that creates a new coin owned by the creator
909 // Blocks are appended to blk0001.dat files on disk. Their location on disk
910 // is indexed by CBlockIndex objects in memory.
917 uint256 hashPrevBlock;
918 uint256 hashMerkleRoot;
924 vector<CTransaction> vtx;
927 mutable vector<uint256> vMerkleTree;
937 READWRITE(this->nVersion);
938 nVersion = this->nVersion;
939 READWRITE(hashPrevBlock);
940 READWRITE(hashMerkleRoot);
945 // ConnectBlock depends on vtx being last so it can calculate offset
946 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
949 const_cast<CBlock*>(this)->vtx.clear();
969 uint256 GetHash() const
971 return Hash(BEGIN(nVersion), END(nNonce));
974 int64 GetBlockTime() const
979 int GetSigOpCount() const
982 foreach(const CTransaction& tx, vtx)
983 n += tx.GetSigOpCount();
988 uint256 BuildMerkleTree() const
991 foreach(const CTransaction& tx, vtx)
992 vMerkleTree.push_back(tx.GetHash());
994 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
996 for (int i = 0; i < nSize; i += 2)
998 int i2 = min(i+1, nSize-1);
999 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1000 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1004 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1007 vector<uint256> GetMerkleBranch(int nIndex) const
1009 if (vMerkleTree.empty())
1011 vector<uint256> vMerkleBranch;
1013 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1015 int i = min(nIndex^1, nSize-1);
1016 vMerkleBranch.push_back(vMerkleTree[j+i]);
1020 return vMerkleBranch;
1023 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1027 foreach(const uint256& otherside, vMerkleBranch)
1030 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1032 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1039 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1041 // Open history file to append
1042 CAutoFile fileout = AppendBlockFile(nFileRet);
1044 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1045 if (!fWriteTransactions)
1046 fileout.nType |= SER_BLOCKHEADERONLY;
1048 // Write index header
1049 unsigned int nSize = fileout.GetSerializeSize(*this);
1050 fileout << FLATDATA(pchMessageStart) << nSize;
1053 nBlockPosRet = ftell(fileout);
1054 if (nBlockPosRet == -1)
1055 return error("CBlock::WriteToDisk() : ftell failed");
1058 // Flush stdio buffers and commit to disk before returning
1060 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1063 _commit(_fileno(fileout));
1065 fsync(fileno(fileout));
1072 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1076 // Open history file to read
1077 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1079 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1080 if (!fReadTransactions)
1081 filein.nType |= SER_BLOCKHEADERONLY;
1087 if (!CheckProofOfWork(GetHash(), nBits))
1088 return error("CBlock::ReadFromDisk() : errors in block header");
1097 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1098 GetHash().ToString().substr(0,20).c_str(),
1100 hashPrevBlock.ToString().substr(0,20).c_str(),
1101 hashMerkleRoot.ToString().substr(0,10).c_str(),
1102 nTime, nBits, nNonce,
1104 for (int i = 0; i < vtx.size(); i++)
1109 printf(" vMerkleTree: ");
1110 for (int i = 0; i < vMerkleTree.size(); i++)
1111 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1116 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1117 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1118 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1119 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1120 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1121 bool CheckBlock() const;
1131 // The block chain is a tree shaped structure starting with the
1132 // genesis block at the root, with each block potentially having multiple
1133 // candidates to be the next block. pprev and pnext link a path through the
1134 // main/longest chain. A blockindex may have multiple pprev pointing back
1135 // to it, but pnext will only point forward to the longest branch, or will
1136 // be null if the block is not part of the longest chain.
1141 const uint256* phashBlock;
1145 unsigned int nBlockPos;
1147 CBigNum bnChainWork;
1151 uint256 hashMerkleRoot;
1154 unsigned int nNonce;
1174 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1180 nBlockPos = nBlockPosIn;
1184 nVersion = block.nVersion;
1185 hashMerkleRoot = block.hashMerkleRoot;
1186 nTime = block.nTime;
1187 nBits = block.nBits;
1188 nNonce = block.nNonce;
1191 uint256 GetBlockHash() const
1196 int64 GetBlockTime() const
1198 return (int64)nTime;
1201 CBigNum GetBlockWork() const
1204 bnTarget.SetCompact(nBits);
1207 return (CBigNum(1)<<256) / (bnTarget+1);
1210 bool IsInMainChain() const
1212 return (pnext || this == pindexBest);
1215 bool CheckIndex() const
1217 return CheckProofOfWork(GetBlockHash(), nBits);
1220 bool EraseBlockFromDisk()
1222 // Open history file
1223 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1227 // Overwrite with empty null block
1235 enum { nMedianTimeSpan=11 };
1237 int64 GetMedianTimePast() const
1239 int64 pmedian[nMedianTimeSpan];
1240 int64* pbegin = &pmedian[nMedianTimeSpan];
1241 int64* pend = &pmedian[nMedianTimeSpan];
1243 const CBlockIndex* pindex = this;
1244 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1245 *(--pbegin) = pindex->GetBlockTime();
1248 return pbegin[(pend - pbegin)/2];
1251 int64 GetMedianTime() const
1253 const CBlockIndex* pindex = this;
1254 for (int i = 0; i < nMedianTimeSpan/2; i++)
1257 return GetBlockTime();
1258 pindex = pindex->pnext;
1260 return pindex->GetMedianTimePast();
1265 string ToString() const
1267 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1268 pprev, pnext, nFile, nBlockPos, nHeight,
1269 hashMerkleRoot.ToString().substr(0,10).c_str(),
1270 GetBlockHash().ToString().substr(0,20).c_str());
1275 printf("%s\n", ToString().c_str());
1282 // Used to marshal pointers into hashes for db storage.
1284 class CDiskBlockIndex : public CBlockIndex
1296 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1298 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1299 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1304 if (!(nType & SER_GETHASH))
1305 READWRITE(nVersion);
1307 READWRITE(hashNext);
1309 READWRITE(nBlockPos);
1313 READWRITE(this->nVersion);
1314 READWRITE(hashPrev);
1315 READWRITE(hashMerkleRoot);
1321 uint256 GetBlockHash() const
1324 block.nVersion = nVersion;
1325 block.hashPrevBlock = hashPrev;
1326 block.hashMerkleRoot = hashMerkleRoot;
1327 block.nTime = nTime;
1328 block.nBits = nBits;
1329 block.nNonce = nNonce;
1330 return block.GetHash();
1334 string ToString() const
1336 string str = "CDiskBlockIndex(";
1337 str += CBlockIndex::ToString();
1338 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1339 GetBlockHash().ToString().c_str(),
1340 hashPrev.ToString().substr(0,20).c_str(),
1341 hashNext.ToString().substr(0,20).c_str());
1347 printf("%s\n", ToString().c_str());
1359 // Describes a place in the block chain to another node such that if the
1360 // other node doesn't have the same branch, it can find a recent common trunk.
1361 // The further back it is, the further before the fork it may be.
1366 vector<uint256> vHave;
1373 explicit CBlockLocator(const CBlockIndex* pindex)
1378 explicit CBlockLocator(uint256 hashBlock)
1380 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1381 if (mi != mapBlockIndex.end())
1387 if (!(nType & SER_GETHASH))
1388 READWRITE(nVersion);
1392 void Set(const CBlockIndex* pindex)
1398 vHave.push_back(pindex->GetBlockHash());
1400 // Exponentially larger steps back
1401 for (int i = 0; pindex && i < nStep; i++)
1402 pindex = pindex->pprev;
1403 if (vHave.size() > 10)
1406 vHave.push_back(hashGenesisBlock);
1409 int GetDistanceBack()
1411 // Retrace how far back it was in the sender's branch
1414 foreach(const uint256& hash, vHave)
1416 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1417 if (mi != mapBlockIndex.end())
1419 CBlockIndex* pindex = (*mi).second;
1420 if (pindex->IsInMainChain())
1430 CBlockIndex* GetBlockIndex()
1432 // Find the first block the caller has in the main chain
1433 foreach(const uint256& hash, vHave)
1435 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1436 if (mi != mapBlockIndex.end())
1438 CBlockIndex* pindex = (*mi).second;
1439 if (pindex->IsInMainChain())
1443 return pindexGenesisBlock;
1446 uint256 GetBlockHash()
1448 // Find the first block the caller has in the main chain
1449 foreach(const uint256& hash, vHave)
1451 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1452 if (mi != mapBlockIndex.end())
1454 CBlockIndex* pindex = (*mi).second;
1455 if (pindex->IsInMainChain())
1459 return hashGenesisBlock;
1464 CBlockIndex* pindex = GetBlockIndex();
1467 return pindex->nHeight;
1477 // Private key that includes an expiration date in case it never gets used.
1482 CPrivKey vchPrivKey;
1486 //// todo: add something to note what created it (user, getnewaddress, change)
1487 //// maybe should have a map<string, string> property map
1489 CWalletKey(int64 nExpires=0)
1491 nTimeCreated = (nExpires ? GetTime() : 0);
1492 nTimeExpires = nExpires;
1497 if (!(nType & SER_GETHASH))
1498 READWRITE(nVersion);
1499 READWRITE(vchPrivKey);
1500 READWRITE(nTimeCreated);
1501 READWRITE(nTimeExpires);
1502 READWRITE(strComment);
1512 // Alert messages are broadcast as a vector of signed data. Unserializing may
1513 // not read the entire buffer if the alert is for a newer version, but older
1514 // versions can still relay the original data.
1516 class CUnsignedAlert
1520 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1525 int nMinVer; // lowest version inclusive
1526 int nMaxVer; // highest version inclusive
1527 set<string> setSubVer; // empty matches all
1532 string strStatusBar;
1537 READWRITE(this->nVersion);
1538 nVersion = this->nVersion;
1539 READWRITE(nRelayUntil);
1540 READWRITE(nExpiration);
1543 READWRITE(setCancel);
1546 READWRITE(setSubVer);
1547 READWRITE(nPriority);
1549 READWRITE(strComment);
1550 READWRITE(strStatusBar);
1551 READWRITE(strRPCError);
1568 strStatusBar.clear();
1569 strRPCError.clear();
1572 string ToString() const
1574 string strSetCancel;
1575 foreach(int n, setCancel)
1576 strSetCancel += strprintf("%d ", n);
1577 string strSetSubVer;
1578 foreach(string str, setSubVer)
1579 strSetSubVer += "\"" + str + "\" ";
1583 " nRelayUntil = %"PRI64d"\n"
1584 " nExpiration = %"PRI64d"\n"
1592 " strComment = \"%s\"\n"
1593 " strStatusBar = \"%s\"\n"
1594 " strRPCError = \"%s\"\n"
1601 strSetCancel.c_str(),
1604 strSetSubVer.c_str(),
1607 strStatusBar.c_str(),
1608 strRPCError.c_str());
1613 printf("%s", ToString().c_str());
1617 class CAlert : public CUnsignedAlert
1620 vector<unsigned char> vchMsg;
1621 vector<unsigned char> vchSig;
1636 CUnsignedAlert::SetNull();
1643 return (nExpiration == 0);
1646 uint256 GetHash() const
1648 return SerializeHash(*this);
1651 bool IsInEffect() const
1653 return (GetAdjustedTime() < nExpiration);
1656 bool Cancels(const CAlert& alert) const
1659 return false; // this was a no-op before 31403
1660 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1663 bool AppliesTo(int nVersion, string strSubVerIn) const
1665 return (IsInEffect() &&
1666 nMinVer <= nVersion && nVersion <= nMaxVer &&
1667 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1670 bool AppliesToMe() const
1672 return AppliesTo(VERSION, ::pszSubVer);
1675 bool RelayTo(CNode* pnode) const
1679 // returns true if wasn't already contained in the set
1680 if (pnode->setKnown.insert(GetHash()).second)
1682 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1684 GetAdjustedTime() < nRelayUntil)
1686 pnode->PushMessage("alert", *this);
1693 bool CheckSignature()
1696 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1697 return error("CAlert::CheckSignature() : SetPubKey failed");
1698 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1699 return error("CAlert::CheckSignature() : verify signature failed");
1701 // Now unserialize the data
1702 CDataStream sMsg(vchMsg);
1703 sMsg >> *(CUnsignedAlert*)this;
1707 bool ProcessAlert();
1719 extern map<uint256, CTransaction> mapTransactions;
1720 extern map<uint256, CWalletTx> mapWallet;
1721 extern vector<uint256> vWalletUpdated;
1722 extern CCriticalSection cs_mapWallet;
1723 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1724 extern map<uint160, vector<unsigned char> > mapPubKeys;
1725 extern CCriticalSection cs_mapKeys;
1726 extern CKey keyUser;