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
39 extern map<string, string> mapAddressBook;
\r
40 extern CCriticalSection cs_mapAddressBook;
\r
43 extern int fGenerateBitcoins;
\r
44 extern int64 nTransactionFee;
\r
45 extern CAddress addrIncoming;
\r
46 extern int fLimitProcessors;
\r
47 extern int nLimitProcessors;
\r
55 bool CheckDiskSpace(int64 nAdditionalBytes=0);
\r
56 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
\r
57 FILE* AppendBlockFile(unsigned int& nFileRet);
\r
58 bool AddKey(const CKey& key);
\r
59 vector<unsigned char> GenerateNewKey();
\r
60 bool AddToWallet(const CWalletTx& wtxIn);
\r
61 void WalletUpdateSpent(const COutPoint& prevout);
\r
62 void ReacceptWalletTransactions();
\r
63 bool LoadBlockIndex(bool fAllowNew=true);
\r
64 void PrintBlockTree();
\r
65 bool ProcessMessages(CNode* pfrom);
\r
66 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
67 bool SendMessages(CNode* pto);
\r
69 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
70 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);
\r
71 bool BroadcastTransaction(CWalletTx& wtxNew);
\r
72 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
\r
73 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
\r
74 void GenerateBitcoins(bool fGenerate);
\r
75 void ThreadBitcoinMiner(void* parg);
\r
76 void BitcoinMiner();
\r
93 unsigned int nBlockPos;
\r
94 unsigned int nTxPos;
\r
101 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
104 nBlockPos = nBlockPosIn;
\r
108 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
109 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
110 bool IsNull() const { return (nFile == -1); }
\r
112 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
114 return (a.nFile == b.nFile &&
\r
115 a.nBlockPos == b.nBlockPos &&
\r
116 a.nTxPos == b.nTxPos);
\r
119 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
124 string ToString() const
\r
127 return strprintf("null");
\r
129 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
134 printf("%s", ToString().c_str());
\r
147 CInPoint() { SetNull(); }
\r
148 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
149 void SetNull() { ptx = NULL; n = -1; }
\r
150 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
162 COutPoint() { SetNull(); }
\r
163 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
164 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
165 void SetNull() { hash = 0; n = -1; }
\r
166 bool IsNull() const { return (hash == 0 && n == -1); }
\r
168 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
170 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
173 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
175 return (a.hash == b.hash && a.n == b.n);
\r
178 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
183 string ToString() const
\r
185 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
190 printf("%s\n", ToString().c_str());
\r
198 // An input of a transaction. It contains the location of the previous
\r
199 // transaction's output that it claims and a signature that matches the
\r
200 // output's public key.
\r
207 unsigned int nSequence;
\r
211 nSequence = UINT_MAX;
\r
214 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
216 prevout = prevoutIn;
\r
217 scriptSig = scriptSigIn;
\r
218 nSequence = nSequenceIn;
\r
221 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
223 prevout = COutPoint(hashPrevTx, nOut);
\r
224 scriptSig = scriptSigIn;
\r
225 nSequence = nSequenceIn;
\r
228 IMPLEMENT_SERIALIZE
\r
230 READWRITE(prevout);
\r
231 READWRITE(scriptSig);
\r
232 READWRITE(nSequence);
\r
235 bool IsFinal() const
\r
237 return (nSequence == UINT_MAX);
\r
240 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
242 return (a.prevout == b.prevout &&
\r
243 a.scriptSig == b.scriptSig &&
\r
244 a.nSequence == b.nSequence);
\r
247 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
252 string ToString() const
\r
255 str += strprintf("CTxIn(");
\r
256 str += prevout.ToString();
\r
257 if (prevout.IsNull())
\r
258 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
260 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
261 if (nSequence != UINT_MAX)
\r
262 str += strprintf(", nSequence=%u", nSequence);
\r
269 printf("%s\n", ToString().c_str());
\r
272 bool IsMine() const;
\r
273 int64 GetDebit() const;
\r
280 // An output of a transaction. It contains the public key that the next input
\r
281 // must be able to sign with to claim it.
\r
287 CScript scriptPubKey;
\r
295 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
298 scriptPubKey = scriptPubKeyIn;
\r
301 IMPLEMENT_SERIALIZE
\r
304 READWRITE(scriptPubKey);
\r
310 scriptPubKey.clear();
\r
315 return (nValue == -1);
\r
318 uint256 GetHash() const
\r
320 return SerializeHash(*this);
\r
323 bool IsMine() const
\r
325 return ::IsMine(scriptPubKey);
\r
328 int64 GetCredit() const
\r
335 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
337 return (a.nValue == b.nValue &&
\r
338 a.scriptPubKey == b.scriptPubKey);
\r
341 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
346 string ToString() const
\r
348 if (scriptPubKey.size() < 6)
\r
349 return "CTxOut(error)";
\r
350 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
355 printf("%s\n", ToString().c_str());
\r
363 // The basic transaction that is broadcasted on the network and contained in
\r
364 // blocks. A transaction can contain multiple inputs and outputs.
\r
371 vector<CTxOut> vout;
\r
372 unsigned int nLockTime;
\r
380 IMPLEMENT_SERIALIZE
\r
382 READWRITE(this->nVersion);
\r
383 nVersion = this->nVersion;
\r
386 READWRITE(nLockTime);
\r
397 bool IsNull() const
\r
399 return (vin.empty() && vout.empty());
\r
402 uint256 GetHash() const
\r
404 return SerializeHash(*this);
\r
407 bool IsFinal(int64 nBlockTime=0) const
\r
409 // Time based nLockTime implemented in 0.1.6,
\r
410 // do not use time based until most 0.1.5 nodes have upgraded.
\r
411 if (nLockTime == 0)
\r
413 if (nBlockTime == 0)
\r
414 nBlockTime = GetAdjustedTime();
\r
415 if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))
\r
417 foreach(const CTxIn& txin, vin)
\r
418 if (!txin.IsFinal())
\r
423 bool IsNewerThan(const CTransaction& old) const
\r
425 if (vin.size() != old.vin.size())
\r
427 for (int i = 0; i < vin.size(); i++)
\r
428 if (vin[i].prevout != old.vin[i].prevout)
\r
431 bool fNewer = false;
\r
432 unsigned int nLowest = UINT_MAX;
\r
433 for (int i = 0; i < vin.size(); i++)
\r
435 if (vin[i].nSequence != old.vin[i].nSequence)
\r
437 if (vin[i].nSequence <= nLowest)
\r
440 nLowest = vin[i].nSequence;
\r
442 if (old.vin[i].nSequence < nLowest)
\r
445 nLowest = old.vin[i].nSequence;
\r
452 bool IsCoinBase() const
\r
454 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
457 bool CheckTransaction() const
\r
459 // Basic checks that don't depend on any context
\r
460 if (vin.empty() || vout.empty())
\r
461 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
463 // Check for negative values
\r
464 foreach(const CTxOut& txout, vout)
\r
465 if (txout.nValue < 0)
\r
466 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
470 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
471 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
475 foreach(const CTxIn& txin, vin)
\r
476 if (txin.prevout.IsNull())
\r
477 return error("CTransaction::CheckTransaction() : prevout is null");
\r
483 bool IsMine() const
\r
485 foreach(const CTxOut& txout, vout)
\r
486 if (txout.IsMine())
\r
491 int64 GetDebit() const
\r
494 foreach(const CTxIn& txin, vin)
\r
495 nDebit += txin.GetDebit();
\r
499 int64 GetCredit() const
\r
502 foreach(const CTxOut& txout, vout)
\r
503 nCredit += txout.GetCredit();
\r
507 int64 GetValueOut() const
\r
509 int64 nValueOut = 0;
\r
510 foreach(const CTxOut& txout, vout)
\r
512 if (txout.nValue < 0)
\r
513 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
514 nValueOut += txout.nValue;
\r
519 int64 GetMinFee(unsigned int nBlockSize=1) const
\r
521 // Base fee is 1 cent per kilobyte
\r
522 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
523 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
525 // Transactions under 60K are free as long as block size is under 80K
\r
526 // (about 27,000bc if made of 50bc inputs)
\r
527 if (nBytes < 60000 && nBlockSize < 80000)
\r
530 // Transactions under 3K are free as long as block size is under 200K
\r
531 if (nBytes < 3000 && nBlockSize < 200000)
\r
534 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
535 if (nMinFee < CENT)
\r
536 foreach(const CTxOut& txout, vout)
\r
537 if (txout.nValue < CENT)
\r
545 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
547 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
549 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
551 // Read transaction
\r
552 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
553 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
556 // Return file pointer
\r
559 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
560 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
561 *pfileRet = filein.release();
\r
567 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
569 return (a.nVersion == b.nVersion &&
\r
571 a.vout == b.vout &&
\r
572 a.nLockTime == b.nLockTime);
\r
575 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
581 string ToString() const
\r
584 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
585 GetHash().ToString().substr(0,6).c_str(),
\r
590 for (int i = 0; i < vin.size(); i++)
\r
591 str += " " + vin[i].ToString() + "\n";
\r
592 for (int i = 0; i < vout.size(); i++)
\r
593 str += " " + vout[i].ToString() + "\n";
\r
599 printf("%s", ToString().c_str());
\r
604 bool DisconnectInputs(CTxDB& txdb);
\r
605 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
606 bool ClientConnectInputs();
\r
608 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
610 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
613 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
617 bool AddToMemoryPool();
\r
619 bool RemoveFromMemoryPool();
\r
627 // A transaction with a merkle branch linking it to the block chain
\r
629 class CMerkleTx : public CTransaction
\r
633 vector<uint256> vMerkleBranch;
\r
637 mutable bool fMerkleVerified;
\r
638 mutable bool fGetCreditCached;
\r
639 mutable int64 nGetCreditCached;
\r
647 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
656 fMerkleVerified = false;
\r
657 fGetCreditCached = false;
\r
658 nGetCreditCached = 0;
\r
661 IMPLEMENT_SERIALIZE
\r
663 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
664 nVersion = this->nVersion;
\r
665 READWRITE(hashBlock);
\r
666 READWRITE(vMerkleBranch);
\r
670 int64 GetCredit(bool fUseCache=false) const
\r
672 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
673 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
676 // GetBalance can assume transactions in mapWallet won't change
\r
677 if (fUseCache && fGetCreditCached)
\r
678 return nGetCreditCached;
\r
679 nGetCreditCached = CTransaction::GetCredit();
\r
680 fGetCreditCached = true;
\r
681 return nGetCreditCached;
\r
685 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
686 int GetDepthInMainChain(int& nHeightRet) const;
\r
687 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
\r
688 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
689 int GetBlocksToMaturity() const;
\r
690 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
691 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
698 // A transaction with a bunch of additional info that only the owner cares
\r
699 // about. It includes any unrecorded transactions needed to link it back
\r
700 // to the block chain.
\r
702 class CWalletTx : public CMerkleTx
\r
705 vector<CMerkleTx> vtxPrev;
\r
706 map<string, string> mapValue;
\r
707 vector<pair<string, string> > vOrderForm;
\r
708 unsigned int fTimeReceivedIsTxTime;
\r
709 unsigned int nTimeReceived; // time received by this node
\r
712 //// probably need to sign the order info so know it came from payer
\r
714 // memory only UI hints
\r
715 mutable unsigned int nTimeDisplayed;
\r
716 mutable int nLinesDisplayed;
\r
724 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
729 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
736 fTimeReceivedIsTxTime = false;
\r
740 nTimeDisplayed = 0;
\r
741 nLinesDisplayed = 0;
\r
744 IMPLEMENT_SERIALIZE
\r
746 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
747 nVersion = this->nVersion;
\r
748 READWRITE(vtxPrev);
\r
749 READWRITE(mapValue);
\r
750 READWRITE(vOrderForm);
\r
751 READWRITE(fTimeReceivedIsTxTime);
\r
752 READWRITE(nTimeReceived);
\r
753 READWRITE(fFromMe);
\r
759 return CWalletDB().WriteTx(GetHash(), *this);
\r
763 int64 GetTxTime() const;
\r
764 int GetRequestCount() const;
\r
766 void AddSupportingTransactions(CTxDB& txdb);
\r
768 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
769 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
771 void RelayWalletTransaction(CTxDB& txdb);
\r
772 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
779 // A txdb record that contains the disk location of a transaction and the
\r
780 // locations of transactions that spend its outputs. vSpent is really only
\r
781 // used as a flag, but having the location is very helpful for debugging.
\r
787 vector<CDiskTxPos> vSpent;
\r
794 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
797 vSpent.resize(nOutputs);
\r
800 IMPLEMENT_SERIALIZE
\r
802 if (!(nType & SER_GETHASH))
\r
803 READWRITE(nVersion);
\r
816 return pos.IsNull();
\r
819 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
821 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
823 for (int i = 0; i < a.vSpent.size(); i++)
\r
824 if (a.vSpent[i] != b.vSpent[i])
\r
829 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
840 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
841 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
842 // requirements. When they solve the proof-of-work, they broadcast the block
\r
843 // to everyone and the block is added to the block chain. The first transaction
\r
844 // in the block is a special one that creates a new coin owned by the creator
\r
847 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
848 // is indexed by CBlockIndex objects in memory.
\r
855 uint256 hashPrevBlock;
\r
856 uint256 hashMerkleRoot;
\r
857 unsigned int nTime;
\r
858 unsigned int nBits;
\r
859 unsigned int nNonce;
\r
861 // network and disk
\r
862 vector<CTransaction> vtx;
\r
865 mutable vector<uint256> vMerkleTree;
\r
873 IMPLEMENT_SERIALIZE
\r
875 READWRITE(this->nVersion);
\r
876 nVersion = this->nVersion;
\r
877 READWRITE(hashPrevBlock);
\r
878 READWRITE(hashMerkleRoot);
\r
883 // ConnectBlock depends on vtx being last so it can calculate offset
\r
884 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
887 const_cast<CBlock*>(this)->vtx.clear();
\r
894 hashMerkleRoot = 0;
\r
899 vMerkleTree.clear();
\r
902 bool IsNull() const
\r
904 return (nBits == 0);
\r
907 uint256 GetHash() const
\r
909 return Hash(BEGIN(nVersion), END(nNonce));
\r
913 uint256 BuildMerkleTree() const
\r
915 vMerkleTree.clear();
\r
916 foreach(const CTransaction& tx, vtx)
\r
917 vMerkleTree.push_back(tx.GetHash());
\r
919 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
921 for (int i = 0; i < nSize; i += 2)
\r
923 int i2 = min(i+1, nSize-1);
\r
924 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
925 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
929 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
932 vector<uint256> GetMerkleBranch(int nIndex) const
\r
934 if (vMerkleTree.empty())
\r
936 vector<uint256> vMerkleBranch;
\r
938 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
940 int i = min(nIndex^1, nSize-1);
\r
941 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
945 return vMerkleBranch;
\r
948 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
952 foreach(const uint256& otherside, vMerkleBranch)
\r
955 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
957 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
964 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
966 // Open history file to append
\r
967 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
969 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
970 if (!fWriteTransactions)
\r
971 fileout.nType |= SER_BLOCKHEADERONLY;
\r
973 // Write index header
\r
974 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
975 fileout << FLATDATA(pchMessageStart) << nSize;
\r
978 nBlockPosRet = ftell(fileout);
\r
979 if (nBlockPosRet == -1)
\r
980 return error("CBlock::WriteToDisk() : ftell failed");
\r
983 // Flush stdio buffers and commit to disk before returning
\r
986 _commit(_fileno(fileout));
\r
988 fsync(fileno(fileout));
\r
994 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
\r
998 // Open history file to read
\r
999 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
1001 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
1002 if (!fReadTransactions)
\r
1003 filein.nType |= SER_BLOCKHEADERONLY;
\r
1008 // Check the header
\r
1009 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
1010 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
1011 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
1012 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
1019 void print() const
\r
1021 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
1022 GetHash().ToString().substr(0,16).c_str(),
\r
1024 hashPrevBlock.ToString().substr(0,16).c_str(),
\r
1025 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1026 nTime, nBits, nNonce,
\r
1028 for (int i = 0; i < vtx.size(); i++)
\r
1033 printf(" vMerkleTree: ");
\r
1034 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1035 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1040 int64 GetBlockValue(int64 nFees) const;
\r
1041 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1042 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1043 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);
\r
1044 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1045 bool CheckBlock() const;
\r
1046 bool AcceptBlock();
\r
1055 // The block chain is a tree shaped structure starting with the
\r
1056 // genesis block at the root, with each block potentially having multiple
\r
1057 // candidates to be the next block. pprev and pnext link a path through the
\r
1058 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1059 // to it, but pnext will only point forward to the longest branch, or will
\r
1060 // be null if the block is not part of the longest chain.
\r
1065 const uint256* phashBlock;
\r
1066 CBlockIndex* pprev;
\r
1067 CBlockIndex* pnext;
\r
1068 unsigned int nFile;
\r
1069 unsigned int nBlockPos;
\r
1074 uint256 hashMerkleRoot;
\r
1075 unsigned int nTime;
\r
1076 unsigned int nBits;
\r
1077 unsigned int nNonce;
\r
1082 phashBlock = NULL;
\r
1090 hashMerkleRoot = 0;
\r
1096 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1098 phashBlock = NULL;
\r
1102 nBlockPos = nBlockPosIn;
\r
1105 nVersion = block.nVersion;
\r
1106 hashMerkleRoot = block.hashMerkleRoot;
\r
1107 nTime = block.nTime;
\r
1108 nBits = block.nBits;
\r
1109 nNonce = block.nNonce;
\r
1112 uint256 GetBlockHash() const
\r
1114 return *phashBlock;
\r
1117 bool IsInMainChain() const
\r
1119 return (pnext || this == pindexBest);
\r
1122 bool EraseBlockFromDisk()
\r
1124 // Open history file
\r
1125 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1129 // Overwrite with empty null block
\r
1137 enum { nMedianTimeSpan=11 };
\r
1139 int64 GetMedianTimePast() const
\r
1141 unsigned int pmedian[nMedianTimeSpan];
\r
1142 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1143 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1145 const CBlockIndex* pindex = this;
\r
1146 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1147 *(--pbegin) = pindex->nTime;
\r
1149 sort(pbegin, pend);
\r
1150 return pbegin[(pend - pbegin)/2];
\r
1153 int64 GetMedianTime() const
\r
1155 const CBlockIndex* pindex = this;
\r
1156 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1158 if (!pindex->pnext)
\r
1160 pindex = pindex->pnext;
\r
1162 return pindex->GetMedianTimePast();
\r
1167 string ToString() const
\r
1169 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1170 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1171 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1172 GetBlockHash().ToString().substr(0,16).c_str());
\r
1175 void print() const
\r
1177 printf("%s\n", ToString().c_str());
\r
1184 // Used to marshal pointers into hashes for db storage.
\r
1186 class CDiskBlockIndex : public CBlockIndex
\r
1198 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1200 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1201 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1204 IMPLEMENT_SERIALIZE
\r
1206 if (!(nType & SER_GETHASH))
\r
1207 READWRITE(nVersion);
\r
1209 READWRITE(hashNext);
\r
1211 READWRITE(nBlockPos);
\r
1212 READWRITE(nHeight);
\r
1215 READWRITE(this->nVersion);
\r
1216 READWRITE(hashPrev);
\r
1217 READWRITE(hashMerkleRoot);
\r
1220 READWRITE(nNonce);
\r
1223 uint256 GetBlockHash() const
\r
1226 block.nVersion = nVersion;
\r
1227 block.hashPrevBlock = hashPrev;
\r
1228 block.hashMerkleRoot = hashMerkleRoot;
\r
1229 block.nTime = nTime;
\r
1230 block.nBits = nBits;
\r
1231 block.nNonce = nNonce;
\r
1232 return block.GetHash();
\r
1236 string ToString() const
\r
1238 string str = "CDiskBlockIndex(";
\r
1239 str += CBlockIndex::ToString();
\r
1240 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1241 GetBlockHash().ToString().c_str(),
\r
1242 hashPrev.ToString().substr(0,16).c_str(),
\r
1243 hashNext.ToString().substr(0,16).c_str());
\r
1247 void print() const
\r
1249 printf("%s\n", ToString().c_str());
\r
1261 // Describes a place in the block chain to another node such that if the
\r
1262 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1263 // The further back it is, the further before the fork it may be.
\r
1265 class CBlockLocator
\r
1268 vector<uint256> vHave;
\r
1275 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1280 explicit CBlockLocator(uint256 hashBlock)
\r
1282 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1283 if (mi != mapBlockIndex.end())
\r
1284 Set((*mi).second);
\r
1287 IMPLEMENT_SERIALIZE
\r
1289 if (!(nType & SER_GETHASH))
\r
1290 READWRITE(nVersion);
\r
1294 void Set(const CBlockIndex* pindex)
\r
1300 vHave.push_back(pindex->GetBlockHash());
\r
1302 // Exponentially larger steps back
\r
1303 for (int i = 0; pindex && i < nStep; i++)
\r
1304 pindex = pindex->pprev;
\r
1305 if (vHave.size() > 10)
\r
1308 vHave.push_back(hashGenesisBlock);
\r
1311 int GetDistanceBack()
\r
1313 // Retrace how far back it was in the sender's branch
\r
1314 int nDistance = 0;
\r
1316 foreach(const uint256& hash, vHave)
\r
1318 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1319 if (mi != mapBlockIndex.end())
\r
1321 CBlockIndex* pindex = (*mi).second;
\r
1322 if (pindex->IsInMainChain())
\r
1325 nDistance += nStep;
\r
1326 if (nDistance > 10)
\r
1332 CBlockIndex* GetBlockIndex()
\r
1334 // Find the first block the caller has in the main chain
\r
1335 foreach(const uint256& hash, vHave)
\r
1337 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1338 if (mi != mapBlockIndex.end())
\r
1340 CBlockIndex* pindex = (*mi).second;
\r
1341 if (pindex->IsInMainChain())
\r
1345 return pindexGenesisBlock;
\r
1348 uint256 GetBlockHash()
\r
1350 // Find the first block the caller has in the main chain
\r
1351 foreach(const uint256& hash, vHave)
\r
1353 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1354 if (mi != mapBlockIndex.end())
\r
1356 CBlockIndex* pindex = (*mi).second;
\r
1357 if (pindex->IsInMainChain())
\r
1361 return hashGenesisBlock;
\r
1366 CBlockIndex* pindex = GetBlockIndex();
\r
1369 return pindex->nHeight;
\r
1379 // Private key that includes an expiration date in case it never gets used.
\r
1384 CPrivKey vchPrivKey;
\r
1385 int64 nTimeCreated;
\r
1386 int64 nTimeExpires;
\r
1387 string strComment;
\r
1388 //// todo: add something to note what created it (user, getnewaddress, change)
\r
1389 //// maybe should have a map<string, string> property map
\r
1391 CWalletKey(int64 nTimeExpiresIn=0)
\r
1393 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
\r
1394 nTimeExpires = nTimeExpiresIn;
\r
1397 IMPLEMENT_SERIALIZE
\r
1399 if (!(nType & SER_GETHASH))
\r
1400 READWRITE(nVersion);
\r
1401 READWRITE(vchPrivKey);
\r
1402 READWRITE(nTimeCreated);
\r
1403 READWRITE(nTimeExpires);
\r
1404 READWRITE(strComment);
\r
1413 extern map<uint256, CTransaction> mapTransactions;
\r
1414 extern map<uint256, CWalletTx> mapWallet;
\r
1415 extern vector<uint256> vWalletUpdated;
\r
1416 extern CCriticalSection cs_mapWallet;
\r
1417 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1418 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1419 extern CCriticalSection cs_mapKeys;
\r
1420 extern CKey keyUser;
\r