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);
86 CBlock* CreateNewBlock(CReserveKey& reservekey);
87 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
88 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
89 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
91 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
92 bool IsInitialBlockDownload();
93 string GetWarnings(string strFor);
110 unsigned int nBlockPos;
118 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
121 nBlockPos = nBlockPosIn;
125 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
126 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
127 bool IsNull() const { return (nFile == -1); }
129 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
131 return (a.nFile == b.nFile &&
132 a.nBlockPos == b.nBlockPos &&
133 a.nTxPos == b.nTxPos);
136 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
141 string ToString() const
144 return strprintf("null");
146 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
151 printf("%s", ToString().c_str());
164 CInPoint() { SetNull(); }
165 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
166 void SetNull() { ptx = NULL; n = -1; }
167 bool IsNull() const { return (ptx == NULL && n == -1); }
179 COutPoint() { SetNull(); }
180 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
181 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
182 void SetNull() { hash = 0; n = -1; }
183 bool IsNull() const { return (hash == 0 && n == -1); }
185 friend bool operator<(const COutPoint& a, const COutPoint& b)
187 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
190 friend bool operator==(const COutPoint& a, const COutPoint& b)
192 return (a.hash == b.hash && a.n == b.n);
195 friend bool operator!=(const COutPoint& a, const COutPoint& b)
200 string ToString() const
202 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
207 printf("%s\n", ToString().c_str());
215 // An input of a transaction. It contains the location of the previous
216 // transaction's output that it claims and a signature that matches the
217 // output's public key.
224 unsigned int nSequence;
228 nSequence = UINT_MAX;
231 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
234 scriptSig = scriptSigIn;
235 nSequence = nSequenceIn;
238 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
240 prevout = COutPoint(hashPrevTx, nOut);
241 scriptSig = scriptSigIn;
242 nSequence = nSequenceIn;
248 READWRITE(scriptSig);
249 READWRITE(nSequence);
254 return (nSequence == UINT_MAX);
257 friend bool operator==(const CTxIn& a, const CTxIn& b)
259 return (a.prevout == b.prevout &&
260 a.scriptSig == b.scriptSig &&
261 a.nSequence == b.nSequence);
264 friend bool operator!=(const CTxIn& a, const CTxIn& b)
269 string ToString() const
272 str += strprintf("CTxIn(");
273 str += prevout.ToString();
274 if (prevout.IsNull())
275 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
277 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
278 if (nSequence != UINT_MAX)
279 str += strprintf(", nSequence=%u", nSequence);
286 printf("%s\n", ToString().c_str());
290 int64 GetDebit() const;
297 // An output of a transaction. It contains the public key that the next input
298 // must be able to sign with to claim it.
304 CScript scriptPubKey;
311 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
314 scriptPubKey = scriptPubKeyIn;
320 READWRITE(scriptPubKey);
326 scriptPubKey.clear();
331 return (nValue == -1);
334 uint256 GetHash() const
336 return SerializeHash(*this);
341 return ::IsMine(scriptPubKey);
344 int64 GetCredit() const
346 if (!MoneyRange(nValue))
347 throw runtime_error("CTxOut::GetCredit() : value out of range");
353 friend bool operator==(const CTxOut& a, const CTxOut& b)
355 return (a.nValue == b.nValue &&
356 a.scriptPubKey == b.scriptPubKey);
359 friend bool operator!=(const CTxOut& a, const CTxOut& b)
364 string ToString() const
366 if (scriptPubKey.size() < 6)
367 return "CTxOut(error)";
368 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
373 printf("%s\n", ToString().c_str());
381 // The basic transaction that is broadcasted on the network and contained in
382 // blocks. A transaction can contain multiple inputs and outputs.
390 unsigned int nLockTime;
400 READWRITE(this->nVersion);
401 nVersion = this->nVersion;
404 READWRITE(nLockTime);
417 return (vin.empty() && vout.empty());
420 uint256 GetHash() const
422 return SerializeHash(*this);
425 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
427 // Time based nLockTime implemented in 0.1.6
430 if (nBlockHeight == 0)
431 nBlockHeight = nBestHeight;
433 nBlockTime = GetAdjustedTime();
434 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
436 foreach(const CTxIn& txin, vin)
442 bool IsNewerThan(const CTransaction& old) const
444 if (vin.size() != old.vin.size())
446 for (int i = 0; i < vin.size(); i++)
447 if (vin[i].prevout != old.vin[i].prevout)
451 unsigned int nLowest = UINT_MAX;
452 for (int i = 0; i < vin.size(); i++)
454 if (vin[i].nSequence != old.vin[i].nSequence)
456 if (vin[i].nSequence <= nLowest)
459 nLowest = vin[i].nSequence;
461 if (old.vin[i].nSequence < nLowest)
464 nLowest = old.vin[i].nSequence;
471 bool IsCoinBase() const
473 return (vin.size() == 1 && vin[0].prevout.IsNull());
476 int GetSigOpCount() const
479 foreach(const CTxIn& txin, vin)
480 n += txin.scriptSig.GetSigOpCount();
481 foreach(const CTxOut& txout, vout)
482 n += txout.scriptPubKey.GetSigOpCount();
488 foreach(const CTxOut& txout, vout)
494 bool IsFromMe() const
496 return (GetDebit() > 0);
499 int64 GetDebit() const
502 foreach(const CTxIn& txin, vin)
504 nDebit += txin.GetDebit();
505 if (!MoneyRange(nDebit))
506 throw runtime_error("CTransaction::GetDebit() : value out of range");
511 int64 GetCredit() const
514 foreach(const CTxOut& txout, vout)
516 nCredit += txout.GetCredit();
517 if (!MoneyRange(nCredit))
518 throw runtime_error("CTransaction::GetCredit() : value out of range");
523 int64 GetValueOut() const
526 foreach(const CTxOut& txout, vout)
528 nValueOut += txout.nValue;
529 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
530 throw runtime_error("CTransaction::GetValueOut() : value out of range");
535 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
537 // Base fee is 1 cent per kilobyte
538 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
539 unsigned int nNewBlockSize = nBlockSize + nBytes;
540 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
546 // Transactions under 10K are free
547 // (about 4500bc if made of 50bc inputs)
553 // Free transaction area
554 if (nNewBlockSize < 27000)
559 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
561 foreach(const CTxOut& txout, vout)
562 if (txout.nValue < CENT)
565 // Raise the price as the block approaches full
566 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
568 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
570 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
573 if (!MoneyRange(nMinFee))
579 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
581 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
583 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
586 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
587 return error("CTransaction::ReadFromDisk() : fseek failed");
590 // Return file pointer
593 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
594 return error("CTransaction::ReadFromDisk() : second fseek failed");
595 *pfileRet = filein.release();
600 friend bool operator==(const CTransaction& a, const CTransaction& b)
602 return (a.nVersion == b.nVersion &&
605 a.nLockTime == b.nLockTime);
608 friend bool operator!=(const CTransaction& a, const CTransaction& b)
614 string ToString() const
617 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
618 GetHash().ToString().substr(0,10).c_str(),
623 for (int i = 0; i < vin.size(); i++)
624 str += " " + vin[i].ToString() + "\n";
625 for (int i = 0; i < vout.size(); i++)
626 str += " " + vout[i].ToString() + "\n";
632 printf("%s", ToString().c_str());
636 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
637 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
638 bool ReadFromDisk(COutPoint prevout);
639 bool DisconnectInputs(CTxDB& txdb);
640 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
641 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
642 bool ClientConnectInputs();
643 bool CheckTransaction() const;
644 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
645 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
648 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
651 bool AddToMemoryPoolUnchecked();
653 bool RemoveFromMemoryPool();
661 // A transaction with a merkle branch linking it to the block chain
663 class CMerkleTx : public CTransaction
667 vector<uint256> vMerkleBranch;
671 mutable char fMerkleVerified;
679 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
688 fMerkleVerified = false;
693 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
694 nVersion = this->nVersion;
695 READWRITE(hashBlock);
696 READWRITE(vMerkleBranch);
701 int SetMerkleBranch(const CBlock* pblock=NULL);
702 int GetDepthInMainChain(int& nHeightRet) const;
703 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
704 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
705 int GetBlocksToMaturity() const;
706 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
707 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
714 // A transaction with a bunch of additional info that only the owner cares
715 // about. It includes any unrecorded transactions needed to link it back
716 // to the block chain.
718 class CWalletTx : public CMerkleTx
721 vector<CMerkleTx> vtxPrev;
722 map<string, string> mapValue;
723 vector<pair<string, string> > vOrderForm;
724 unsigned int nTimeReceived; // time received by this node
727 char fTimeReceivedIsTxTime;
729 string strFromAccount;
732 mutable char fDebitCached;
733 mutable char fCreditCached;
734 mutable int64 nDebitCached;
735 mutable int64 nCreditCached;
737 // memory only UI hints
738 mutable unsigned int nTimeDisplayed;
739 mutable int nLinesDisplayed;
740 mutable char fConfirmedDisplayed;
748 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
753 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
766 fTimeReceivedIsTxTime = false;
768 strFromAccount.clear();
769 fDebitCached = false;
770 fCreditCached = false;
775 fConfirmedDisplayed = false;
781 const_cast<CWalletTx*>(this)->Init();
782 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
785 READWRITE(vOrderForm);
787 if (fRead && nVersion < 100)
788 const_cast<CWalletTx*>(this)->fTimeReceivedIsTxTime = nVersion;
789 READWRITE(nTimeReceived);
792 if (nVersion >= 31404)
794 READWRITE(fTimeReceivedIsTxTime);
796 READWRITE(strFromAccount);
800 int64 GetDebit() const
806 nDebitCached = CTransaction::GetDebit();
811 int64 GetCredit(bool fUseCache=false) const
813 // Must wait until coinbase is safely deep enough in the chain before valuing it
814 if (IsCoinBase() && GetBlocksToMaturity() > 0)
817 // GetBalance can assume transactions in mapWallet won't change
818 if (fUseCache && fCreditCached)
819 return nCreditCached;
820 nCreditCached = CTransaction::GetCredit();
821 fCreditCached = true;
822 return nCreditCached;
825 bool IsFromMe() const
827 return (GetDebit() > 0);
830 bool IsConfirmed() const
832 // Quick answer in most cases
835 if (GetDepthInMainChain() >= 1)
837 if (!IsFromMe()) // using wtx's cached debit
840 // If no confirmations but it's from us, we can still
841 // consider it confirmed if all dependencies are confirmed
842 map<uint256, const CMerkleTx*> mapPrev;
843 vector<const CMerkleTx*> vWorkQueue;
844 vWorkQueue.reserve(vtxPrev.size()+1);
845 vWorkQueue.push_back(this);
846 for (int i = 0; i < vWorkQueue.size(); i++)
848 const CMerkleTx* ptx = vWorkQueue[i];
852 if (ptx->GetDepthInMainChain() >= 1)
854 if (!ptx->IsFromMe())
858 foreach(const CMerkleTx& tx, vtxPrev)
859 mapPrev[tx.GetHash()] = &tx;
861 foreach(const CTxIn& txin, ptx->vin)
863 if (!mapPrev.count(txin.prevout.hash))
865 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
873 return CWalletDB().WriteTx(GetHash(), *this);
877 int64 GetTxTime() const;
878 int GetRequestCount() const;
880 void AddSupportingTransactions(CTxDB& txdb);
882 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
883 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
885 void RelayWalletTransaction(CTxDB& txdb);
886 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
893 // A txdb record that contains the disk location of a transaction and the
894 // locations of transactions that spend its outputs. vSpent is really only
895 // used as a flag, but having the location is very helpful for debugging.
901 vector<CDiskTxPos> vSpent;
908 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
911 vSpent.resize(nOutputs);
916 if (!(nType & SER_GETHASH))
933 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
935 return (a.pos == b.pos &&
936 a.vSpent == b.vSpent);
939 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
950 // Nodes collect new transactions into a block, hash them into a hash tree,
951 // and scan through nonce values to make the block's hash satisfy proof-of-work
952 // requirements. When they solve the proof-of-work, they broadcast the block
953 // to everyone and the block is added to the block chain. The first transaction
954 // in the block is a special one that creates a new coin owned by the creator
957 // Blocks are appended to blk0001.dat files on disk. Their location on disk
958 // is indexed by CBlockIndex objects in memory.
965 uint256 hashPrevBlock;
966 uint256 hashMerkleRoot;
972 vector<CTransaction> vtx;
975 mutable vector<uint256> vMerkleTree;
985 READWRITE(this->nVersion);
986 nVersion = this->nVersion;
987 READWRITE(hashPrevBlock);
988 READWRITE(hashMerkleRoot);
993 // ConnectBlock depends on vtx being last so it can calculate offset
994 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
997 const_cast<CBlock*>(this)->vtx.clear();
1009 vMerkleTree.clear();
1014 return (nBits == 0);
1017 uint256 GetHash() const
1019 return Hash(BEGIN(nVersion), END(nNonce));
1022 int64 GetBlockTime() const
1024 return (int64)nTime;
1027 int GetSigOpCount() const
1030 foreach(const CTransaction& tx, vtx)
1031 n += tx.GetSigOpCount();
1036 uint256 BuildMerkleTree() const
1038 vMerkleTree.clear();
1039 foreach(const CTransaction& tx, vtx)
1040 vMerkleTree.push_back(tx.GetHash());
1042 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1044 for (int i = 0; i < nSize; i += 2)
1046 int i2 = min(i+1, nSize-1);
1047 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1048 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1052 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1055 vector<uint256> GetMerkleBranch(int nIndex) const
1057 if (vMerkleTree.empty())
1059 vector<uint256> vMerkleBranch;
1061 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1063 int i = min(nIndex^1, nSize-1);
1064 vMerkleBranch.push_back(vMerkleTree[j+i]);
1068 return vMerkleBranch;
1071 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1075 foreach(const uint256& otherside, vMerkleBranch)
1078 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1080 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1087 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1089 // Open history file to append
1090 CAutoFile fileout = AppendBlockFile(nFileRet);
1092 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1093 if (!fWriteTransactions)
1094 fileout.nType |= SER_BLOCKHEADERONLY;
1096 // Write index header
1097 unsigned int nSize = fileout.GetSerializeSize(*this);
1098 fileout << FLATDATA(pchMessageStart) << nSize;
1101 nBlockPosRet = ftell(fileout);
1102 if (nBlockPosRet == -1)
1103 return error("CBlock::WriteToDisk() : ftell failed");
1106 // Flush stdio buffers and commit to disk before returning
1108 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1111 _commit(_fileno(fileout));
1113 fsync(fileno(fileout));
1120 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1124 // Open history file to read
1125 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1127 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1128 if (!fReadTransactions)
1129 filein.nType |= SER_BLOCKHEADERONLY;
1135 if (!CheckProofOfWork(GetHash(), nBits))
1136 return error("CBlock::ReadFromDisk() : errors in block header");
1145 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1146 GetHash().ToString().substr(0,20).c_str(),
1148 hashPrevBlock.ToString().substr(0,20).c_str(),
1149 hashMerkleRoot.ToString().substr(0,10).c_str(),
1150 nTime, nBits, nNonce,
1152 for (int i = 0; i < vtx.size(); i++)
1157 printf(" vMerkleTree: ");
1158 for (int i = 0; i < vMerkleTree.size(); i++)
1159 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1164 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1165 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1166 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1167 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1168 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1169 bool CheckBlock() const;
1179 // The block chain is a tree shaped structure starting with the
1180 // genesis block at the root, with each block potentially having multiple
1181 // candidates to be the next block. pprev and pnext link a path through the
1182 // main/longest chain. A blockindex may have multiple pprev pointing back
1183 // to it, but pnext will only point forward to the longest branch, or will
1184 // be null if the block is not part of the longest chain.
1189 const uint256* phashBlock;
1193 unsigned int nBlockPos;
1195 CBigNum bnChainWork;
1199 uint256 hashMerkleRoot;
1202 unsigned int nNonce;
1222 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1228 nBlockPos = nBlockPosIn;
1232 nVersion = block.nVersion;
1233 hashMerkleRoot = block.hashMerkleRoot;
1234 nTime = block.nTime;
1235 nBits = block.nBits;
1236 nNonce = block.nNonce;
1239 uint256 GetBlockHash() const
1244 int64 GetBlockTime() const
1246 return (int64)nTime;
1249 CBigNum GetBlockWork() const
1252 bnTarget.SetCompact(nBits);
1255 return (CBigNum(1)<<256) / (bnTarget+1);
1258 bool IsInMainChain() const
1260 return (pnext || this == pindexBest);
1263 bool CheckIndex() const
1265 return CheckProofOfWork(GetBlockHash(), nBits);
1268 bool EraseBlockFromDisk()
1270 // Open history file
1271 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1275 // Overwrite with empty null block
1283 enum { nMedianTimeSpan=11 };
1285 int64 GetMedianTimePast() const
1287 int64 pmedian[nMedianTimeSpan];
1288 int64* pbegin = &pmedian[nMedianTimeSpan];
1289 int64* pend = &pmedian[nMedianTimeSpan];
1291 const CBlockIndex* pindex = this;
1292 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1293 *(--pbegin) = pindex->GetBlockTime();
1296 return pbegin[(pend - pbegin)/2];
1299 int64 GetMedianTime() const
1301 const CBlockIndex* pindex = this;
1302 for (int i = 0; i < nMedianTimeSpan/2; i++)
1305 return GetBlockTime();
1306 pindex = pindex->pnext;
1308 return pindex->GetMedianTimePast();
1313 string ToString() const
1315 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1316 pprev, pnext, nFile, nBlockPos, nHeight,
1317 hashMerkleRoot.ToString().substr(0,10).c_str(),
1318 GetBlockHash().ToString().substr(0,20).c_str());
1323 printf("%s\n", ToString().c_str());
1330 // Used to marshal pointers into hashes for db storage.
1332 class CDiskBlockIndex : public CBlockIndex
1344 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1346 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1347 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1352 if (!(nType & SER_GETHASH))
1353 READWRITE(nVersion);
1355 READWRITE(hashNext);
1357 READWRITE(nBlockPos);
1361 READWRITE(this->nVersion);
1362 READWRITE(hashPrev);
1363 READWRITE(hashMerkleRoot);
1369 uint256 GetBlockHash() const
1372 block.nVersion = nVersion;
1373 block.hashPrevBlock = hashPrev;
1374 block.hashMerkleRoot = hashMerkleRoot;
1375 block.nTime = nTime;
1376 block.nBits = nBits;
1377 block.nNonce = nNonce;
1378 return block.GetHash();
1382 string ToString() const
1384 string str = "CDiskBlockIndex(";
1385 str += CBlockIndex::ToString();
1386 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1387 GetBlockHash().ToString().c_str(),
1388 hashPrev.ToString().substr(0,20).c_str(),
1389 hashNext.ToString().substr(0,20).c_str());
1395 printf("%s\n", ToString().c_str());
1407 // Describes a place in the block chain to another node such that if the
1408 // other node doesn't have the same branch, it can find a recent common trunk.
1409 // The further back it is, the further before the fork it may be.
1414 vector<uint256> vHave;
1421 explicit CBlockLocator(const CBlockIndex* pindex)
1426 explicit CBlockLocator(uint256 hashBlock)
1428 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1429 if (mi != mapBlockIndex.end())
1435 if (!(nType & SER_GETHASH))
1436 READWRITE(nVersion);
1440 void Set(const CBlockIndex* pindex)
1446 vHave.push_back(pindex->GetBlockHash());
1448 // Exponentially larger steps back
1449 for (int i = 0; pindex && i < nStep; i++)
1450 pindex = pindex->pprev;
1451 if (vHave.size() > 10)
1454 vHave.push_back(hashGenesisBlock);
1457 int GetDistanceBack()
1459 // Retrace how far back it was in the sender's branch
1462 foreach(const uint256& hash, vHave)
1464 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1465 if (mi != mapBlockIndex.end())
1467 CBlockIndex* pindex = (*mi).second;
1468 if (pindex->IsInMainChain())
1478 CBlockIndex* GetBlockIndex()
1480 // Find the first block the caller has in the main chain
1481 foreach(const uint256& hash, vHave)
1483 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1484 if (mi != mapBlockIndex.end())
1486 CBlockIndex* pindex = (*mi).second;
1487 if (pindex->IsInMainChain())
1491 return pindexGenesisBlock;
1494 uint256 GetBlockHash()
1496 // Find the first block the caller has in the main chain
1497 foreach(const uint256& hash, vHave)
1499 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1500 if (mi != mapBlockIndex.end())
1502 CBlockIndex* pindex = (*mi).second;
1503 if (pindex->IsInMainChain())
1507 return hashGenesisBlock;
1512 CBlockIndex* pindex = GetBlockIndex();
1515 return pindex->nHeight;
1525 // Private key that includes an expiration date in case it never gets used.
1530 CPrivKey vchPrivKey;
1534 //// todo: add something to note what created it (user, getnewaddress, change)
1535 //// maybe should have a map<string, string> property map
1537 CWalletKey(int64 nExpires=0)
1539 nTimeCreated = (nExpires ? GetTime() : 0);
1540 nTimeExpires = nExpires;
1545 if (!(nType & SER_GETHASH))
1546 READWRITE(nVersion);
1547 READWRITE(vchPrivKey);
1548 READWRITE(nTimeCreated);
1549 READWRITE(nTimeExpires);
1550 READWRITE(strComment);
1560 // Account information.
1561 // Stored in wallet with key "acc"+string account name
1566 vector<unsigned char> vchPubKey;
1580 if (!(nType & SER_GETHASH))
1581 READWRITE(nVersion);
1582 READWRITE(vchPubKey);
1589 // Internal transfers.
1590 // Database key is acentry<account><counter>
1592 class CAccountingEntry
1597 string strOtherAccount;
1609 strOtherAccount.clear();
1615 if (!(nType & SER_GETHASH))
1616 READWRITE(nVersion);
1617 READWRITE(nCreditDebit);
1619 READWRITE(strOtherAccount);
1620 READWRITE(strComment);
1633 // Alert messages are broadcast as a vector of signed data. Unserializing may
1634 // not read the entire buffer if the alert is for a newer version, but older
1635 // versions can still relay the original data.
1637 class CUnsignedAlert
1641 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1646 int nMinVer; // lowest version inclusive
1647 int nMaxVer; // highest version inclusive
1648 set<string> setSubVer; // empty matches all
1653 string strStatusBar;
1658 READWRITE(this->nVersion);
1659 nVersion = this->nVersion;
1660 READWRITE(nRelayUntil);
1661 READWRITE(nExpiration);
1664 READWRITE(setCancel);
1667 READWRITE(setSubVer);
1668 READWRITE(nPriority);
1670 READWRITE(strComment);
1671 READWRITE(strStatusBar);
1672 READWRITE(strRPCError);
1689 strStatusBar.clear();
1690 strRPCError.clear();
1693 string ToString() const
1695 string strSetCancel;
1696 foreach(int n, setCancel)
1697 strSetCancel += strprintf("%d ", n);
1698 string strSetSubVer;
1699 foreach(string str, setSubVer)
1700 strSetSubVer += "\"" + str + "\" ";
1704 " nRelayUntil = %"PRI64d"\n"
1705 " nExpiration = %"PRI64d"\n"
1713 " strComment = \"%s\"\n"
1714 " strStatusBar = \"%s\"\n"
1715 " strRPCError = \"%s\"\n"
1722 strSetCancel.c_str(),
1725 strSetSubVer.c_str(),
1728 strStatusBar.c_str(),
1729 strRPCError.c_str());
1734 printf("%s", ToString().c_str());
1738 class CAlert : public CUnsignedAlert
1741 vector<unsigned char> vchMsg;
1742 vector<unsigned char> vchSig;
1757 CUnsignedAlert::SetNull();
1764 return (nExpiration == 0);
1767 uint256 GetHash() const
1769 return SerializeHash(*this);
1772 bool IsInEffect() const
1774 return (GetAdjustedTime() < nExpiration);
1777 bool Cancels(const CAlert& alert) const
1780 return false; // this was a no-op before 31403
1781 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1784 bool AppliesTo(int nVersion, string strSubVerIn) const
1786 return (IsInEffect() &&
1787 nMinVer <= nVersion && nVersion <= nMaxVer &&
1788 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1791 bool AppliesToMe() const
1793 return AppliesTo(VERSION, ::pszSubVer);
1796 bool RelayTo(CNode* pnode) const
1800 // returns true if wasn't already contained in the set
1801 if (pnode->setKnown.insert(GetHash()).second)
1803 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1805 GetAdjustedTime() < nRelayUntil)
1807 pnode->PushMessage("alert", *this);
1814 bool CheckSignature()
1817 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1818 return error("CAlert::CheckSignature() : SetPubKey failed");
1819 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1820 return error("CAlert::CheckSignature() : verify signature failed");
1822 // Now unserialize the data
1823 CDataStream sMsg(vchMsg);
1824 sMsg >> *(CUnsignedAlert*)this;
1828 bool ProcessAlert();
1840 extern map<uint256, CTransaction> mapTransactions;
1841 extern map<uint256, CWalletTx> mapWallet;
1842 extern vector<uint256> vWalletUpdated;
1843 extern CCriticalSection cs_mapWallet;
1844 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1845 extern map<uint160, vector<unsigned char> > mapPubKeys;
1846 extern CCriticalSection cs_mapKeys;
1847 extern CKey keyUser;