1 // Copyright (c) 2009-2010 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 WalletUpdateSpent(const COutPoint& prevout);
\r
60 void ReacceptWalletTransactions();
\r
61 void RelayWalletTransactions();
\r
62 bool LoadBlockIndex(bool fAllowNew=true);
\r
63 void PrintBlockTree();
\r
64 bool ProcessMessages(CNode* pfrom);
\r
65 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
66 bool SendMessages(CNode* pto);
\r
68 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
69 bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key);
\r
70 bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);
\r
71 void GenerateBitcoins(bool fGenerate);
\r
72 void ThreadBitcoinMiner(void* parg);
\r
73 void BitcoinMiner();
\r
90 unsigned int nBlockPos;
\r
91 unsigned int nTxPos;
\r
98 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
101 nBlockPos = nBlockPosIn;
\r
105 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
106 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
107 bool IsNull() const { return (nFile == -1); }
\r
109 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
111 return (a.nFile == b.nFile &&
\r
112 a.nBlockPos == b.nBlockPos &&
\r
113 a.nTxPos == b.nTxPos);
\r
116 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
121 string ToString() const
\r
124 return strprintf("null");
\r
126 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
131 printf("%s", ToString().c_str());
\r
144 CInPoint() { SetNull(); }
\r
145 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
146 void SetNull() { ptx = NULL; n = -1; }
\r
147 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
159 COutPoint() { SetNull(); }
\r
160 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
161 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
162 void SetNull() { hash = 0; n = -1; }
\r
163 bool IsNull() const { return (hash == 0 && n == -1); }
\r
165 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
167 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
170 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
172 return (a.hash == b.hash && a.n == b.n);
\r
175 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
180 string ToString() const
\r
182 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
187 printf("%s\n", ToString().c_str());
\r
195 // An input of a transaction. It contains the location of the previous
\r
196 // transaction's output that it claims and a signature that matches the
\r
197 // output's public key.
\r
204 unsigned int nSequence;
\r
208 nSequence = UINT_MAX;
\r
211 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
213 prevout = prevoutIn;
\r
214 scriptSig = scriptSigIn;
\r
215 nSequence = nSequenceIn;
\r
218 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
220 prevout = COutPoint(hashPrevTx, nOut);
\r
221 scriptSig = scriptSigIn;
\r
222 nSequence = nSequenceIn;
\r
225 IMPLEMENT_SERIALIZE
\r
227 READWRITE(prevout);
\r
228 READWRITE(scriptSig);
\r
229 READWRITE(nSequence);
\r
232 bool IsFinal() const
\r
234 return (nSequence == UINT_MAX);
\r
237 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
239 return (a.prevout == b.prevout &&
\r
240 a.scriptSig == b.scriptSig &&
\r
241 a.nSequence == b.nSequence);
\r
244 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
249 string ToString() const
\r
252 str += strprintf("CTxIn(");
\r
253 str += prevout.ToString();
\r
254 if (prevout.IsNull())
\r
255 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
257 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
258 if (nSequence != UINT_MAX)
\r
259 str += strprintf(", nSequence=%u", nSequence);
\r
266 printf("%s\n", ToString().c_str());
\r
269 bool IsMine() const;
\r
270 int64 GetDebit() const;
\r
277 // An output of a transaction. It contains the public key that the next input
\r
278 // must be able to sign with to claim it.
\r
284 CScript scriptPubKey;
\r
292 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
295 scriptPubKey = scriptPubKeyIn;
\r
298 IMPLEMENT_SERIALIZE
\r
301 READWRITE(scriptPubKey);
\r
307 scriptPubKey.clear();
\r
312 return (nValue == -1);
\r
315 uint256 GetHash() const
\r
317 return SerializeHash(*this);
\r
320 bool IsMine() const
\r
322 return ::IsMine(scriptPubKey);
\r
325 int64 GetCredit() const
\r
332 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
334 return (a.nValue == b.nValue &&
\r
335 a.scriptPubKey == b.scriptPubKey);
\r
338 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
343 string ToString() const
\r
345 if (scriptPubKey.size() < 6)
\r
346 return "CTxOut(error)";
\r
347 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
352 printf("%s\n", ToString().c_str());
\r
360 // The basic transaction that is broadcasted on the network and contained in
\r
361 // blocks. A transaction can contain multiple inputs and outputs.
\r
368 vector<CTxOut> vout;
\r
369 unsigned int nLockTime;
\r
377 IMPLEMENT_SERIALIZE
\r
379 READWRITE(this->nVersion);
\r
380 nVersion = this->nVersion;
\r
383 READWRITE(nLockTime);
\r
394 bool IsNull() const
\r
396 return (vin.empty() && vout.empty());
\r
399 uint256 GetHash() const
\r
401 return SerializeHash(*this);
\r
404 bool IsFinal(int64 nBlockTime=0) const
\r
406 // Time based nLockTime implemented in 0.1.6,
\r
407 // do not use time based until most 0.1.5 nodes have upgraded.
\r
408 if (nLockTime == 0)
\r
410 if (nBlockTime == 0)
\r
411 nBlockTime = GetAdjustedTime();
\r
412 if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))
\r
414 foreach(const CTxIn& txin, vin)
\r
415 if (!txin.IsFinal())
\r
420 bool IsNewerThan(const CTransaction& old) const
\r
422 if (vin.size() != old.vin.size())
\r
424 for (int i = 0; i < vin.size(); i++)
\r
425 if (vin[i].prevout != old.vin[i].prevout)
\r
428 bool fNewer = false;
\r
429 unsigned int nLowest = UINT_MAX;
\r
430 for (int i = 0; i < vin.size(); i++)
\r
432 if (vin[i].nSequence != old.vin[i].nSequence)
\r
434 if (vin[i].nSequence <= nLowest)
\r
437 nLowest = vin[i].nSequence;
\r
439 if (old.vin[i].nSequence < nLowest)
\r
442 nLowest = old.vin[i].nSequence;
\r
449 bool IsCoinBase() const
\r
451 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
454 bool CheckTransaction() const
\r
456 // Basic checks that don't depend on any context
\r
457 if (vin.empty() || vout.empty())
\r
458 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
460 // Check for negative values
\r
461 foreach(const CTxOut& txout, vout)
\r
462 if (txout.nValue < 0)
\r
463 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
467 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
468 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
472 foreach(const CTxIn& txin, vin)
\r
473 if (txin.prevout.IsNull())
\r
474 return error("CTransaction::CheckTransaction() : prevout is null");
\r
480 bool IsMine() const
\r
482 foreach(const CTxOut& txout, vout)
\r
483 if (txout.IsMine())
\r
488 int64 GetDebit() const
\r
491 foreach(const CTxIn& txin, vin)
\r
492 nDebit += txin.GetDebit();
\r
496 int64 GetCredit() const
\r
499 foreach(const CTxOut& txout, vout)
\r
500 nCredit += txout.GetCredit();
\r
504 int64 GetValueOut() const
\r
506 int64 nValueOut = 0;
\r
507 foreach(const CTxOut& txout, vout)
\r
509 if (txout.nValue < 0)
\r
510 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
511 nValueOut += txout.nValue;
\r
516 int64 GetMinFee(unsigned int nBlockSize=1) const
\r
518 // Base fee is 1 cent per kilobyte
\r
519 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
520 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
522 // Transactions under 60K are free as long as block size is under 80K
\r
523 // (about 27,000bc if made of 50bc inputs)
\r
524 if (nBytes < 60000 && nBlockSize < 80000)
\r
527 // Transactions under 3K are free as long as block size is under 200K
\r
528 if (nBytes < 3000 && nBlockSize < 200000)
\r
531 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
532 if (nMinFee < CENT)
\r
533 foreach(const CTxOut& txout, vout)
\r
534 if (txout.nValue < CENT)
\r
542 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
544 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
546 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
548 // Read transaction
\r
549 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
550 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
553 // Return file pointer
\r
556 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
557 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
558 *pfileRet = filein.release();
\r
564 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
566 return (a.nVersion == b.nVersion &&
\r
568 a.vout == b.vout &&
\r
569 a.nLockTime == b.nLockTime);
\r
572 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
578 string ToString() const
\r
581 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
582 GetHash().ToString().substr(0,6).c_str(),
\r
587 for (int i = 0; i < vin.size(); i++)
\r
588 str += " " + vin[i].ToString() + "\n";
\r
589 for (int i = 0; i < vout.size(); i++)
\r
590 str += " " + vout[i].ToString() + "\n";
\r
596 printf("%s", ToString().c_str());
\r
601 bool DisconnectInputs(CTxDB& txdb);
\r
602 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
603 bool ClientConnectInputs();
\r
605 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
607 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
610 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
614 bool AddToMemoryPool();
\r
616 bool RemoveFromMemoryPool();
\r
624 // A transaction with a merkle branch linking it to the block chain
\r
626 class CMerkleTx : public CTransaction
\r
630 vector<uint256> vMerkleBranch;
\r
634 mutable bool fMerkleVerified;
\r
635 mutable bool fGetCreditCached;
\r
636 mutable int64 nGetCreditCached;
\r
644 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
653 fMerkleVerified = false;
\r
654 fGetCreditCached = false;
\r
655 nGetCreditCached = 0;
\r
658 IMPLEMENT_SERIALIZE
\r
660 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
661 nVersion = this->nVersion;
\r
662 READWRITE(hashBlock);
\r
663 READWRITE(vMerkleBranch);
\r
667 int64 GetCredit(bool fUseCache=false) const
\r
669 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
670 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
673 // GetBalance can assume transactions in mapWallet won't change
\r
674 if (fUseCache && fGetCreditCached)
\r
675 return nGetCreditCached;
\r
676 nGetCreditCached = CTransaction::GetCredit();
\r
677 fGetCreditCached = true;
\r
678 return nGetCreditCached;
\r
682 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
683 int GetDepthInMainChain() const;
\r
684 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
685 int GetBlocksToMaturity() const;
\r
686 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
687 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
694 // A transaction with a bunch of additional info that only the owner cares
\r
695 // about. It includes any unrecorded transactions needed to link it back
\r
696 // to the block chain.
\r
698 class CWalletTx : public CMerkleTx
\r
701 vector<CMerkleTx> vtxPrev;
\r
702 map<string, string> mapValue;
\r
703 vector<pair<string, string> > vOrderForm;
\r
704 unsigned int fTimeReceivedIsTxTime;
\r
705 unsigned int nTimeReceived; // time received by this node
\r
708 //// probably need to sign the order info so know it came from payer
\r
710 // memory only UI hints
\r
711 mutable unsigned int nTimeDisplayed;
\r
712 mutable int nLinesDisplayed;
\r
720 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
725 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
732 fTimeReceivedIsTxTime = false;
\r
736 nTimeDisplayed = 0;
\r
737 nLinesDisplayed = 0;
\r
740 IMPLEMENT_SERIALIZE
\r
742 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
743 nVersion = this->nVersion;
\r
744 READWRITE(vtxPrev);
\r
745 READWRITE(mapValue);
\r
746 READWRITE(vOrderForm);
\r
747 READWRITE(fTimeReceivedIsTxTime);
\r
748 READWRITE(nTimeReceived);
\r
749 READWRITE(fFromMe);
\r
755 return CWalletDB().WriteTx(GetHash(), *this);
\r
759 int64 GetTxTime() const;
\r
760 int GetRequestCount() const;
\r
762 void AddSupportingTransactions(CTxDB& txdb);
\r
764 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
765 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
767 void RelayWalletTransaction(CTxDB& txdb);
\r
768 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
775 // A txdb record that contains the disk location of a transaction and the
\r
776 // locations of transactions that spend its outputs. vSpent is really only
\r
777 // used as a flag, but having the location is very helpful for debugging.
\r
783 vector<CDiskTxPos> vSpent;
\r
790 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
793 vSpent.resize(nOutputs);
\r
796 IMPLEMENT_SERIALIZE
\r
798 if (!(nType & SER_GETHASH))
\r
799 READWRITE(nVersion);
\r
812 return pos.IsNull();
\r
815 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
817 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
819 for (int i = 0; i < a.vSpent.size(); i++)
\r
820 if (a.vSpent[i] != b.vSpent[i])
\r
825 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
836 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
837 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
838 // requirements. When they solve the proof-of-work, they broadcast the block
\r
839 // to everyone and the block is added to the block chain. The first transaction
\r
840 // in the block is a special one that creates a new coin owned by the creator
\r
843 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
844 // is indexed by CBlockIndex objects in memory.
\r
851 uint256 hashPrevBlock;
\r
852 uint256 hashMerkleRoot;
\r
853 unsigned int nTime;
\r
854 unsigned int nBits;
\r
855 unsigned int nNonce;
\r
857 // network and disk
\r
858 vector<CTransaction> vtx;
\r
861 mutable vector<uint256> vMerkleTree;
\r
869 IMPLEMENT_SERIALIZE
\r
871 READWRITE(this->nVersion);
\r
872 nVersion = this->nVersion;
\r
873 READWRITE(hashPrevBlock);
\r
874 READWRITE(hashMerkleRoot);
\r
879 // ConnectBlock depends on vtx being last so it can calculate offset
\r
880 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
883 const_cast<CBlock*>(this)->vtx.clear();
\r
890 hashMerkleRoot = 0;
\r
895 vMerkleTree.clear();
\r
898 bool IsNull() const
\r
900 return (nBits == 0);
\r
903 uint256 GetHash() const
\r
905 return Hash(BEGIN(nVersion), END(nNonce));
\r
909 uint256 BuildMerkleTree() const
\r
911 vMerkleTree.clear();
\r
912 foreach(const CTransaction& tx, vtx)
\r
913 vMerkleTree.push_back(tx.GetHash());
\r
915 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
917 for (int i = 0; i < nSize; i += 2)
\r
919 int i2 = min(i+1, nSize-1);
\r
920 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
921 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
925 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
928 vector<uint256> GetMerkleBranch(int nIndex) const
\r
930 if (vMerkleTree.empty())
\r
932 vector<uint256> vMerkleBranch;
\r
934 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
936 int i = min(nIndex^1, nSize-1);
\r
937 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
941 return vMerkleBranch;
\r
944 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
948 foreach(const uint256& otherside, vMerkleBranch)
\r
951 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
953 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
960 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
962 // Open history file to append
\r
963 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
965 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
966 if (!fWriteTransactions)
\r
967 fileout.nType |= SER_BLOCKHEADERONLY;
\r
969 // Write index header
\r
970 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
971 fileout << FLATDATA(pchMessageStart) << nSize;
\r
974 nBlockPosRet = ftell(fileout);
\r
975 if (nBlockPosRet == -1)
\r
976 return error("CBlock::WriteToDisk() : ftell failed");
\r
979 // Flush stdio buffers and commit to disk before returning
\r
982 _commit(_fileno(fileout));
\r
984 fsync(fileno(fileout));
\r
990 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
\r
994 // Open history file to read
\r
995 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
997 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
998 if (!fReadTransactions)
\r
999 filein.nType |= SER_BLOCKHEADERONLY;
\r
1004 // Check the header
\r
1005 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
1006 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
1007 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
1008 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
1015 void print() const
\r
1017 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
1018 GetHash().ToString().substr(0,16).c_str(),
\r
1020 hashPrevBlock.ToString().substr(0,16).c_str(),
\r
1021 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1022 nTime, nBits, nNonce,
\r
1024 for (int i = 0; i < vtx.size(); i++)
\r
1029 printf(" vMerkleTree: ");
\r
1030 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1031 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1036 int64 GetBlockValue(int64 nFees) const;
\r
1037 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1038 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1039 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);
\r
1040 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1041 bool CheckBlock() const;
\r
1042 bool AcceptBlock();
\r
1051 // The block chain is a tree shaped structure starting with the
\r
1052 // genesis block at the root, with each block potentially having multiple
\r
1053 // candidates to be the next block. pprev and pnext link a path through the
\r
1054 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1055 // to it, but pnext will only point forward to the longest branch, or will
\r
1056 // be null if the block is not part of the longest chain.
\r
1061 const uint256* phashBlock;
\r
1062 CBlockIndex* pprev;
\r
1063 CBlockIndex* pnext;
\r
1064 unsigned int nFile;
\r
1065 unsigned int nBlockPos;
\r
1070 uint256 hashMerkleRoot;
\r
1071 unsigned int nTime;
\r
1072 unsigned int nBits;
\r
1073 unsigned int nNonce;
\r
1078 phashBlock = NULL;
\r
1086 hashMerkleRoot = 0;
\r
1092 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1094 phashBlock = NULL;
\r
1098 nBlockPos = nBlockPosIn;
\r
1101 nVersion = block.nVersion;
\r
1102 hashMerkleRoot = block.hashMerkleRoot;
\r
1103 nTime = block.nTime;
\r
1104 nBits = block.nBits;
\r
1105 nNonce = block.nNonce;
\r
1108 uint256 GetBlockHash() const
\r
1110 return *phashBlock;
\r
1113 bool IsInMainChain() const
\r
1115 return (pnext || this == pindexBest);
\r
1118 bool EraseBlockFromDisk()
\r
1120 // Open history file
\r
1121 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1125 // Overwrite with empty null block
\r
1133 enum { nMedianTimeSpan=11 };
\r
1135 int64 GetMedianTimePast() const
\r
1137 unsigned int pmedian[nMedianTimeSpan];
\r
1138 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1139 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1141 const CBlockIndex* pindex = this;
\r
1142 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1143 *(--pbegin) = pindex->nTime;
\r
1145 sort(pbegin, pend);
\r
1146 return pbegin[(pend - pbegin)/2];
\r
1149 int64 GetMedianTime() const
\r
1151 const CBlockIndex* pindex = this;
\r
1152 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1154 if (!pindex->pnext)
\r
1156 pindex = pindex->pnext;
\r
1158 return pindex->GetMedianTimePast();
\r
1163 string ToString() const
\r
1165 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1166 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1167 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1168 GetBlockHash().ToString().substr(0,16).c_str());
\r
1171 void print() const
\r
1173 printf("%s\n", ToString().c_str());
\r
1180 // Used to marshal pointers into hashes for db storage.
\r
1182 class CDiskBlockIndex : public CBlockIndex
\r
1194 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1196 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1197 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1200 IMPLEMENT_SERIALIZE
\r
1202 if (!(nType & SER_GETHASH))
\r
1203 READWRITE(nVersion);
\r
1205 READWRITE(hashNext);
\r
1207 READWRITE(nBlockPos);
\r
1208 READWRITE(nHeight);
\r
1211 READWRITE(this->nVersion);
\r
1212 READWRITE(hashPrev);
\r
1213 READWRITE(hashMerkleRoot);
\r
1216 READWRITE(nNonce);
\r
1219 uint256 GetBlockHash() const
\r
1222 block.nVersion = nVersion;
\r
1223 block.hashPrevBlock = hashPrev;
\r
1224 block.hashMerkleRoot = hashMerkleRoot;
\r
1225 block.nTime = nTime;
\r
1226 block.nBits = nBits;
\r
1227 block.nNonce = nNonce;
\r
1228 return block.GetHash();
\r
1232 string ToString() const
\r
1234 string str = "CDiskBlockIndex(";
\r
1235 str += CBlockIndex::ToString();
\r
1236 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1237 GetBlockHash().ToString().c_str(),
\r
1238 hashPrev.ToString().substr(0,16).c_str(),
\r
1239 hashNext.ToString().substr(0,16).c_str());
\r
1243 void print() const
\r
1245 printf("%s\n", ToString().c_str());
\r
1257 // Describes a place in the block chain to another node such that if the
\r
1258 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1259 // The further back it is, the further before the fork it may be.
\r
1261 class CBlockLocator
\r
1264 vector<uint256> vHave;
\r
1271 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1276 explicit CBlockLocator(uint256 hashBlock)
\r
1278 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1279 if (mi != mapBlockIndex.end())
\r
1280 Set((*mi).second);
\r
1283 IMPLEMENT_SERIALIZE
\r
1285 if (!(nType & SER_GETHASH))
\r
1286 READWRITE(nVersion);
\r
1290 void Set(const CBlockIndex* pindex)
\r
1296 vHave.push_back(pindex->GetBlockHash());
\r
1298 // Exponentially larger steps back
\r
1299 for (int i = 0; pindex && i < nStep; i++)
\r
1300 pindex = pindex->pprev;
\r
1301 if (vHave.size() > 10)
\r
1304 vHave.push_back(hashGenesisBlock);
\r
1307 int GetDistanceBack()
\r
1309 // Retrace how far back it was in the sender's branch
\r
1310 int nDistance = 0;
\r
1312 foreach(const uint256& hash, vHave)
\r
1314 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1315 if (mi != mapBlockIndex.end())
\r
1317 CBlockIndex* pindex = (*mi).second;
\r
1318 if (pindex->IsInMainChain())
\r
1321 nDistance += nStep;
\r
1322 if (nDistance > 10)
\r
1328 CBlockIndex* GetBlockIndex()
\r
1330 // Find the first block the caller has in the main chain
\r
1331 foreach(const uint256& hash, vHave)
\r
1333 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1334 if (mi != mapBlockIndex.end())
\r
1336 CBlockIndex* pindex = (*mi).second;
\r
1337 if (pindex->IsInMainChain())
\r
1341 return pindexGenesisBlock;
\r
1344 uint256 GetBlockHash()
\r
1346 // Find the first block the caller has in the main chain
\r
1347 foreach(const uint256& hash, vHave)
\r
1349 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1350 if (mi != mapBlockIndex.end())
\r
1352 CBlockIndex* pindex = (*mi).second;
\r
1353 if (pindex->IsInMainChain())
\r
1357 return hashGenesisBlock;
\r
1362 CBlockIndex* pindex = GetBlockIndex();
\r
1365 return pindex->nHeight;
\r
1375 // Private key that includes an expiration date in case it never gets used.
\r
1380 CPrivKey vchPrivKey;
\r
1381 int64 nTimeCreated;
\r
1382 int64 nTimeExpires;
\r
1384 CWalletKey(int64 nTimeExpiresIn=0)
\r
1386 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
\r
1387 nTimeExpires = nTimeExpiresIn;
\r
1390 IMPLEMENT_SERIALIZE
\r
1392 if (!(nType & SER_GETHASH))
\r
1393 READWRITE(nVersion);
\r
1394 READWRITE(vchPrivKey);
\r
1395 READWRITE(nTimeCreated);
\r
1396 READWRITE(nTimeExpires);
\r
1405 extern map<uint256, CTransaction> mapTransactions;
\r
1406 extern map<uint256, CWalletTx> mapWallet;
\r
1407 extern vector<uint256> vWalletUpdated;
\r
1408 extern CCriticalSection cs_mapWallet;
\r
1409 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1410 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1411 extern CCriticalSection cs_mapKeys;
\r
1412 extern CKey keyUser;
\r