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 unsigned int MAX_BLOCK_SIZE = 1000000;
\r
19 static const int64 COIN = 100000000;
\r
20 static const int64 CENT = 1000000;
\r
21 static const int64 MAX_MONEY = 21000000 * COIN;
\r
22 static const int COINBASE_MATURITY = 100;
\r
24 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
\r
31 extern CCriticalSection cs_main;
\r
32 extern map<uint256, CBlockIndex*> mapBlockIndex;
\r
33 extern const uint256 hashGenesisBlock;
\r
34 extern CBlockIndex* pindexGenesisBlock;
\r
35 extern int nBestHeight;
\r
36 extern CBigNum bnBestChainWork;
\r
37 extern CBigNum bnBestInvalidWork;
\r
38 extern uint256 hashBestChain;
\r
39 extern CBlockIndex* pindexBest;
\r
40 extern unsigned int nTransactionsUpdated;
\r
41 extern map<uint256, int> mapRequestCount;
\r
42 extern CCriticalSection cs_mapRequestCount;
\r
43 extern map<string, string> mapAddressBook;
\r
44 extern CCriticalSection cs_mapAddressBook;
\r
45 extern vector<unsigned char> vchDefaultKey;
\r
46 extern double dHashesPerSec;
\r
47 extern int64 nHPSTimerStart;
\r
50 extern int fGenerateBitcoins;
\r
51 extern int64 nTransactionFee;
\r
52 extern CAddress addrIncoming;
\r
53 extern int fLimitProcessors;
\r
54 extern int nLimitProcessors;
\r
55 extern int fMinimizeToTray;
\r
56 extern int fMinimizeOnClose;
\r
64 bool CheckDiskSpace(int64 nAdditionalBytes=0);
\r
65 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
\r
66 FILE* AppendBlockFile(unsigned int& nFileRet);
\r
67 bool AddKey(const CKey& key);
\r
68 vector<unsigned char> GenerateNewKey();
\r
69 bool AddToWallet(const CWalletTx& wtxIn);
\r
70 void WalletUpdateSpent(const COutPoint& prevout);
\r
71 void ReacceptWalletTransactions();
\r
72 bool LoadBlockIndex(bool fAllowNew=true);
\r
73 void PrintBlockTree();
\r
74 bool ProcessMessages(CNode* pfrom);
\r
75 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
76 bool SendMessages(CNode* pto, bool fSendTrickle);
\r
78 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
79 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);
\r
80 bool BroadcastTransaction(CWalletTx& wtxNew);
\r
81 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
\r
82 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
\r
83 void GenerateBitcoins(bool fGenerate);
\r
84 void ThreadBitcoinMiner(void* parg);
\r
85 void BitcoinMiner();
\r
86 bool IsInitialBlockDownload();
\r
103 unsigned int nFile;
\r
104 unsigned int nBlockPos;
\r
105 unsigned int nTxPos;
\r
112 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
115 nBlockPos = nBlockPosIn;
\r
119 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
120 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
121 bool IsNull() const { return (nFile == -1); }
\r
123 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
125 return (a.nFile == b.nFile &&
\r
126 a.nBlockPos == b.nBlockPos &&
\r
127 a.nTxPos == b.nTxPos);
\r
130 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
135 string ToString() const
\r
138 return strprintf("null");
\r
140 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
145 printf("%s", ToString().c_str());
\r
158 CInPoint() { SetNull(); }
\r
159 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
160 void SetNull() { ptx = NULL; n = -1; }
\r
161 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
173 COutPoint() { SetNull(); }
\r
174 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
175 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
176 void SetNull() { hash = 0; n = -1; }
\r
177 bool IsNull() const { return (hash == 0 && n == -1); }
\r
179 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
181 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
184 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
186 return (a.hash == b.hash && a.n == b.n);
\r
189 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
194 string ToString() const
\r
196 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
201 printf("%s\n", ToString().c_str());
\r
209 // An input of a transaction. It contains the location of the previous
\r
210 // transaction's output that it claims and a signature that matches the
\r
211 // output's public key.
\r
218 unsigned int nSequence;
\r
222 nSequence = UINT_MAX;
\r
225 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
227 prevout = prevoutIn;
\r
228 scriptSig = scriptSigIn;
\r
229 nSequence = nSequenceIn;
\r
232 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
234 prevout = COutPoint(hashPrevTx, nOut);
\r
235 scriptSig = scriptSigIn;
\r
236 nSequence = nSequenceIn;
\r
239 IMPLEMENT_SERIALIZE
\r
241 READWRITE(prevout);
\r
242 READWRITE(scriptSig);
\r
243 READWRITE(nSequence);
\r
246 bool IsFinal() const
\r
248 return (nSequence == UINT_MAX);
\r
251 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
253 return (a.prevout == b.prevout &&
\r
254 a.scriptSig == b.scriptSig &&
\r
255 a.nSequence == b.nSequence);
\r
258 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
263 string ToString() const
\r
266 str += strprintf("CTxIn(");
\r
267 str += prevout.ToString();
\r
268 if (prevout.IsNull())
\r
269 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
271 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
272 if (nSequence != UINT_MAX)
\r
273 str += strprintf(", nSequence=%u", nSequence);
\r
280 printf("%s\n", ToString().c_str());
\r
283 bool IsMine() const;
\r
284 int64 GetDebit() const;
\r
291 // An output of a transaction. It contains the public key that the next input
\r
292 // must be able to sign with to claim it.
\r
298 CScript scriptPubKey;
\r
306 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
309 scriptPubKey = scriptPubKeyIn;
\r
312 IMPLEMENT_SERIALIZE
\r
315 READWRITE(scriptPubKey);
\r
321 scriptPubKey.clear();
\r
326 return (nValue == -1);
\r
329 uint256 GetHash() const
\r
331 return SerializeHash(*this);
\r
334 bool IsMine() const
\r
336 return ::IsMine(scriptPubKey);
\r
339 int64 GetCredit() const
\r
346 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
348 return (a.nValue == b.nValue &&
\r
349 a.scriptPubKey == b.scriptPubKey);
\r
352 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
357 string ToString() const
\r
359 if (scriptPubKey.size() < 6)
\r
360 return "CTxOut(error)";
\r
361 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
366 printf("%s\n", ToString().c_str());
\r
374 // The basic transaction that is broadcasted on the network and contained in
\r
375 // blocks. A transaction can contain multiple inputs and outputs.
\r
382 vector<CTxOut> vout;
\r
383 unsigned int nLockTime;
\r
391 IMPLEMENT_SERIALIZE
\r
393 READWRITE(this->nVersion);
\r
394 nVersion = this->nVersion;
\r
397 READWRITE(nLockTime);
\r
408 bool IsNull() const
\r
410 return (vin.empty() && vout.empty());
\r
413 uint256 GetHash() const
\r
415 return SerializeHash(*this);
\r
418 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
\r
420 // Time based nLockTime implemented in 0.1.6
\r
421 if (nLockTime == 0)
\r
423 if (nBlockHeight == 0)
\r
424 nBlockHeight = nBestHeight;
\r
425 if (nBlockTime == 0)
\r
426 nBlockTime = GetAdjustedTime();
\r
427 if (nLockTime < (nLockTime < 500000000 ? nBlockHeight : nBlockTime))
\r
429 foreach(const CTxIn& txin, vin)
\r
430 if (!txin.IsFinal())
\r
435 bool IsNewerThan(const CTransaction& old) const
\r
437 if (vin.size() != old.vin.size())
\r
439 for (int i = 0; i < vin.size(); i++)
\r
440 if (vin[i].prevout != old.vin[i].prevout)
\r
443 bool fNewer = false;
\r
444 unsigned int nLowest = UINT_MAX;
\r
445 for (int i = 0; i < vin.size(); i++)
\r
447 if (vin[i].nSequence != old.vin[i].nSequence)
\r
449 if (vin[i].nSequence <= nLowest)
\r
452 nLowest = vin[i].nSequence;
\r
454 if (old.vin[i].nSequence < nLowest)
\r
457 nLowest = old.vin[i].nSequence;
\r
464 bool IsCoinBase() const
\r
466 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
469 bool CheckTransaction() const
\r
471 // Basic checks that don't depend on any context
\r
472 if (vin.empty() || vout.empty())
\r
473 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
475 // Check for negative or overflow output values
\r
476 int64 nValueOut = 0;
\r
477 foreach(const CTxOut& txout, vout)
\r
479 if (txout.nValue < 0)
\r
480 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
481 if (txout.nValue > MAX_MONEY)
\r
482 return error("CTransaction::CheckTransaction() : txout.nValue too high");
\r
483 nValueOut += txout.nValue;
\r
484 if (nValueOut > MAX_MONEY)
\r
485 return error("CTransaction::CheckTransaction() : txout total too high");
\r
490 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
491 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
495 foreach(const CTxIn& txin, vin)
\r
496 if (txin.prevout.IsNull())
\r
497 return error("CTransaction::CheckTransaction() : prevout is null");
\r
503 bool IsMine() const
\r
505 foreach(const CTxOut& txout, vout)
\r
506 if (txout.IsMine())
\r
511 int64 GetDebit() const
\r
514 foreach(const CTxIn& txin, vin)
\r
515 nDebit += txin.GetDebit();
\r
519 int64 GetCredit() const
\r
522 foreach(const CTxOut& txout, vout)
\r
523 nCredit += txout.GetCredit();
\r
527 int64 GetValueOut() const
\r
529 int64 nValueOut = 0;
\r
530 foreach(const CTxOut& txout, vout)
\r
532 if (txout.nValue < 0)
\r
533 throw runtime_error("CTransaction::GetValueOut() : negative value");
\r
534 nValueOut += txout.nValue;
\r
539 int64 GetMinFee(unsigned int nBlockSize=1) const
\r
541 // Base fee is 1 cent per kilobyte
\r
542 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
543 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
545 // Transactions under 60K are free as long as block size is under 80K
\r
546 // (about 27,000bc if made of 50bc inputs)
\r
547 if (nBytes < 60000 && nBlockSize < 80000)
\r
550 // Transactions under 3K are free as long as block size is under 200K
\r
551 if (nBytes < 3000 && nBlockSize < 200000)
\r
554 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
555 if (nMinFee < CENT)
\r
556 foreach(const CTxOut& txout, vout)
\r
557 if (txout.nValue < CENT)
\r
565 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
567 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
569 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
571 // Read transaction
\r
572 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
573 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
576 // Return file pointer
\r
579 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
580 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
581 *pfileRet = filein.release();
\r
587 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
589 return (a.nVersion == b.nVersion &&
\r
591 a.vout == b.vout &&
\r
592 a.nLockTime == b.nLockTime);
\r
595 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
601 string ToString() const
\r
604 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
605 GetHash().ToString().substr(0,6).c_str(),
\r
610 for (int i = 0; i < vin.size(); i++)
\r
611 str += " " + vin[i].ToString() + "\n";
\r
612 for (int i = 0; i < vout.size(); i++)
\r
613 str += " " + vout[i].ToString() + "\n";
\r
619 printf("%s", ToString().c_str());
\r
624 bool DisconnectInputs(CTxDB& txdb);
\r
625 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
\r
626 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
627 bool ClientConnectInputs();
\r
629 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
631 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
634 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
638 bool AddToMemoryPool();
\r
640 bool RemoveFromMemoryPool();
\r
648 // A transaction with a merkle branch linking it to the block chain
\r
650 class CMerkleTx : public CTransaction
\r
654 vector<uint256> vMerkleBranch;
\r
658 mutable bool fMerkleVerified;
\r
659 mutable bool fGetCreditCached;
\r
660 mutable int64 nGetCreditCached;
\r
668 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
677 fMerkleVerified = false;
\r
678 fGetCreditCached = false;
\r
679 nGetCreditCached = 0;
\r
682 IMPLEMENT_SERIALIZE
\r
684 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
685 nVersion = this->nVersion;
\r
686 READWRITE(hashBlock);
\r
687 READWRITE(vMerkleBranch);
\r
691 int64 GetCredit(bool fUseCache=false) const
\r
693 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
694 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
697 // GetBalance can assume transactions in mapWallet won't change
\r
698 if (fUseCache && fGetCreditCached)
\r
699 return nGetCreditCached;
\r
700 nGetCreditCached = CTransaction::GetCredit();
\r
701 fGetCreditCached = true;
\r
702 return nGetCreditCached;
\r
706 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
707 int GetDepthInMainChain(int& nHeightRet) const;
\r
708 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
\r
709 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
710 int GetBlocksToMaturity() const;
\r
711 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
712 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
719 // A transaction with a bunch of additional info that only the owner cares
\r
720 // about. It includes any unrecorded transactions needed to link it back
\r
721 // to the block chain.
\r
723 class CWalletTx : public CMerkleTx
\r
726 vector<CMerkleTx> vtxPrev;
\r
727 map<string, string> mapValue;
\r
728 vector<pair<string, string> > vOrderForm;
\r
729 unsigned int fTimeReceivedIsTxTime;
\r
730 unsigned int nTimeReceived; // time received by this node
\r
733 //// probably need to sign the order info so know it came from payer
\r
735 // memory only UI hints
\r
736 mutable unsigned int nTimeDisplayed;
\r
737 mutable int nLinesDisplayed;
\r
745 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
750 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
757 fTimeReceivedIsTxTime = false;
\r
761 nTimeDisplayed = 0;
\r
762 nLinesDisplayed = 0;
\r
765 IMPLEMENT_SERIALIZE
\r
767 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
768 nVersion = this->nVersion;
\r
769 READWRITE(vtxPrev);
\r
770 READWRITE(mapValue);
\r
771 READWRITE(vOrderForm);
\r
772 READWRITE(fTimeReceivedIsTxTime);
\r
773 READWRITE(nTimeReceived);
\r
774 READWRITE(fFromMe);
\r
780 return CWalletDB().WriteTx(GetHash(), *this);
\r
784 int64 GetTxTime() const;
\r
785 int GetRequestCount() const;
\r
787 void AddSupportingTransactions(CTxDB& txdb);
\r
789 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
790 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
792 void RelayWalletTransaction(CTxDB& txdb);
\r
793 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
800 // A txdb record that contains the disk location of a transaction and the
\r
801 // locations of transactions that spend its outputs. vSpent is really only
\r
802 // used as a flag, but having the location is very helpful for debugging.
\r
808 vector<CDiskTxPos> vSpent;
\r
815 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
818 vSpent.resize(nOutputs);
\r
821 IMPLEMENT_SERIALIZE
\r
823 if (!(nType & SER_GETHASH))
\r
824 READWRITE(nVersion);
\r
837 return pos.IsNull();
\r
840 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
842 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
844 for (int i = 0; i < a.vSpent.size(); i++)
\r
845 if (a.vSpent[i] != b.vSpent[i])
\r
850 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
861 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
862 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
863 // requirements. When they solve the proof-of-work, they broadcast the block
\r
864 // to everyone and the block is added to the block chain. The first transaction
\r
865 // in the block is a special one that creates a new coin owned by the creator
\r
868 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
869 // is indexed by CBlockIndex objects in memory.
\r
876 uint256 hashPrevBlock;
\r
877 uint256 hashMerkleRoot;
\r
878 unsigned int nTime;
\r
879 unsigned int nBits;
\r
880 unsigned int nNonce;
\r
882 // network and disk
\r
883 vector<CTransaction> vtx;
\r
886 mutable vector<uint256> vMerkleTree;
\r
894 IMPLEMENT_SERIALIZE
\r
896 READWRITE(this->nVersion);
\r
897 nVersion = this->nVersion;
\r
898 READWRITE(hashPrevBlock);
\r
899 READWRITE(hashMerkleRoot);
\r
904 // ConnectBlock depends on vtx being last so it can calculate offset
\r
905 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
908 const_cast<CBlock*>(this)->vtx.clear();
\r
915 hashMerkleRoot = 0;
\r
920 vMerkleTree.clear();
\r
923 bool IsNull() const
\r
925 return (nBits == 0);
\r
928 uint256 GetHash() const
\r
930 return Hash(BEGIN(nVersion), END(nNonce));
\r
934 uint256 BuildMerkleTree() const
\r
936 vMerkleTree.clear();
\r
937 foreach(const CTransaction& tx, vtx)
\r
938 vMerkleTree.push_back(tx.GetHash());
\r
940 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
942 for (int i = 0; i < nSize; i += 2)
\r
944 int i2 = min(i+1, nSize-1);
\r
945 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
946 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
950 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
953 vector<uint256> GetMerkleBranch(int nIndex) const
\r
955 if (vMerkleTree.empty())
\r
957 vector<uint256> vMerkleBranch;
\r
959 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
961 int i = min(nIndex^1, nSize-1);
\r
962 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
966 return vMerkleBranch;
\r
969 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
973 foreach(const uint256& otherside, vMerkleBranch)
\r
976 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
978 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
985 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
987 // Open history file to append
\r
988 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
990 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
991 if (!fWriteTransactions)
\r
992 fileout.nType |= SER_BLOCKHEADERONLY;
\r
994 // Write index header
\r
995 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
996 fileout << FLATDATA(pchMessageStart) << nSize;
\r
999 nBlockPosRet = ftell(fileout);
\r
1000 if (nBlockPosRet == -1)
\r
1001 return error("CBlock::WriteToDisk() : ftell failed");
\r
1004 // Flush stdio buffers and commit to disk before returning
\r
1006 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
\r
1009 _commit(_fileno(fileout));
\r
1011 fsync(fileno(fileout));
\r
1018 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
\r
1022 // Open history file to read
\r
1023 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
1025 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
1026 if (!fReadTransactions)
\r
1027 filein.nType |= SER_BLOCKHEADERONLY;
\r
1032 // Check the header
\r
1033 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
1034 return error("CBlock::ReadFromDisk() : nBits errors in block header");
\r
1035 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
1036 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
\r
1043 void print() const
\r
1045 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
1046 GetHash().ToString().substr(0,16).c_str(),
\r
1048 hashPrevBlock.ToString().substr(0,16).c_str(),
\r
1049 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1050 nTime, nBits, nNonce,
\r
1052 for (int i = 0; i < vtx.size(); i++)
\r
1057 printf(" vMerkleTree: ");
\r
1058 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1059 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1064 int64 GetBlockValue(int nHeight, int64 nFees) const;
\r
1065 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1066 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1067 bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);
\r
1068 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1069 bool CheckBlock() const;
\r
1070 bool AcceptBlock();
\r
1079 // The block chain is a tree shaped structure starting with the
\r
1080 // genesis block at the root, with each block potentially having multiple
\r
1081 // candidates to be the next block. pprev and pnext link a path through the
\r
1082 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1083 // to it, but pnext will only point forward to the longest branch, or will
\r
1084 // be null if the block is not part of the longest chain.
\r
1089 const uint256* phashBlock;
\r
1090 CBlockIndex* pprev;
\r
1091 CBlockIndex* pnext;
\r
1092 unsigned int nFile;
\r
1093 unsigned int nBlockPos;
\r
1095 CBigNum bnChainWork;
\r
1099 uint256 hashMerkleRoot;
\r
1100 unsigned int nTime;
\r
1101 unsigned int nBits;
\r
1102 unsigned int nNonce;
\r
1107 phashBlock = NULL;
\r
1116 hashMerkleRoot = 0;
\r
1122 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1124 phashBlock = NULL;
\r
1128 nBlockPos = nBlockPosIn;
\r
1132 nVersion = block.nVersion;
\r
1133 hashMerkleRoot = block.hashMerkleRoot;
\r
1134 nTime = block.nTime;
\r
1135 nBits = block.nBits;
\r
1136 nNonce = block.nNonce;
\r
1139 uint256 GetBlockHash() const
\r
1141 return *phashBlock;
\r
1144 CBigNum GetBlockWork() const
\r
1146 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);
\r
1149 bool IsInMainChain() const
\r
1151 return (pnext || this == pindexBest);
\r
1154 bool EraseBlockFromDisk()
\r
1156 // Open history file
\r
1157 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1161 // Overwrite with empty null block
\r
1169 enum { nMedianTimeSpan=11 };
\r
1171 int64 GetMedianTimePast() const
\r
1173 unsigned int pmedian[nMedianTimeSpan];
\r
1174 unsigned int* pbegin = &pmedian[nMedianTimeSpan];
\r
1175 unsigned int* pend = &pmedian[nMedianTimeSpan];
\r
1177 const CBlockIndex* pindex = this;
\r
1178 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1179 *(--pbegin) = pindex->nTime;
\r
1181 sort(pbegin, pend);
\r
1182 return pbegin[(pend - pbegin)/2];
\r
1185 int64 GetMedianTime() const
\r
1187 const CBlockIndex* pindex = this;
\r
1188 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1190 if (!pindex->pnext)
\r
1192 pindex = pindex->pnext;
\r
1194 return pindex->GetMedianTimePast();
\r
1199 string ToString() const
\r
1201 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1202 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1203 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1204 GetBlockHash().ToString().substr(0,16).c_str());
\r
1207 void print() const
\r
1209 printf("%s\n", ToString().c_str());
\r
1216 // Used to marshal pointers into hashes for db storage.
\r
1218 class CDiskBlockIndex : public CBlockIndex
\r
1230 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1232 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1233 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1236 IMPLEMENT_SERIALIZE
\r
1238 if (!(nType & SER_GETHASH))
\r
1239 READWRITE(nVersion);
\r
1241 READWRITE(hashNext);
\r
1243 READWRITE(nBlockPos);
\r
1244 READWRITE(nHeight);
\r
1247 READWRITE(this->nVersion);
\r
1248 READWRITE(hashPrev);
\r
1249 READWRITE(hashMerkleRoot);
\r
1252 READWRITE(nNonce);
\r
1255 uint256 GetBlockHash() const
\r
1258 block.nVersion = nVersion;
\r
1259 block.hashPrevBlock = hashPrev;
\r
1260 block.hashMerkleRoot = hashMerkleRoot;
\r
1261 block.nTime = nTime;
\r
1262 block.nBits = nBits;
\r
1263 block.nNonce = nNonce;
\r
1264 return block.GetHash();
\r
1268 string ToString() const
\r
1270 string str = "CDiskBlockIndex(";
\r
1271 str += CBlockIndex::ToString();
\r
1272 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1273 GetBlockHash().ToString().c_str(),
\r
1274 hashPrev.ToString().substr(0,16).c_str(),
\r
1275 hashNext.ToString().substr(0,16).c_str());
\r
1279 void print() const
\r
1281 printf("%s\n", ToString().c_str());
\r
1293 // Describes a place in the block chain to another node such that if the
\r
1294 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1295 // The further back it is, the further before the fork it may be.
\r
1297 class CBlockLocator
\r
1300 vector<uint256> vHave;
\r
1307 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1312 explicit CBlockLocator(uint256 hashBlock)
\r
1314 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1315 if (mi != mapBlockIndex.end())
\r
1316 Set((*mi).second);
\r
1319 IMPLEMENT_SERIALIZE
\r
1321 if (!(nType & SER_GETHASH))
\r
1322 READWRITE(nVersion);
\r
1326 void Set(const CBlockIndex* pindex)
\r
1332 vHave.push_back(pindex->GetBlockHash());
\r
1334 // Exponentially larger steps back
\r
1335 for (int i = 0; pindex && i < nStep; i++)
\r
1336 pindex = pindex->pprev;
\r
1337 if (vHave.size() > 10)
\r
1340 vHave.push_back(hashGenesisBlock);
\r
1343 int GetDistanceBack()
\r
1345 // Retrace how far back it was in the sender's branch
\r
1346 int nDistance = 0;
\r
1348 foreach(const uint256& hash, vHave)
\r
1350 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1351 if (mi != mapBlockIndex.end())
\r
1353 CBlockIndex* pindex = (*mi).second;
\r
1354 if (pindex->IsInMainChain())
\r
1357 nDistance += nStep;
\r
1358 if (nDistance > 10)
\r
1364 CBlockIndex* GetBlockIndex()
\r
1366 // Find the first block the caller has in the main chain
\r
1367 foreach(const uint256& hash, vHave)
\r
1369 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1370 if (mi != mapBlockIndex.end())
\r
1372 CBlockIndex* pindex = (*mi).second;
\r
1373 if (pindex->IsInMainChain())
\r
1377 return pindexGenesisBlock;
\r
1380 uint256 GetBlockHash()
\r
1382 // Find the first block the caller has in the main chain
\r
1383 foreach(const uint256& hash, vHave)
\r
1385 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1386 if (mi != mapBlockIndex.end())
\r
1388 CBlockIndex* pindex = (*mi).second;
\r
1389 if (pindex->IsInMainChain())
\r
1393 return hashGenesisBlock;
\r
1398 CBlockIndex* pindex = GetBlockIndex();
\r
1401 return pindex->nHeight;
\r
1411 // Private key that includes an expiration date in case it never gets used.
\r
1416 CPrivKey vchPrivKey;
\r
1417 int64 nTimeCreated;
\r
1418 int64 nTimeExpires;
\r
1419 string strComment;
\r
1420 //// todo: add something to note what created it (user, getnewaddress, change)
\r
1421 //// maybe should have a map<string, string> property map
\r
1423 CWalletKey(int64 nTimeExpiresIn=0)
\r
1425 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
\r
1426 nTimeExpires = nTimeExpiresIn;
\r
1429 IMPLEMENT_SERIALIZE
\r
1431 if (!(nType & SER_GETHASH))
\r
1432 READWRITE(nVersion);
\r
1433 READWRITE(vchPrivKey);
\r
1434 READWRITE(nTimeCreated);
\r
1435 READWRITE(nTimeExpires);
\r
1436 READWRITE(strComment);
\r
1445 extern map<uint256, CTransaction> mapTransactions;
\r
1446 extern map<uint256, CWalletTx> mapWallet;
\r
1447 extern vector<uint256> vWalletUpdated;
\r
1448 extern CCriticalSection cs_mapWallet;
\r
1449 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1450 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1451 extern CCriticalSection cs_mapKeys;
\r
1452 extern CKey keyUser;
\r