Add branch README.md
[bitcoinplatinum.git] / main.h
blob0082d5d065b6fac187445eaca4fb52969e72cd42
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 class COutPoint;
6 class CInPoint;
7 class CDiskTxPos;
8 class CCoinBase;
9 class CTxIn;
10 class CTxOut;
11 class CTransaction;
12 class CBlock;
13 class CBlockIndex;
14 class CWalletTx;
15 class CKeyItem;
17 static const unsigned int MAX_BLOCK_SIZE = 1000000;
18 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
19 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
20 static const int64 COIN = 100000000;
21 static const int64 CENT = 1000000;
22 static const int64 MAX_MONEY = 21000000 * COIN;
23 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
24 static const int COINBASE_MATURITY = 100;
25 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
32 extern CCriticalSection cs_main;
33 extern map<uint256, CBlockIndex*> mapBlockIndex;
34 extern const uint256 hashGenesisBlock;
35 extern CBlockIndex* pindexGenesisBlock;
36 extern int nBestHeight;
37 extern CBigNum bnBestChainWork;
38 extern CBigNum bnBestInvalidWork;
39 extern uint256 hashBestChain;
40 extern CBlockIndex* pindexBest;
41 extern unsigned int nTransactionsUpdated;
42 extern map<uint256, int> mapRequestCount;
43 extern CCriticalSection cs_mapRequestCount;
44 extern map<string, string> mapAddressBook;
45 extern CCriticalSection cs_mapAddressBook;
46 extern vector<unsigned char> vchDefaultKey;
47 extern double dHashesPerSec;
48 extern int64 nHPSTimerStart;
50 // Settings
51 extern int fGenerateBitcoins;
52 extern int64 nTransactionFee;
53 extern CAddress addrIncoming;
54 extern int fLimitProcessors;
55 extern int nLimitProcessors;
56 extern int fMinimizeToTray;
57 extern int fMinimizeOnClose;
65 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
66 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
67 FILE* AppendBlockFile(unsigned int& nFileRet);
68 bool AddKey(const CKey& key);
69 vector<unsigned char> GenerateNewKey();
70 bool AddToWallet(const CWalletTx& wtxIn);
71 void WalletUpdateSpent(const COutPoint& prevout);
72 void ReacceptWalletTransactions();
73 bool LoadBlockIndex(bool fAllowNew=true);
74 void PrintBlockTree();
75 bool ProcessMessages(CNode* pfrom);
76 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
77 bool SendMessages(CNode* pto, bool fSendTrickle);
78 int64 GetBalance();
79 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
80 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);
81 bool BroadcastTransaction(CWalletTx& wtxNew);
82 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
83 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
84 void GenerateBitcoins(bool fGenerate);
85 void ThreadBitcoinMiner(void* parg);
86 void BitcoinMiner();
87 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
88 bool IsInitialBlockDownload();
89 string GetWarnings(string strFor);
102 class CDiskTxPos
104 public:
105 unsigned int nFile;
106 unsigned int nBlockPos;
107 unsigned int nTxPos;
109 CDiskTxPos()
111 SetNull();
114 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
116 nFile = nFileIn;
117 nBlockPos = nBlockPosIn;
118 nTxPos = nTxPosIn;
121 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
122 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
123 bool IsNull() const { return (nFile == -1); }
125 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
127 return (a.nFile == b.nFile &&
128 a.nBlockPos == b.nBlockPos &&
129 a.nTxPos == b.nTxPos);
132 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
134 return !(a == b);
137 string ToString() const
139 if (IsNull())
140 return strprintf("null");
141 else
142 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
145 void print() const
147 printf("%s", ToString().c_str());
154 class CInPoint
156 public:
157 CTransaction* ptx;
158 unsigned int n;
160 CInPoint() { SetNull(); }
161 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
162 void SetNull() { ptx = NULL; n = -1; }
163 bool IsNull() const { return (ptx == NULL && n == -1); }
169 class COutPoint
171 public:
172 uint256 hash;
173 unsigned int n;
175 COutPoint() { SetNull(); }
176 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
177 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
178 void SetNull() { hash = 0; n = -1; }
179 bool IsNull() const { return (hash == 0 && n == -1); }
181 friend bool operator<(const COutPoint& a, const COutPoint& b)
183 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
186 friend bool operator==(const COutPoint& a, const COutPoint& b)
188 return (a.hash == b.hash && a.n == b.n);
191 friend bool operator!=(const COutPoint& a, const COutPoint& b)
193 return !(a == b);
196 string ToString() const
198 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
201 void print() const
203 printf("%s\n", ToString().c_str());
211 // An input of a transaction. It contains the location of the previous
212 // transaction's output that it claims and a signature that matches the
213 // output's public key.
215 class CTxIn
217 public:
218 COutPoint prevout;
219 CScript scriptSig;
220 unsigned int nSequence;
222 CTxIn()
224 nSequence = UINT_MAX;
227 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
229 prevout = prevoutIn;
230 scriptSig = scriptSigIn;
231 nSequence = nSequenceIn;
234 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
236 prevout = COutPoint(hashPrevTx, nOut);
237 scriptSig = scriptSigIn;
238 nSequence = nSequenceIn;
241 IMPLEMENT_SERIALIZE
243 READWRITE(prevout);
244 READWRITE(scriptSig);
245 READWRITE(nSequence);
248 bool IsFinal() const
250 return (nSequence == UINT_MAX);
253 friend bool operator==(const CTxIn& a, const CTxIn& b)
255 return (a.prevout == b.prevout &&
256 a.scriptSig == b.scriptSig &&
257 a.nSequence == b.nSequence);
260 friend bool operator!=(const CTxIn& a, const CTxIn& b)
262 return !(a == b);
265 string ToString() const
267 string str;
268 str += strprintf("CTxIn(");
269 str += prevout.ToString();
270 if (prevout.IsNull())
271 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
272 else
273 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
274 if (nSequence != UINT_MAX)
275 str += strprintf(", nSequence=%u", nSequence);
276 str += ")";
277 return str;
280 void print() const
282 printf("%s\n", ToString().c_str());
285 bool IsMine() const;
286 int64 GetDebit() const;
293 // An output of a transaction. It contains the public key that the next input
294 // must be able to sign with to claim it.
296 class CTxOut
298 public:
299 int64 nValue;
300 CScript scriptPubKey;
302 CTxOut()
304 SetNull();
307 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
309 nValue = nValueIn;
310 scriptPubKey = scriptPubKeyIn;
313 IMPLEMENT_SERIALIZE
315 READWRITE(nValue);
316 READWRITE(scriptPubKey);
319 void SetNull()
321 nValue = -1;
322 scriptPubKey.clear();
325 bool IsNull()
327 return (nValue == -1);
330 uint256 GetHash() const
332 return SerializeHash(*this);
335 bool IsMine() const
337 return ::IsMine(scriptPubKey);
340 int64 GetCredit() const
342 if (!MoneyRange(nValue))
343 throw runtime_error("CTxOut::GetCredit() : value out of range");
344 if (IsMine())
345 return nValue;
346 return 0;
349 friend bool operator==(const CTxOut& a, const CTxOut& b)
351 return (a.nValue == b.nValue &&
352 a.scriptPubKey == b.scriptPubKey);
355 friend bool operator!=(const CTxOut& a, const CTxOut& b)
357 return !(a == b);
360 string ToString() const
362 if (scriptPubKey.size() < 6)
363 return "CTxOut(error)";
364 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
367 void print() const
369 printf("%s\n", ToString().c_str());
377 // The basic transaction that is broadcasted on the network and contained in
378 // blocks. A transaction can contain multiple inputs and outputs.
380 class CTransaction
382 public:
383 int nVersion;
384 vector<CTxIn> vin;
385 vector<CTxOut> vout;
386 unsigned int nLockTime;
389 CTransaction()
391 SetNull();
394 IMPLEMENT_SERIALIZE
396 READWRITE(this->nVersion);
397 nVersion = this->nVersion;
398 READWRITE(vin);
399 READWRITE(vout);
400 READWRITE(nLockTime);
403 void SetNull()
405 nVersion = 1;
406 vin.clear();
407 vout.clear();
408 nLockTime = 0;
411 bool IsNull() const
413 return (vin.empty() && vout.empty());
416 uint256 GetHash() const
418 return SerializeHash(*this);
421 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
423 // Time based nLockTime implemented in 0.1.6
424 if (nLockTime == 0)
425 return true;
426 if (nBlockHeight == 0)
427 nBlockHeight = nBestHeight;
428 if (nBlockTime == 0)
429 nBlockTime = GetAdjustedTime();
430 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
431 return true;
432 foreach(const CTxIn& txin, vin)
433 if (!txin.IsFinal())
434 return false;
435 return true;
438 bool IsNewerThan(const CTransaction& old) const
440 if (vin.size() != old.vin.size())
441 return false;
442 for (int i = 0; i < vin.size(); i++)
443 if (vin[i].prevout != old.vin[i].prevout)
444 return false;
446 bool fNewer = false;
447 unsigned int nLowest = UINT_MAX;
448 for (int i = 0; i < vin.size(); i++)
450 if (vin[i].nSequence != old.vin[i].nSequence)
452 if (vin[i].nSequence <= nLowest)
454 fNewer = false;
455 nLowest = vin[i].nSequence;
457 if (old.vin[i].nSequence < nLowest)
459 fNewer = true;
460 nLowest = old.vin[i].nSequence;
464 return fNewer;
467 bool IsCoinBase() const
469 return (vin.size() == 1 && vin[0].prevout.IsNull());
472 bool CheckTransaction() const
474 // Basic checks that don't depend on any context
475 if (vin.empty() || vout.empty())
476 return error("CTransaction::CheckTransaction() : vin or vout empty");
478 // Size limits
479 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
480 return error("CTransaction::CheckTransaction() : size limits failed");
482 // Check for negative or overflow output values
483 int64 nValueOut = 0;
484 foreach(const CTxOut& txout, vout)
486 if (txout.nValue < 0)
487 return error("CTransaction::CheckTransaction() : txout.nValue negative");
488 if (txout.nValue > MAX_MONEY)
489 return error("CTransaction::CheckTransaction() : txout.nValue too high");
490 nValueOut += txout.nValue;
491 if (!MoneyRange(nValueOut))
492 return error("CTransaction::CheckTransaction() : txout total out of range");
495 if (IsCoinBase())
497 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
498 return error("CTransaction::CheckTransaction() : coinbase script size");
500 else
502 foreach(const CTxIn& txin, vin)
503 if (txin.prevout.IsNull())
504 return error("CTransaction::CheckTransaction() : prevout is null");
507 return true;
510 int GetSigOpCount() const
512 int n = 0;
513 foreach(const CTxIn& txin, vin)
514 n += txin.scriptSig.GetSigOpCount();
515 foreach(const CTxOut& txout, vout)
516 n += txout.scriptPubKey.GetSigOpCount();
517 return n;
520 bool IsMine() const
522 foreach(const CTxOut& txout, vout)
523 if (txout.IsMine())
524 return true;
525 return false;
528 int64 GetDebit() const
530 int64 nDebit = 0;
531 foreach(const CTxIn& txin, vin)
533 nDebit += txin.GetDebit();
534 if (!MoneyRange(nDebit))
535 throw runtime_error("CTransaction::GetDebit() : value out of range");
537 return nDebit;
540 int64 GetCredit() const
542 int64 nCredit = 0;
543 foreach(const CTxOut& txout, vout)
545 nCredit += txout.GetCredit();
546 if (!MoneyRange(nCredit))
547 throw runtime_error("CTransaction::GetCredit() : value out of range");
549 return nCredit;
552 int64 GetValueOut() const
554 int64 nValueOut = 0;
555 foreach(const CTxOut& txout, vout)
557 nValueOut += txout.nValue;
558 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
559 throw runtime_error("CTransaction::GetValueOut() : value out of range");
561 return nValueOut;
564 int64 GetMinFee(unsigned int nBlockSize=1) const
566 // Base fee is 1 cent per kilobyte
567 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
568 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
570 // Transactions under 60K are free as long as block size is under 80K
571 // (about 27,000bc if made of 50bc inputs)
572 if (nBytes < 60000 && nBlockSize < 80000)
573 nMinFee = 0;
575 // Transactions under 3K are free as long as block size is under 200K
576 if (nBytes < 3000 && nBlockSize < 200000)
577 nMinFee = 0;
579 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
580 if (nMinFee < CENT)
581 foreach(const CTxOut& txout, vout)
582 if (txout.nValue < CENT)
583 nMinFee = CENT;
585 // Raise the price as the block approaches full
586 if (MAX_BLOCK_SIZE/2 <= nBlockSize && nBlockSize < MAX_BLOCK_SIZE)
587 nMinFee *= MAX_BLOCK_SIZE / (MAX_BLOCK_SIZE - nBlockSize);
588 if (!MoneyRange(nMinFee))
589 nMinFee = MAX_MONEY;
591 return nMinFee;
595 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
597 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
598 if (!filein)
599 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
601 // Read transaction
602 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
603 return error("CTransaction::ReadFromDisk() : fseek failed");
604 filein >> *this;
606 // Return file pointer
607 if (pfileRet)
609 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
610 return error("CTransaction::ReadFromDisk() : second fseek failed");
611 *pfileRet = filein.release();
613 return true;
617 friend bool operator==(const CTransaction& a, const CTransaction& b)
619 return (a.nVersion == b.nVersion &&
620 a.vin == b.vin &&
621 a.vout == b.vout &&
622 a.nLockTime == b.nLockTime);
625 friend bool operator!=(const CTransaction& a, const CTransaction& b)
627 return !(a == b);
631 string ToString() const
633 string str;
634 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
635 GetHash().ToString().substr(0,6).c_str(),
636 nVersion,
637 vin.size(),
638 vout.size(),
639 nLockTime);
640 for (int i = 0; i < vin.size(); i++)
641 str += " " + vin[i].ToString() + "\n";
642 for (int i = 0; i < vout.size(); i++)
643 str += " " + vout[i].ToString() + "\n";
644 return str;
647 void print() const
649 printf("%s", ToString().c_str());
654 bool DisconnectInputs(CTxDB& txdb);
655 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
656 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
657 bool ClientConnectInputs();
659 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
661 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
663 CTxDB txdb("r");
664 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
667 protected:
668 bool AddToMemoryPoolUnchecked();
669 public:
670 bool RemoveFromMemoryPool();
678 // A transaction with a merkle branch linking it to the block chain
680 class CMerkleTx : public CTransaction
682 public:
683 uint256 hashBlock;
684 vector<uint256> vMerkleBranch;
685 int nIndex;
687 // memory only
688 mutable bool fMerkleVerified;
689 mutable bool fGetCreditCached;
690 mutable int64 nGetCreditCached;
693 CMerkleTx()
695 Init();
698 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
700 Init();
703 void Init()
705 hashBlock = 0;
706 nIndex = -1;
707 fMerkleVerified = false;
708 fGetCreditCached = false;
709 nGetCreditCached = 0;
712 IMPLEMENT_SERIALIZE
714 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
715 nVersion = this->nVersion;
716 READWRITE(hashBlock);
717 READWRITE(vMerkleBranch);
718 READWRITE(nIndex);
721 int64 GetCredit(bool fUseCache=false) const
723 // Must wait until coinbase is safely deep enough in the chain before valuing it
724 if (IsCoinBase() && GetBlocksToMaturity() > 0)
725 return 0;
727 // GetBalance can assume transactions in mapWallet won't change
728 if (fUseCache && fGetCreditCached)
729 return nGetCreditCached;
730 nGetCreditCached = CTransaction::GetCredit();
731 fGetCreditCached = true;
732 return nGetCreditCached;
736 int SetMerkleBranch(const CBlock* pblock=NULL);
737 int GetDepthInMainChain(int& nHeightRet) const;
738 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
739 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
740 int GetBlocksToMaturity() const;
741 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
742 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
749 // A transaction with a bunch of additional info that only the owner cares
750 // about. It includes any unrecorded transactions needed to link it back
751 // to the block chain.
753 class CWalletTx : public CMerkleTx
755 public:
756 vector<CMerkleTx> vtxPrev;
757 map<string, string> mapValue;
758 vector<pair<string, string> > vOrderForm;
759 unsigned int fTimeReceivedIsTxTime;
760 unsigned int nTimeReceived; // time received by this node
761 char fFromMe;
762 char fSpent;
763 //// probably need to sign the order info so know it came from payer
765 // memory only UI hints
766 mutable unsigned int nTimeDisplayed;
767 mutable int nLinesDisplayed;
770 CWalletTx()
772 Init();
775 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
777 Init();
780 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
782 Init();
785 void Init()
787 fTimeReceivedIsTxTime = false;
788 nTimeReceived = 0;
789 fFromMe = false;
790 fSpent = false;
791 nTimeDisplayed = 0;
792 nLinesDisplayed = 0;
795 IMPLEMENT_SERIALIZE
797 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
798 nVersion = this->nVersion;
799 READWRITE(vtxPrev);
800 READWRITE(mapValue);
801 READWRITE(vOrderForm);
802 READWRITE(fTimeReceivedIsTxTime);
803 READWRITE(nTimeReceived);
804 READWRITE(fFromMe);
805 READWRITE(fSpent);
808 bool WriteToDisk()
810 return CWalletDB().WriteTx(GetHash(), *this);
814 int64 GetTxTime() const;
815 int GetRequestCount() const;
817 void AddSupportingTransactions(CTxDB& txdb);
819 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
820 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
822 void RelayWalletTransaction(CTxDB& txdb);
823 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
830 // A txdb record that contains the disk location of a transaction and the
831 // locations of transactions that spend its outputs. vSpent is really only
832 // used as a flag, but having the location is very helpful for debugging.
834 class CTxIndex
836 public:
837 CDiskTxPos pos;
838 vector<CDiskTxPos> vSpent;
840 CTxIndex()
842 SetNull();
845 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
847 pos = posIn;
848 vSpent.resize(nOutputs);
851 IMPLEMENT_SERIALIZE
853 if (!(nType & SER_GETHASH))
854 READWRITE(nVersion);
855 READWRITE(pos);
856 READWRITE(vSpent);
859 void SetNull()
861 pos.SetNull();
862 vSpent.clear();
865 bool IsNull()
867 return pos.IsNull();
870 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
872 return (a.pos == b.pos &&
873 a.vSpent == b.vSpent);
876 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
878 return !(a == b);
887 // Nodes collect new transactions into a block, hash them into a hash tree,
888 // and scan through nonce values to make the block's hash satisfy proof-of-work
889 // requirements. When they solve the proof-of-work, they broadcast the block
890 // to everyone and the block is added to the block chain. The first transaction
891 // in the block is a special one that creates a new coin owned by the creator
892 // of the block.
894 // Blocks are appended to blk0001.dat files on disk. Their location on disk
895 // is indexed by CBlockIndex objects in memory.
897 class CBlock
899 public:
900 // header
901 int nVersion;
902 uint256 hashPrevBlock;
903 uint256 hashMerkleRoot;
904 unsigned int nTime;
905 unsigned int nBits;
906 unsigned int nNonce;
908 // network and disk
909 vector<CTransaction> vtx;
911 // memory only
912 mutable vector<uint256> vMerkleTree;
915 CBlock()
917 SetNull();
920 IMPLEMENT_SERIALIZE
922 READWRITE(this->nVersion);
923 nVersion = this->nVersion;
924 READWRITE(hashPrevBlock);
925 READWRITE(hashMerkleRoot);
926 READWRITE(nTime);
927 READWRITE(nBits);
928 READWRITE(nNonce);
930 // ConnectBlock depends on vtx being last so it can calculate offset
931 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
932 READWRITE(vtx);
933 else if (fRead)
934 const_cast<CBlock*>(this)->vtx.clear();
937 void SetNull()
939 nVersion = 1;
940 hashPrevBlock = 0;
941 hashMerkleRoot = 0;
942 nTime = 0;
943 nBits = 0;
944 nNonce = 0;
945 vtx.clear();
946 vMerkleTree.clear();
949 bool IsNull() const
951 return (nBits == 0);
954 uint256 GetHash() const
956 return Hash(BEGIN(nVersion), END(nNonce));
959 int64 GetBlockTime() const
961 return (int64)nTime;
964 int GetSigOpCount() const
966 int n = 0;
967 foreach(const CTransaction& tx, vtx)
968 n += tx.GetSigOpCount();
969 return n;
973 uint256 BuildMerkleTree() const
975 vMerkleTree.clear();
976 foreach(const CTransaction& tx, vtx)
977 vMerkleTree.push_back(tx.GetHash());
978 int j = 0;
979 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
981 for (int i = 0; i < nSize; i += 2)
983 int i2 = min(i+1, nSize-1);
984 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
985 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
987 j += nSize;
989 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
992 vector<uint256> GetMerkleBranch(int nIndex) const
994 if (vMerkleTree.empty())
995 BuildMerkleTree();
996 vector<uint256> vMerkleBranch;
997 int j = 0;
998 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1000 int i = min(nIndex^1, nSize-1);
1001 vMerkleBranch.push_back(vMerkleTree[j+i]);
1002 nIndex >>= 1;
1003 j += nSize;
1005 return vMerkleBranch;
1008 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1010 if (nIndex == -1)
1011 return 0;
1012 foreach(const uint256& otherside, vMerkleBranch)
1014 if (nIndex & 1)
1015 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1016 else
1017 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1018 nIndex >>= 1;
1020 return hash;
1024 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1026 // Open history file to append
1027 CAutoFile fileout = AppendBlockFile(nFileRet);
1028 if (!fileout)
1029 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1030 if (!fWriteTransactions)
1031 fileout.nType |= SER_BLOCKHEADERONLY;
1033 // Write index header
1034 unsigned int nSize = fileout.GetSerializeSize(*this);
1035 fileout << FLATDATA(pchMessageStart) << nSize;
1037 // Write block
1038 nBlockPosRet = ftell(fileout);
1039 if (nBlockPosRet == -1)
1040 return error("CBlock::WriteToDisk() : ftell failed");
1041 fileout << *this;
1043 // Flush stdio buffers and commit to disk before returning
1044 fflush(fileout);
1045 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1047 #ifdef __WXMSW__
1048 _commit(_fileno(fileout));
1049 #else
1050 fsync(fileno(fileout));
1051 #endif
1054 return true;
1057 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1059 SetNull();
1061 // Open history file to read
1062 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1063 if (!filein)
1064 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1065 if (!fReadTransactions)
1066 filein.nType |= SER_BLOCKHEADERONLY;
1068 // Read block
1069 filein >> *this;
1071 // Check the header
1072 if (!CheckProofOfWork(GetHash(), nBits))
1073 return error("CBlock::ReadFromDisk() : errors in block header");
1075 return true;
1080 void print() const
1082 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1083 GetHash().ToString().substr(0,20).c_str(),
1084 nVersion,
1085 hashPrevBlock.ToString().substr(0,20).c_str(),
1086 hashMerkleRoot.ToString().substr(0,6).c_str(),
1087 nTime, nBits, nNonce,
1088 vtx.size());
1089 for (int i = 0; i < vtx.size(); i++)
1091 printf(" ");
1092 vtx[i].print();
1094 printf(" vMerkleTree: ");
1095 for (int i = 0; i < vMerkleTree.size(); i++)
1096 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
1097 printf("\n");
1101 int64 GetBlockValue(int nHeight, int64 nFees) const;
1102 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1103 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1104 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1105 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1106 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1107 bool CheckBlock() const;
1108 bool AcceptBlock();
1117 // The block chain is a tree shaped structure starting with the
1118 // genesis block at the root, with each block potentially having multiple
1119 // candidates to be the next block. pprev and pnext link a path through the
1120 // main/longest chain. A blockindex may have multiple pprev pointing back
1121 // to it, but pnext will only point forward to the longest branch, or will
1122 // be null if the block is not part of the longest chain.
1124 class CBlockIndex
1126 public:
1127 const uint256* phashBlock;
1128 CBlockIndex* pprev;
1129 CBlockIndex* pnext;
1130 unsigned int nFile;
1131 unsigned int nBlockPos;
1132 int nHeight;
1133 CBigNum bnChainWork;
1135 // block header
1136 int nVersion;
1137 uint256 hashMerkleRoot;
1138 unsigned int nTime;
1139 unsigned int nBits;
1140 unsigned int nNonce;
1143 CBlockIndex()
1145 phashBlock = NULL;
1146 pprev = NULL;
1147 pnext = NULL;
1148 nFile = 0;
1149 nBlockPos = 0;
1150 nHeight = 0;
1151 bnChainWork = 0;
1153 nVersion = 0;
1154 hashMerkleRoot = 0;
1155 nTime = 0;
1156 nBits = 0;
1157 nNonce = 0;
1160 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1162 phashBlock = NULL;
1163 pprev = NULL;
1164 pnext = NULL;
1165 nFile = nFileIn;
1166 nBlockPos = nBlockPosIn;
1167 nHeight = 0;
1168 bnChainWork = 0;
1170 nVersion = block.nVersion;
1171 hashMerkleRoot = block.hashMerkleRoot;
1172 nTime = block.nTime;
1173 nBits = block.nBits;
1174 nNonce = block.nNonce;
1177 uint256 GetBlockHash() const
1179 return *phashBlock;
1182 int64 GetBlockTime() const
1184 return (int64)nTime;
1187 CBigNum GetBlockWork() const
1189 if (CBigNum().SetCompact(nBits) <= 0)
1190 return 0;
1191 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);
1194 bool IsInMainChain() const
1196 return (pnext || this == pindexBest);
1199 bool CheckIndex() const
1201 return CheckProofOfWork(GetBlockHash(), nBits);
1204 bool EraseBlockFromDisk()
1206 // Open history file
1207 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1208 if (!fileout)
1209 return false;
1211 // Overwrite with empty null block
1212 CBlock block;
1213 block.SetNull();
1214 fileout << block;
1216 return true;
1219 enum { nMedianTimeSpan=11 };
1221 int64 GetMedianTimePast() const
1223 int64 pmedian[nMedianTimeSpan];
1224 int64* pbegin = &pmedian[nMedianTimeSpan];
1225 int64* pend = &pmedian[nMedianTimeSpan];
1227 const CBlockIndex* pindex = this;
1228 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1229 *(--pbegin) = pindex->GetBlockTime();
1231 sort(pbegin, pend);
1232 return pbegin[(pend - pbegin)/2];
1235 int64 GetMedianTime() const
1237 const CBlockIndex* pindex = this;
1238 for (int i = 0; i < nMedianTimeSpan/2; i++)
1240 if (!pindex->pnext)
1241 return GetBlockTime();
1242 pindex = pindex->pnext;
1244 return pindex->GetMedianTimePast();
1249 string ToString() const
1251 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1252 pprev, pnext, nFile, nBlockPos, nHeight,
1253 hashMerkleRoot.ToString().substr(0,6).c_str(),
1254 GetBlockHash().ToString().substr(0,20).c_str());
1257 void print() const
1259 printf("%s\n", ToString().c_str());
1266 // Used to marshal pointers into hashes for db storage.
1268 class CDiskBlockIndex : public CBlockIndex
1270 public:
1271 uint256 hashPrev;
1272 uint256 hashNext;
1274 CDiskBlockIndex()
1276 hashPrev = 0;
1277 hashNext = 0;
1280 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1282 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1283 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1286 IMPLEMENT_SERIALIZE
1288 if (!(nType & SER_GETHASH))
1289 READWRITE(nVersion);
1291 READWRITE(hashNext);
1292 READWRITE(nFile);
1293 READWRITE(nBlockPos);
1294 READWRITE(nHeight);
1296 // block header
1297 READWRITE(this->nVersion);
1298 READWRITE(hashPrev);
1299 READWRITE(hashMerkleRoot);
1300 READWRITE(nTime);
1301 READWRITE(nBits);
1302 READWRITE(nNonce);
1305 uint256 GetBlockHash() const
1307 CBlock block;
1308 block.nVersion = nVersion;
1309 block.hashPrevBlock = hashPrev;
1310 block.hashMerkleRoot = hashMerkleRoot;
1311 block.nTime = nTime;
1312 block.nBits = nBits;
1313 block.nNonce = nNonce;
1314 return block.GetHash();
1318 string ToString() const
1320 string str = "CDiskBlockIndex(";
1321 str += CBlockIndex::ToString();
1322 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1323 GetBlockHash().ToString().c_str(),
1324 hashPrev.ToString().substr(0,20).c_str(),
1325 hashNext.ToString().substr(0,20).c_str());
1326 return str;
1329 void print() const
1331 printf("%s\n", ToString().c_str());
1343 // Describes a place in the block chain to another node such that if the
1344 // other node doesn't have the same branch, it can find a recent common trunk.
1345 // The further back it is, the further before the fork it may be.
1347 class CBlockLocator
1349 protected:
1350 vector<uint256> vHave;
1351 public:
1353 CBlockLocator()
1357 explicit CBlockLocator(const CBlockIndex* pindex)
1359 Set(pindex);
1362 explicit CBlockLocator(uint256 hashBlock)
1364 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1365 if (mi != mapBlockIndex.end())
1366 Set((*mi).second);
1369 IMPLEMENT_SERIALIZE
1371 if (!(nType & SER_GETHASH))
1372 READWRITE(nVersion);
1373 READWRITE(vHave);
1376 void Set(const CBlockIndex* pindex)
1378 vHave.clear();
1379 int nStep = 1;
1380 while (pindex)
1382 vHave.push_back(pindex->GetBlockHash());
1384 // Exponentially larger steps back
1385 for (int i = 0; pindex && i < nStep; i++)
1386 pindex = pindex->pprev;
1387 if (vHave.size() > 10)
1388 nStep *= 2;
1390 vHave.push_back(hashGenesisBlock);
1393 int GetDistanceBack()
1395 // Retrace how far back it was in the sender's branch
1396 int nDistance = 0;
1397 int nStep = 1;
1398 foreach(const uint256& hash, vHave)
1400 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1401 if (mi != mapBlockIndex.end())
1403 CBlockIndex* pindex = (*mi).second;
1404 if (pindex->IsInMainChain())
1405 return nDistance;
1407 nDistance += nStep;
1408 if (nDistance > 10)
1409 nStep *= 2;
1411 return nDistance;
1414 CBlockIndex* GetBlockIndex()
1416 // Find the first block the caller has in the main chain
1417 foreach(const uint256& hash, vHave)
1419 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1420 if (mi != mapBlockIndex.end())
1422 CBlockIndex* pindex = (*mi).second;
1423 if (pindex->IsInMainChain())
1424 return pindex;
1427 return pindexGenesisBlock;
1430 uint256 GetBlockHash()
1432 // Find the first block the caller has in the main chain
1433 foreach(const uint256& hash, vHave)
1435 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1436 if (mi != mapBlockIndex.end())
1438 CBlockIndex* pindex = (*mi).second;
1439 if (pindex->IsInMainChain())
1440 return hash;
1443 return hashGenesisBlock;
1446 int GetHeight()
1448 CBlockIndex* pindex = GetBlockIndex();
1449 if (!pindex)
1450 return 0;
1451 return pindex->nHeight;
1461 // Private key that includes an expiration date in case it never gets used.
1463 class CWalletKey
1465 public:
1466 CPrivKey vchPrivKey;
1467 int64 nTimeCreated;
1468 int64 nTimeExpires;
1469 string strComment;
1470 //// todo: add something to note what created it (user, getnewaddress, change)
1471 //// maybe should have a map<string, string> property map
1473 CWalletKey(int64 nTimeExpiresIn=0)
1475 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
1476 nTimeExpires = nTimeExpiresIn;
1479 IMPLEMENT_SERIALIZE
1481 if (!(nType & SER_GETHASH))
1482 READWRITE(nVersion);
1483 READWRITE(vchPrivKey);
1484 READWRITE(nTimeCreated);
1485 READWRITE(nTimeExpires);
1486 READWRITE(strComment);
1496 // Alert messages are broadcast as a vector of signed data. Unserializing may
1497 // not read the entire buffer if the alert is for a newer version, but older
1498 // versions can still relay the original data.
1500 class CUnsignedAlert
1502 public:
1503 int nVersion;
1504 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1505 int64 nExpiration;
1506 int nID;
1507 int nCancel;
1508 set<int> setCancel;
1509 int nMinVer; // lowest version inclusive
1510 int nMaxVer; // highest version inclusive
1511 set<string> setSubVer; // empty matches all
1512 int nPriority;
1514 // Actions
1515 string strComment;
1516 string strStatusBar;
1517 string strRPCError;
1519 IMPLEMENT_SERIALIZE
1521 READWRITE(this->nVersion);
1522 nVersion = this->nVersion;
1523 READWRITE(nRelayUntil);
1524 READWRITE(nExpiration);
1525 READWRITE(nID);
1526 READWRITE(nCancel);
1527 READWRITE(setCancel);
1528 READWRITE(nMinVer);
1529 READWRITE(nMaxVer);
1530 READWRITE(setSubVer);
1531 READWRITE(nPriority);
1533 READWRITE(strComment);
1534 READWRITE(strStatusBar);
1535 READWRITE(strRPCError);
1538 void SetNull()
1540 nVersion = 1;
1541 nRelayUntil = 0;
1542 nExpiration = 0;
1543 nID = 0;
1544 nCancel = 0;
1545 setCancel.clear();
1546 nMinVer = 0;
1547 nMaxVer = 0;
1548 setSubVer.clear();
1549 nPriority = 0;
1551 strComment.clear();
1552 strStatusBar.clear();
1553 strRPCError.clear();
1556 string ToString() const
1558 string strSetCancel;
1559 foreach(int n, setCancel)
1560 strSetCancel += strprintf("%d ", n);
1561 string strSetSubVer;
1562 foreach(string str, setSubVer)
1563 strSetSubVer += "\"" + str + "\" ";
1564 return strprintf(
1565 "CAlert(\n"
1566 " nVersion = %d\n"
1567 " nRelayUntil = %"PRI64d"\n"
1568 " nExpiration = %"PRI64d"\n"
1569 " nID = %d\n"
1570 " nCancel = %d\n"
1571 " setCancel = %s\n"
1572 " nMinVer = %d\n"
1573 " nMaxVer = %d\n"
1574 " setSubVer = %s\n"
1575 " nPriority = %d\n"
1576 " strComment = \"%s\"\n"
1577 " strStatusBar = \"%s\"\n"
1578 " strRPCError = \"%s\"\n"
1579 ")\n",
1580 nVersion,
1581 nRelayUntil,
1582 nExpiration,
1583 nID,
1584 nCancel,
1585 strSetCancel.c_str(),
1586 nMinVer,
1587 nMaxVer,
1588 strSetSubVer.c_str(),
1589 nPriority,
1590 strComment.c_str(),
1591 strStatusBar.c_str(),
1592 strRPCError.c_str());
1595 void print() const
1597 printf("%s", ToString().c_str());
1601 class CAlert : public CUnsignedAlert
1603 public:
1604 vector<unsigned char> vchMsg;
1605 vector<unsigned char> vchSig;
1607 CAlert()
1609 SetNull();
1612 IMPLEMENT_SERIALIZE
1614 READWRITE(vchMsg);
1615 READWRITE(vchSig);
1618 void SetNull()
1620 CUnsignedAlert::SetNull();
1621 vchMsg.clear();
1622 vchSig.clear();
1625 bool IsNull() const
1627 return (nExpiration == 0);
1630 uint256 GetHash() const
1632 return SerializeHash(*this);
1635 bool IsInEffect() const
1637 return (GetAdjustedTime() < nExpiration);
1640 bool Cancels(const CAlert& alert) const
1642 if (!IsInEffect())
1643 false;
1644 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1647 bool AppliesTo(int nVersion, string strSubVerIn) const
1649 return (IsInEffect() &&
1650 nMinVer <= nVersion && nVersion <= nMaxVer &&
1651 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1654 bool AppliesToMe() const
1656 return AppliesTo(VERSION, ::pszSubVer);
1659 bool RelayTo(CNode* pnode) const
1661 if (!IsInEffect())
1662 return false;
1663 // returns true if wasn't already contained in the set
1664 if (pnode->setKnown.insert(GetHash()).second)
1666 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1667 AppliesToMe() ||
1668 GetAdjustedTime() < nRelayUntil)
1670 pnode->PushMessage("alert", *this);
1671 return true;
1674 return false;
1677 bool CheckSignature()
1679 CKey key;
1680 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1681 return error("CAlert::CheckSignature() : SetPubKey failed");
1682 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1683 return error("CAlert::CheckSignature() : verify signature failed");
1685 // Now unserialize the data
1686 CDataStream sMsg(vchMsg);
1687 sMsg >> *(CUnsignedAlert*)this;
1688 return true;
1691 bool ProcessAlert();
1703 extern map<uint256, CTransaction> mapTransactions;
1704 extern map<uint256, CWalletTx> mapWallet;
1705 extern vector<uint256> vWalletUpdated;
1706 extern CCriticalSection cs_mapWallet;
1707 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1708 extern map<uint160, vector<unsigned char> > mapPubKeys;
1709 extern CCriticalSection cs_mapKeys;
1710 extern CKey keyUser;