1 // Copyright (c) 2009 Satoshi Nakamoto
\r
2 // Distributed under the MIT/X11 software license, see the accompanying
\r
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
\r
17 static const unsigned int MAX_SIZE = 0x02000000;
\r
18 static const int64 COIN = 100000000;
\r
19 static const int64 CENT = 1000000;
\r
20 static const int COINBASE_MATURITY = 100;
\r
22 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
\r
29 extern CCriticalSection cs_main;
\r
30 extern map<uint256, CBlockIndex*> mapBlockIndex;
\r
31 extern const uint256 hashGenesisBlock;
\r
32 extern CBlockIndex* pindexGenesisBlock;
\r
33 extern int nBestHeight;
\r
34 extern uint256 hashBestChain;
\r
35 extern CBlockIndex* pindexBest;
\r
36 extern unsigned int nTransactionsUpdated;
\r
37 extern map<uint256, int> mapRequestCount;
\r
38 extern CCriticalSection cs_mapRequestCount;
\r
41 extern int fGenerateBitcoins;
\r
42 extern int64 nTransactionFee;
\r
43 extern CAddress addrIncoming;
\r
44 extern int fLimitProcessors;
\r
45 extern int nLimitProcessors;
\r
53 bool CheckDiskSpace(int64 nAdditionalBytes=0);
\r
54 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
\r
55 FILE* AppendBlockFile(unsigned int& nFileRet);
\r
56 bool AddKey(const CKey& key);
\r
57 vector<unsigned char> GenerateNewKey();
\r
58 bool AddToWallet(const CWalletTx& wtxIn);
\r
59 void ReacceptWalletTransactions();
\r
60 void RelayWalletTransactions();
\r
61 bool LoadBlockIndex(bool fAllowNew=true);
\r
62 void PrintBlockTree();
\r
63 bool ProcessMessages(CNode* pfrom);
\r
64 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
65 bool SendMessages(CNode* pto);
\r
67 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
68 bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key);
\r
69 bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);
\r
70 void GenerateBitcoins(bool fGenerate);
\r
71 void ThreadBitcoinMiner(void* parg);
\r
72 void BitcoinMiner();
\r
89 unsigned int nBlockPos;
\r
90 unsigned int nTxPos;
\r
97 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
100 nBlockPos = nBlockPosIn;
\r
104 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
105 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
106 bool IsNull() const { return (nFile == -1); }
\r
108 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
110 return (a.nFile == b.nFile &&
\r
111 a.nBlockPos == b.nBlockPos &&
\r
112 a.nTxPos == b.nTxPos);
\r
115 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
120 string ToString() const
\r
123 return strprintf("null");
\r
125 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
130 printf("%s", ToString().c_str());
\r
143 CInPoint() { SetNull(); }
\r
144 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
145 void SetNull() { ptx = NULL; n = -1; }
\r
146 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
158 COutPoint() { SetNull(); }
\r
159 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
160 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
161 void SetNull() { hash = 0; n = -1; }
\r
162 bool IsNull() const { return (hash == 0 && n == -1); }
\r
164 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
166 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
169 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
171 return (a.hash == b.hash && a.n == b.n);
\r
174 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
179 string ToString() const
\r
181 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
186 printf("%s\n", ToString().c_str());
\r
194 // An input of a transaction. It contains the location of the previous
\r
195 // transaction's output that it claims and a signature that matches the
\r
196 // output's public key.
\r
203 unsigned int nSequence;
\r
207 nSequence = UINT_MAX;
\r
210 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
212 prevout = prevoutIn;
\r
213 scriptSig = scriptSigIn;
\r
214 nSequence = nSequenceIn;
\r
217 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
219 prevout = COutPoint(hashPrevTx, nOut);
\r
220 scriptSig = scriptSigIn;
\r
221 nSequence = nSequenceIn;
\r
224 IMPLEMENT_SERIALIZE
\r
226 READWRITE(prevout);
\r
227 READWRITE(scriptSig);
\r
228 READWRITE(nSequence);
\r
231 bool IsFinal() const
\r
233 return (nSequence == UINT_MAX);
\r
236 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
238 return (a.prevout == b.prevout &&
\r
239 a.scriptSig == b.scriptSig &&
\r
240 a.nSequence == b.nSequence);
\r
243 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
248 string ToString() const
\r
251 str += strprintf("CTxIn(");
\r
252 str += prevout.ToString();
\r
253 if (prevout.IsNull())
\r
254 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
256 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
257 if (nSequence != UINT_MAX)
\r
258 str += strprintf(", nSequence=%u", nSequence);
\r
265 printf("%s\n", ToString().c_str());
\r
268 bool IsMine() const;
\r
269 int64 GetDebit() const;
\r
276 // An output of a transaction. It contains the public key that the next input
\r
277 // must be able to sign with to claim it.
\r
283 CScript scriptPubKey;
\r
291 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
294 scriptPubKey = scriptPubKeyIn;
\r
297 IMPLEMENT_SERIALIZE
\r
300 READWRITE(scriptPubKey);
\r
306 scriptPubKey.clear();
\r
311 return (nValue == -1);
\r
314 uint256 GetHash() const
\r
316 return SerializeHash(*this);
\r
319 bool IsMine() const
\r
321 return ::IsMine(scriptPubKey);
\r
324 int64 GetCredit() const
\r
331 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
333 return (a.nValue == b.nValue &&
\r
334 a.scriptPubKey == b.scriptPubKey);
\r
337 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
342 string ToString() const
\r
344 if (scriptPubKey.size() < 6)
\r
345 return "CTxOut(error)";
\r
346 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
351 printf("%s\n", ToString().c_str());
\r
359 // The basic transaction that is broadcasted on the network and contained in
\r
360 // blocks. A transaction can contain multiple inputs and outputs.
\r
367 vector<CTxOut> vout;
\r
368 unsigned int nLockTime;
\r
376 IMPLEMENT_SERIALIZE
\r
378 READWRITE(this->nVersion);
\r
379 nVersion = this->nVersion;
\r
382 READWRITE(nLockTime);
\r
393 bool IsNull() const
\r
395 return (vin.empty() && vout.empty());
\r
398 uint256 GetHash() const
\r
400 return SerializeHash(*this);
\r
403 bool IsFinal(int64 nBlockTime=0) const
\r
405 // Time based nLockTime implemented in 0.1.6,
\r
406 // do not use time based until most 0.1.5 nodes have upgraded.
\r
407 if (nLockTime == 0)
\r
409 if (nBlockTime == 0)
\r
410 nBlockTime = GetAdjustedTime();
\r
411 if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))
\r
413 foreach(const CTxIn& txin, vin)
\r
414 if (!txin.IsFinal())
\r
419 bool IsNewerThan(const CTransaction& old) const
\r
421 if (vin.size() != old.vin.size())
\r
423 for (int i = 0; i < vin.size(); i++)
\r
424 if (vin[i].prevout != old.vin[i].prevout)
\r
427 bool fNewer = false;
\r
428 unsigned int nLowest = UINT_MAX;
\r
429 for (int i = 0; i < vin.size(); i++)
\r
431 if (vin[i].nSequence != old.vin[i].nSequence)
\r
433 if (vin[i].nSequence <= nLowest)
\r
436 nLowest = vin[i].nSequence;
\r
438 if (old.vin[i].nSequence < nLowest)
\r
441 nLowest = old.vin[i].nSequence;
\r
448 bool IsCoinBase() const
\r
450 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
453 bool CheckTransaction() const
\r
455 // Basic checks that don't depend on any context
\r
456 if (vin.empty() || vout.empty())
\r
457 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
459 // Check for negative values
\r
460 foreach(const CTxOut& txout, vout)
\r
461 if (txout.nValue < 0)
\r
462 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
466 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
467 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
471 foreach(const CTxIn& txin, vin)
\r
472 if (txin.prevout.IsNull())
\r
473 return error("CTransaction::CheckTransaction() : prevout is null");
\r
479 bool IsMine() const
\r
481 foreach(const CTxOut& txout, vout)
\r
482 if (txout.IsMine())
\r
487 int64 GetDebit() const
\r
490 foreach(const CTxIn& txin, vin)
\r
491 nDebit += txin.GetDebit();
\r
495 int64 GetCredit() const
\r
498 foreach(const CTxOut& txout, vout)
\r
499 nCredit += txout.GetCredit();
\r
503 int64 GetValueOut() const
\r
505 int64 nValueOut = 0;
\r
506 foreach(const CTxOut& txout, vout)
\r
508 if (txout.nValue < 0)
\r
509 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
510 nValueOut += txout.nValue;
\r
515 int64 GetMinFee(bool fDiscount=false) const
\r
517 // Base fee is 1 cent per kilobyte
\r
518 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
519 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
521 // First 100 transactions in a block are free
\r
522 if (fDiscount && nBytes < 10000)
\r
525 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
526 if (nMinFee < CENT)
\r
527 foreach(const CTxOut& txout, vout)
\r
528 if (txout.nValue < CENT)
\r
536 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
538 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
540 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
542 // Read transaction
\r
543 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
544 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
547 // Return file pointer
\r
550 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
551 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
552 *pfileRet = filein.release();
\r
558 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
560 return (a.nVersion == b.nVersion &&
\r
562 a.vout == b.vout &&
\r
563 a.nLockTime == b.nLockTime);
\r
566 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
572 string ToString() const
\r
575 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
576 GetHash().ToString().substr(0,6).c_str(),
\r
581 for (int i = 0; i < vin.size(); i++)
\r
582 str += " " + vin[i].ToString() + "\n";
\r
583 for (int i = 0; i < vout.size(); i++)
\r
584 str += " " + vout[i].ToString() + "\n";
\r
590 printf("%s", ToString().c_str());
\r
595 bool DisconnectInputs(CTxDB& txdb);
\r
596 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
597 bool ClientConnectInputs();
\r
599 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
601 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
604 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
608 bool AddToMemoryPool();
\r
610 bool RemoveFromMemoryPool();
\r
618 // A transaction with a merkle branch linking it to the block chain
\r
620 class CMerkleTx : public CTransaction
\r
624 vector<uint256> vMerkleBranch;
\r
628 mutable bool fMerkleVerified;
\r
629 mutable bool fGetCreditCached;
\r
630 mutable int64 nGetCreditCached;
\r
638 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
647 fMerkleVerified = false;
\r
648 fGetCreditCached = false;
\r
649 nGetCreditCached = 0;
\r
652 IMPLEMENT_SERIALIZE
\r
654 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
655 nVersion = this->nVersion;
\r
656 READWRITE(hashBlock);
\r
657 READWRITE(vMerkleBranch);
\r
661 int64 GetCredit(bool fUseCache=false) const
\r
663 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
664 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
667 // GetBalance can assume transactions in mapWallet won't change
\r
668 if (fUseCache && fGetCreditCached)
\r
669 return nGetCreditCached;
\r
670 nGetCreditCached = CTransaction::GetCredit();
\r
671 fGetCreditCached = true;
\r
672 return nGetCreditCached;
\r
676 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
677 int GetDepthInMainChain() const;
\r
678 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
679 int GetBlocksToMaturity() const;
\r
680 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
681 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
688 // A transaction with a bunch of additional info that only the owner cares
\r
689 // about. It includes any unrecorded transactions needed to link it back
\r
690 // to the block chain.
\r
692 class CWalletTx : public CMerkleTx
\r
695 vector<CMerkleTx> vtxPrev;
\r
696 map<string, string> mapValue;
\r
697 vector<pair<string, string> > vOrderForm;
\r
698 unsigned int fTimeReceivedIsTxTime;
\r
699 unsigned int nTimeReceived; // time received by this node
\r
702 //// probably need to sign the order info so know it came from payer
\r
704 // memory only UI hints
\r
705 mutable unsigned int nTimeDisplayed;
\r
706 mutable int nLinesDisplayed;
\r
714 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
719 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
726 fTimeReceivedIsTxTime = false;
\r
730 nTimeDisplayed = 0;
\r
731 nLinesDisplayed = 0;
\r
734 IMPLEMENT_SERIALIZE
\r
736 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
737 nVersion = this->nVersion;
\r
738 READWRITE(vtxPrev);
\r
739 READWRITE(mapValue);
\r
740 READWRITE(vOrderForm);
\r
741 READWRITE(fTimeReceivedIsTxTime);
\r
742 READWRITE(nTimeReceived);
\r
743 READWRITE(fFromMe);
\r
749 return CWalletDB().WriteTx(GetHash(), *this);
\r
753 int64 GetTxTime() const;
\r
754 int GetRequestCount() const;
\r
756 void AddSupportingTransactions(CTxDB& txdb);
\r
758 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
759 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
761 void RelayWalletTransaction(CTxDB& txdb);
\r
762 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
769 // A txdb record that contains the disk location of a transaction and the
\r
770 // locations of transactions that spend its outputs. vSpent is really only
\r
771 // used as a flag, but having the location is very helpful for debugging.
\r
777 vector<CDiskTxPos> vSpent;
\r
784 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
787 vSpent.resize(nOutputs);
\r
790 IMPLEMENT_SERIALIZE
\r
792 if (!(nType & SER_GETHASH))
\r
793 READWRITE(nVersion);
\r
806 return pos.IsNull();
\r
809 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
811 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
813 for (int i = 0; i < a.vSpent.size(); i++)
\r
814 if (a.vSpent[i] != b.vSpent[i])
\r
819 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
830 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
831 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
832 // requirements. When they solve the proof-of-work, they broadcast the block
\r
833 // to everyone and the block is added to the block chain. The first transaction
\r
834 // in the block is a special one that creates a new coin owned by the creator
\r
837 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
838 // is indexed by CBlockIndex objects in memory.
\r
845 uint256 hashPrevBlock;
\r
846 uint256 hashMerkleRoot;
\r
847 unsigned int nTime;
\r
848 unsigned int nBits;
\r
849 unsigned int nNonce;
\r
851 // network and disk
\r
852 vector<CTransaction> vtx;
\r
855 mutable vector<uint256> vMerkleTree;
\r
863 IMPLEMENT_SERIALIZE
\r
865 READWRITE(this->nVersion);
\r
866 nVersion = this->nVersion;
\r
867 READWRITE(hashPrevBlock);
\r
868 READWRITE(hashMerkleRoot);
\r
873 // ConnectBlock depends on vtx being last so it can calculate offset
\r
874 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
877 const_cast<CBlock*>(this)->vtx.clear();
\r
884 hashMerkleRoot = 0;
\r
889 vMerkleTree.clear();
\r
892 bool IsNull() const
\r
894 return (nBits == 0);
\r
897 uint256 GetHash() const
\r
899 return Hash(BEGIN(nVersion), END(nNonce));
\r
903 uint256 BuildMerkleTree() const
\r
905 vMerkleTree.clear();
\r
906 foreach(const CTransaction& tx, vtx)
\r
907 vMerkleTree.push_back(tx.GetHash());
\r
909 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
911 for (int i = 0; i < nSize; i += 2)
\r
913 int i2 = min(i+1, nSize-1);
\r
914 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
915 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
919 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
922 vector<uint256> GetMerkleBranch(int nIndex) const
\r
924 if (vMerkleTree.empty())
\r
926 vector<uint256> vMerkleBranch;
\r
928 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
930 int i = min(nIndex^1, nSize-1);
\r
931 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
935 return vMerkleBranch;
\r
938 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
942 foreach(const uint256& otherside, vMerkleBranch)
\r
945 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
947 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
954 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
956 // Open history file to append
\r
957 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
959 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
960 if (!fWriteTransactions)
\r
961 fileout.nType |= SER_BLOCKHEADERONLY;
\r
963 // Write index header
\r
964 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
965 fileout << FLATDATA(pchMessageStart) << nSize;
\r
968 nBlockPosRet = ftell(fileout);
\r
969 if (nBlockPosRet == -1)
\r
970 return error("CBlock::WriteToDisk() : ftell failed");
\r
973 // Flush stdio buffers and commit to disk before returning
\r
976 _commit(_fileno(fileout));
\r
978 fsync(fileno(fileout));
\r
984 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
\r
988 // Open history file to read
\r
989 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
991 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
992 if (!fReadTransactions)
\r
993 filein.nType |= SER_BLOCKHEADERONLY;
\r
998 // Check the header
\r
999 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
1000 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
1001 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
1002 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
1009 void print() const
\r
1011 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
1012 GetHash().ToString().substr(0,14).c_str(),
\r
1014 hashPrevBlock.ToString().substr(0,14).c_str(),
\r
1015 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1016 nTime, nBits, nNonce,
\r
1018 for (int i = 0; i < vtx.size(); i++)
\r
1023 printf(" vMerkleTree: ");
\r
1024 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1025 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1030 int64 GetBlockValue(int64 nFees) const;
\r
1031 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1032 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1033 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);
\r
1034 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1035 bool CheckBlock() const;
\r
1036 bool AcceptBlock();
\r
1045 // The block chain is a tree shaped structure starting with the
\r
1046 // genesis block at the root, with each block potentially having multiple
\r
1047 // candidates to be the next block. pprev and pnext link a path through the
\r
1048 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1049 // to it, but pnext will only point forward to the longest branch, or will
\r
1050 // be null if the block is not part of the longest chain.
\r
1055 const uint256* phashBlock;
\r
1056 CBlockIndex* pprev;
\r
1057 CBlockIndex* pnext;
\r
1058 unsigned int nFile;
\r
1059 unsigned int nBlockPos;
\r
1064 uint256 hashMerkleRoot;
\r
1065 unsigned int nTime;
\r
1066 unsigned int nBits;
\r
1067 unsigned int nNonce;
\r
1072 phashBlock = NULL;
\r
1080 hashMerkleRoot = 0;
\r
1086 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1088 phashBlock = NULL;
\r
1092 nBlockPos = nBlockPosIn;
\r
1095 nVersion = block.nVersion;
\r
1096 hashMerkleRoot = block.hashMerkleRoot;
\r
1097 nTime = block.nTime;
\r
1098 nBits = block.nBits;
\r
1099 nNonce = block.nNonce;
\r
1102 uint256 GetBlockHash() const
\r
1104 return *phashBlock;
\r
1107 bool IsInMainChain() const
\r
1109 return (pnext || this == pindexBest);
\r
1112 bool EraseBlockFromDisk()
\r
1114 // Open history file
\r
1115 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1119 // Overwrite with empty null block
\r
1127 enum { nMedianTimeSpan=11 };
\r
1129 int64 GetMedianTimePast() const
\r
1131 unsigned int pmedian[nMedianTimeSpan];
\r
1132 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1133 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1135 const CBlockIndex* pindex = this;
\r
1136 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1137 *(--pbegin) = pindex->nTime;
\r
1139 sort(pbegin, pend);
\r
1140 return pbegin[(pend - pbegin)/2];
\r
1143 int64 GetMedianTime() const
\r
1145 const CBlockIndex* pindex = this;
\r
1146 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1148 if (!pindex->pnext)
\r
1150 pindex = pindex->pnext;
\r
1152 return pindex->GetMedianTimePast();
\r
1157 string ToString() const
\r
1159 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1160 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1161 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1162 GetBlockHash().ToString().substr(0,14).c_str());
\r
1165 void print() const
\r
1167 printf("%s\n", ToString().c_str());
\r
1174 // Used to marshal pointers into hashes for db storage.
\r
1176 class CDiskBlockIndex : public CBlockIndex
\r
1188 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1190 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1191 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1194 IMPLEMENT_SERIALIZE
\r
1196 if (!(nType & SER_GETHASH))
\r
1197 READWRITE(nVersion);
\r
1199 READWRITE(hashNext);
\r
1201 READWRITE(nBlockPos);
\r
1202 READWRITE(nHeight);
\r
1205 READWRITE(this->nVersion);
\r
1206 READWRITE(hashPrev);
\r
1207 READWRITE(hashMerkleRoot);
\r
1210 READWRITE(nNonce);
\r
1213 uint256 GetBlockHash() const
\r
1216 block.nVersion = nVersion;
\r
1217 block.hashPrevBlock = hashPrev;
\r
1218 block.hashMerkleRoot = hashMerkleRoot;
\r
1219 block.nTime = nTime;
\r
1220 block.nBits = nBits;
\r
1221 block.nNonce = nNonce;
\r
1222 return block.GetHash();
\r
1226 string ToString() const
\r
1228 string str = "CDiskBlockIndex(";
\r
1229 str += CBlockIndex::ToString();
\r
1230 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1231 GetBlockHash().ToString().c_str(),
\r
1232 hashPrev.ToString().substr(0,14).c_str(),
\r
1233 hashNext.ToString().substr(0,14).c_str());
\r
1237 void print() const
\r
1239 printf("%s\n", ToString().c_str());
\r
1251 // Describes a place in the block chain to another node such that if the
\r
1252 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1253 // The further back it is, the further before the fork it may be.
\r
1255 class CBlockLocator
\r
1258 vector<uint256> vHave;
\r
1265 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1270 explicit CBlockLocator(uint256 hashBlock)
\r
1272 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1273 if (mi != mapBlockIndex.end())
\r
1274 Set((*mi).second);
\r
1277 IMPLEMENT_SERIALIZE
\r
1279 if (!(nType & SER_GETHASH))
\r
1280 READWRITE(nVersion);
\r
1284 void Set(const CBlockIndex* pindex)
\r
1290 vHave.push_back(pindex->GetBlockHash());
\r
1292 // Exponentially larger steps back
\r
1293 for (int i = 0; pindex && i < nStep; i++)
\r
1294 pindex = pindex->pprev;
\r
1295 if (vHave.size() > 10)
\r
1298 vHave.push_back(hashGenesisBlock);
\r
1301 CBlockIndex* GetBlockIndex()
\r
1303 // Find the first block the caller has in the main chain
\r
1304 foreach(const uint256& hash, vHave)
\r
1306 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1307 if (mi != mapBlockIndex.end())
\r
1309 CBlockIndex* pindex = (*mi).second;
\r
1310 if (pindex->IsInMainChain())
\r
1314 return pindexGenesisBlock;
\r
1317 uint256 GetBlockHash()
\r
1319 // Find the first block the caller has in the main chain
\r
1320 foreach(const uint256& hash, vHave)
\r
1322 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1323 if (mi != mapBlockIndex.end())
\r
1325 CBlockIndex* pindex = (*mi).second;
\r
1326 if (pindex->IsInMainChain())
\r
1330 return hashGenesisBlock;
\r
1335 CBlockIndex* pindex = GetBlockIndex();
\r
1338 return pindex->nHeight;
\r
1353 extern map<uint256, CTransaction> mapTransactions;
\r
1354 extern map<uint256, CWalletTx> mapWallet;
\r
1355 extern vector<uint256> vWalletUpdated;
\r
1356 extern CCriticalSection cs_mapWallet;
\r
1357 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1358 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1359 extern CCriticalSection cs_mapKeys;
\r
1360 extern CKey keyUser;
\r