Update License in File Headers
[bitcoinplatinum.git] / src / main.h
blobf879b731309d86fefdf3166e8e808372b4d981ff
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_MAIN_H
6 #define BITCOIN_MAIN_H
8 #include "bignum.h"
9 #include "sync.h"
10 #include "net.h"
11 #include "script.h"
13 #include <list>
15 class CWallet;
16 class CBlock;
17 class CBlockIndex;
18 class CKeyItem;
19 class CReserveKey;
21 class CAddress;
22 class CInv;
23 class CRequestTracker;
24 class CNode;
26 static const unsigned int MAX_BLOCK_SIZE = 1000000;
27 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
28 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
29 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
30 static const int64 MIN_TX_FEE = 50000;
31 static const int64 MIN_RELAY_TX_FEE = 10000;
32 static const int64 MAX_MONEY = 21000000 * COIN;
33 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
34 static const int COINBASE_MATURITY = 100;
35 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
36 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
37 #ifdef USE_UPNP
38 static const int fHaveUPnP = true;
39 #else
40 static const int fHaveUPnP = false;
41 #endif
44 extern CScript COINBASE_FLAGS;
51 extern CCriticalSection cs_main;
52 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
53 extern uint256 hashGenesisBlock;
54 extern CBlockIndex* pindexGenesisBlock;
55 extern int nBestHeight;
56 extern CBigNum bnBestChainWork;
57 extern CBigNum bnBestInvalidWork;
58 extern uint256 hashBestChain;
59 extern CBlockIndex* pindexBest;
60 extern unsigned int nTransactionsUpdated;
61 extern uint64 nLastBlockTx;
62 extern uint64 nLastBlockSize;
63 extern const std::string strMessageMagic;
64 extern double dHashesPerSec;
65 extern int64 nHPSTimerStart;
66 extern int64 nTimeBestReceived;
67 extern CCriticalSection cs_setpwalletRegistered;
68 extern std::set<CWallet*> setpwalletRegistered;
69 extern unsigned char pchMessageStart[4];
71 // Settings
72 extern int64 nTransactionFee;
78 class CReserveKey;
79 class CTxDB;
80 class CTxIndex;
82 void RegisterWallet(CWallet* pwalletIn);
83 void UnregisterWallet(CWallet* pwalletIn);
84 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
85 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
86 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
87 FILE* AppendBlockFile(unsigned int& nFileRet);
88 bool LoadBlockIndex(bool fAllowNew=true);
89 void PrintBlockTree();
90 bool ProcessMessages(CNode* pfrom);
91 bool SendMessages(CNode* pto, bool fSendTrickle);
92 bool LoadExternalBlockFile(FILE* fileIn);
93 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
94 CBlock* CreateNewBlock(CReserveKey& reservekey);
95 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
96 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
97 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
98 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
99 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
100 int GetNumBlocksOfPeers();
101 bool IsInitialBlockDownload();
102 std::string GetWarnings(std::string strFor);
103 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
115 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
117 /** Position on disk for a particular transaction. */
118 class CDiskTxPos
120 public:
121 unsigned int nFile;
122 unsigned int nBlockPos;
123 unsigned int nTxPos;
125 CDiskTxPos()
127 SetNull();
130 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
132 nFile = nFileIn;
133 nBlockPos = nBlockPosIn;
134 nTxPos = nTxPosIn;
137 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
138 void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
139 bool IsNull() const { return (nFile == (unsigned int) -1); }
141 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
143 return (a.nFile == b.nFile &&
144 a.nBlockPos == b.nBlockPos &&
145 a.nTxPos == b.nTxPos);
148 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
150 return !(a == b);
153 std::string ToString() const
155 if (IsNull())
156 return "null";
157 else
158 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
161 void print() const
163 printf("%s", ToString().c_str());
169 /** An inpoint - a combination of a transaction and an index n into its vin */
170 class CInPoint
172 public:
173 CTransaction* ptx;
174 unsigned int n;
176 CInPoint() { SetNull(); }
177 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
178 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
179 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
184 /** An outpoint - a combination of a transaction hash and an index n into its vout */
185 class COutPoint
187 public:
188 uint256 hash;
189 unsigned int n;
191 COutPoint() { SetNull(); }
192 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
193 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
194 void SetNull() { hash = 0; n = (unsigned int) -1; }
195 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
197 friend bool operator<(const COutPoint& a, const COutPoint& b)
199 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
202 friend bool operator==(const COutPoint& a, const COutPoint& b)
204 return (a.hash == b.hash && a.n == b.n);
207 friend bool operator!=(const COutPoint& a, const COutPoint& b)
209 return !(a == b);
212 std::string ToString() const
214 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
217 void print() const
219 printf("%s\n", ToString().c_str());
226 /** An input of a transaction. It contains the location of the previous
227 * transaction's output that it claims and a signature that matches the
228 * output's public key.
230 class CTxIn
232 public:
233 COutPoint prevout;
234 CScript scriptSig;
235 unsigned int nSequence;
237 CTxIn()
239 nSequence = std::numeric_limits<unsigned int>::max();
242 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
244 prevout = prevoutIn;
245 scriptSig = scriptSigIn;
246 nSequence = nSequenceIn;
249 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
251 prevout = COutPoint(hashPrevTx, nOut);
252 scriptSig = scriptSigIn;
253 nSequence = nSequenceIn;
256 IMPLEMENT_SERIALIZE
258 READWRITE(prevout);
259 READWRITE(scriptSig);
260 READWRITE(nSequence);
263 bool IsFinal() const
265 return (nSequence == std::numeric_limits<unsigned int>::max());
268 friend bool operator==(const CTxIn& a, const CTxIn& b)
270 return (a.prevout == b.prevout &&
271 a.scriptSig == b.scriptSig &&
272 a.nSequence == b.nSequence);
275 friend bool operator!=(const CTxIn& a, const CTxIn& b)
277 return !(a == b);
280 std::string ToString() const
282 std::string str;
283 str += "CTxIn(";
284 str += prevout.ToString();
285 if (prevout.IsNull())
286 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
287 else
288 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
289 if (nSequence != std::numeric_limits<unsigned int>::max())
290 str += strprintf(", nSequence=%u", nSequence);
291 str += ")";
292 return str;
295 void print() const
297 printf("%s\n", ToString().c_str());
304 /** An output of a transaction. It contains the public key that the next input
305 * must be able to sign with to claim it.
307 class CTxOut
309 public:
310 int64 nValue;
311 CScript scriptPubKey;
313 CTxOut()
315 SetNull();
318 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
320 nValue = nValueIn;
321 scriptPubKey = scriptPubKeyIn;
324 IMPLEMENT_SERIALIZE
326 READWRITE(nValue);
327 READWRITE(scriptPubKey);
330 void SetNull()
332 nValue = -1;
333 scriptPubKey.clear();
336 bool IsNull()
338 return (nValue == -1);
341 uint256 GetHash() const
343 return SerializeHash(*this);
346 friend bool operator==(const CTxOut& a, const CTxOut& b)
348 return (a.nValue == b.nValue &&
349 a.scriptPubKey == b.scriptPubKey);
352 friend bool operator!=(const CTxOut& a, const CTxOut& b)
354 return !(a == b);
357 std::string ToString() const
359 if (scriptPubKey.size() < 6)
360 return "CTxOut(error)";
361 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
364 void print() const
366 printf("%s\n", ToString().c_str());
373 enum GetMinFee_mode
375 GMF_BLOCK,
376 GMF_RELAY,
377 GMF_SEND,
380 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
382 /** The basic transaction that is broadcasted on the network and contained in
383 * blocks. A transaction can contain multiple inputs and outputs.
385 class CTransaction
387 public:
388 int nVersion;
389 std::vector<CTxIn> vin;
390 std::vector<CTxOut> vout;
391 unsigned int nLockTime;
393 // Denial-of-service detection:
394 mutable int nDoS;
395 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
397 CTransaction()
399 SetNull();
402 IMPLEMENT_SERIALIZE
404 READWRITE(this->nVersion);
405 nVersion = this->nVersion;
406 READWRITE(vin);
407 READWRITE(vout);
408 READWRITE(nLockTime);
411 void SetNull()
413 nVersion = 1;
414 vin.clear();
415 vout.clear();
416 nLockTime = 0;
417 nDoS = 0; // Denial-of-service prevention
420 bool IsNull() const
422 return (vin.empty() && vout.empty());
425 uint256 GetHash() const
427 return SerializeHash(*this);
430 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
432 // Time based nLockTime implemented in 0.1.6
433 if (nLockTime == 0)
434 return true;
435 if (nBlockHeight == 0)
436 nBlockHeight = nBestHeight;
437 if (nBlockTime == 0)
438 nBlockTime = GetAdjustedTime();
439 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
440 return true;
441 BOOST_FOREACH(const CTxIn& txin, vin)
442 if (!txin.IsFinal())
443 return false;
444 return true;
447 bool IsNewerThan(const CTransaction& old) const
449 if (vin.size() != old.vin.size())
450 return false;
451 for (unsigned int i = 0; i < vin.size(); i++)
452 if (vin[i].prevout != old.vin[i].prevout)
453 return false;
455 bool fNewer = false;
456 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
457 for (unsigned int i = 0; i < vin.size(); i++)
459 if (vin[i].nSequence != old.vin[i].nSequence)
461 if (vin[i].nSequence <= nLowest)
463 fNewer = false;
464 nLowest = vin[i].nSequence;
466 if (old.vin[i].nSequence < nLowest)
468 fNewer = true;
469 nLowest = old.vin[i].nSequence;
473 return fNewer;
476 bool IsCoinBase() const
478 return (vin.size() == 1 && vin[0].prevout.IsNull());
481 /** Check for standard transaction types
482 @return True if all outputs (scriptPubKeys) use only standard transaction forms
484 bool IsStandard() const;
486 /** Check for standard transaction types
487 @param[in] mapInputs Map of previous transactions that have outputs we're spending
488 @return True if all inputs (scriptSigs) use only standard transaction forms
489 @see CTransaction::FetchInputs
491 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
493 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
494 @return number of sigops this transaction's outputs will produce when spent
495 @see CTransaction::FetchInputs
497 unsigned int GetLegacySigOpCount() const;
499 /** Count ECDSA signature operations in pay-to-script-hash inputs.
501 @param[in] mapInputs Map of previous transactions that have outputs we're spending
502 @return maximum number of sigops required to validate this transaction's inputs
503 @see CTransaction::FetchInputs
505 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
507 /** Amount of bitcoins spent by this transaction.
508 @return sum of all outputs (note: does not include fees)
510 int64 GetValueOut() const
512 int64 nValueOut = 0;
513 BOOST_FOREACH(const CTxOut& txout, vout)
515 nValueOut += txout.nValue;
516 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
517 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
519 return nValueOut;
522 /** Amount of bitcoins coming in to this transaction
523 Note that lightweight clients may not know anything besides the hash of previous transactions,
524 so may not be able to calculate this.
526 @param[in] mapInputs Map of previous transactions that have outputs we're spending
527 @return Sum of value of all inputs (scriptSigs)
528 @see CTransaction::FetchInputs
530 int64 GetValueIn(const MapPrevTx& mapInputs) const;
532 static bool AllowFree(double dPriority)
534 // Large (in bytes) low-priority (new, small-coin) transactions
535 // need a fee.
536 return dPriority > COIN * 144 / 250;
539 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
541 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
542 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
544 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
545 unsigned int nNewBlockSize = nBlockSize + nBytes;
546 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
548 if (fAllowFree)
550 if (nBlockSize == 1)
552 // Transactions under 10K are free
553 // (about 4500bc if made of 50bc inputs)
554 if (nBytes < 10000)
555 nMinFee = 0;
557 else
559 // Free transaction area
560 if (nNewBlockSize < 27000)
561 nMinFee = 0;
565 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
566 if (nMinFee < nBaseFee)
568 BOOST_FOREACH(const CTxOut& txout, vout)
569 if (txout.nValue < CENT)
570 nMinFee = nBaseFee;
573 // Raise the price as the block approaches full
574 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
576 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
577 return MAX_MONEY;
578 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
581 if (!MoneyRange(nMinFee))
582 nMinFee = MAX_MONEY;
583 return nMinFee;
587 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
589 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
590 if (!filein)
591 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
593 // Read transaction
594 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
595 return error("CTransaction::ReadFromDisk() : fseek failed");
596 filein >> *this;
598 // Return file pointer
599 if (pfileRet)
601 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
602 return error("CTransaction::ReadFromDisk() : second fseek failed");
603 *pfileRet = filein.release();
605 return true;
608 friend bool operator==(const CTransaction& a, const CTransaction& b)
610 return (a.nVersion == b.nVersion &&
611 a.vin == b.vin &&
612 a.vout == b.vout &&
613 a.nLockTime == b.nLockTime);
616 friend bool operator!=(const CTransaction& a, const CTransaction& b)
618 return !(a == b);
622 std::string ToString() const
624 std::string str;
625 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
626 GetHash().ToString().substr(0,10).c_str(),
627 nVersion,
628 vin.size(),
629 vout.size(),
630 nLockTime);
631 for (unsigned int i = 0; i < vin.size(); i++)
632 str += " " + vin[i].ToString() + "\n";
633 for (unsigned int i = 0; i < vout.size(); i++)
634 str += " " + vout[i].ToString() + "\n";
635 return str;
638 void print() const
640 printf("%s", ToString().c_str());
644 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
645 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
646 bool ReadFromDisk(COutPoint prevout);
647 bool DisconnectInputs(CTxDB& txdb);
649 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
651 @param[in] txdb Transaction database
652 @param[in] mapTestPool List of pending changes to the transaction index database
653 @param[in] fBlock True if being called to add a new best-block to the chain
654 @param[in] fMiner True if being called by CreateNewBlock
655 @param[out] inputsRet Pointers to this transaction's inputs
656 @param[out] fInvalid returns true if transaction is invalid
657 @return Returns true if all inputs are in txdb or mapTestPool
659 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
660 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
662 /** Sanity check previous transactions, then, if all checks succeed,
663 mark them as spent by this transaction.
665 @param[in] inputs Previous transactions (from FetchInputs)
666 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
667 @param[in] posThisTx Position of this transaction on disk
668 @param[in] pindexBlock
669 @param[in] fBlock true if called from ConnectBlock
670 @param[in] fMiner true if called from CreateNewBlock
671 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
672 @return Returns true if all checks succeed
674 bool ConnectInputs(MapPrevTx inputs,
675 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
676 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
677 bool ClientConnectInputs();
678 bool CheckTransaction() const;
679 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
681 protected:
682 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
689 /** A transaction with a merkle branch linking it to the block chain. */
690 class CMerkleTx : public CTransaction
692 public:
693 uint256 hashBlock;
694 std::vector<uint256> vMerkleBranch;
695 int nIndex;
697 // memory only
698 mutable bool fMerkleVerified;
701 CMerkleTx()
703 Init();
706 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
708 Init();
711 void Init()
713 hashBlock = 0;
714 nIndex = -1;
715 fMerkleVerified = false;
719 IMPLEMENT_SERIALIZE
721 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
722 nVersion = this->nVersion;
723 READWRITE(hashBlock);
724 READWRITE(vMerkleBranch);
725 READWRITE(nIndex);
729 int SetMerkleBranch(const CBlock* pblock=NULL);
730 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
731 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
732 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
733 int GetBlocksToMaturity() const;
734 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
735 bool AcceptToMemoryPool();
741 /** A txdb record that contains the disk location of a transaction and the
742 * locations of transactions that spend its outputs. vSpent is really only
743 * used as a flag, but having the location is very helpful for debugging.
745 class CTxIndex
747 public:
748 CDiskTxPos pos;
749 std::vector<CDiskTxPos> vSpent;
751 CTxIndex()
753 SetNull();
756 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
758 pos = posIn;
759 vSpent.resize(nOutputs);
762 IMPLEMENT_SERIALIZE
764 if (!(nType & SER_GETHASH))
765 READWRITE(nVersion);
766 READWRITE(pos);
767 READWRITE(vSpent);
770 void SetNull()
772 pos.SetNull();
773 vSpent.clear();
776 bool IsNull()
778 return pos.IsNull();
781 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
783 return (a.pos == b.pos &&
784 a.vSpent == b.vSpent);
787 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
789 return !(a == b);
791 int GetDepthInMainChain() const;
799 /** Nodes collect new transactions into a block, hash them into a hash tree,
800 * and scan through nonce values to make the block's hash satisfy proof-of-work
801 * requirements. When they solve the proof-of-work, they broadcast the block
802 * to everyone and the block is added to the block chain. The first transaction
803 * in the block is a special one that creates a new coin owned by the creator
804 * of the block.
806 * Blocks are appended to blk0001.dat files on disk. Their location on disk
807 * is indexed by CBlockIndex objects in memory.
809 class CBlock
811 public:
812 // header
813 int nVersion;
814 uint256 hashPrevBlock;
815 uint256 hashMerkleRoot;
816 unsigned int nTime;
817 unsigned int nBits;
818 unsigned int nNonce;
820 // network and disk
821 std::vector<CTransaction> vtx;
823 // memory only
824 mutable std::vector<uint256> vMerkleTree;
826 // Denial-of-service detection:
827 mutable int nDoS;
828 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
830 CBlock()
832 SetNull();
835 IMPLEMENT_SERIALIZE
837 READWRITE(this->nVersion);
838 nVersion = this->nVersion;
839 READWRITE(hashPrevBlock);
840 READWRITE(hashMerkleRoot);
841 READWRITE(nTime);
842 READWRITE(nBits);
843 READWRITE(nNonce);
845 // ConnectBlock depends on vtx being last so it can calculate offset
846 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
847 READWRITE(vtx);
848 else if (fRead)
849 const_cast<CBlock*>(this)->vtx.clear();
852 void SetNull()
854 nVersion = 1;
855 hashPrevBlock = 0;
856 hashMerkleRoot = 0;
857 nTime = 0;
858 nBits = 0;
859 nNonce = 0;
860 vtx.clear();
861 vMerkleTree.clear();
862 nDoS = 0;
865 bool IsNull() const
867 return (nBits == 0);
870 uint256 GetHash() const
872 return Hash(BEGIN(nVersion), END(nNonce));
875 int64 GetBlockTime() const
877 return (int64)nTime;
880 void UpdateTime(const CBlockIndex* pindexPrev);
883 uint256 BuildMerkleTree() const
885 vMerkleTree.clear();
886 BOOST_FOREACH(const CTransaction& tx, vtx)
887 vMerkleTree.push_back(tx.GetHash());
888 int j = 0;
889 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
891 for (int i = 0; i < nSize; i += 2)
893 int i2 = std::min(i+1, nSize-1);
894 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
895 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
897 j += nSize;
899 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
902 std::vector<uint256> GetMerkleBranch(int nIndex) const
904 if (vMerkleTree.empty())
905 BuildMerkleTree();
906 std::vector<uint256> vMerkleBranch;
907 int j = 0;
908 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
910 int i = std::min(nIndex^1, nSize-1);
911 vMerkleBranch.push_back(vMerkleTree[j+i]);
912 nIndex >>= 1;
913 j += nSize;
915 return vMerkleBranch;
918 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
920 if (nIndex == -1)
921 return 0;
922 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
924 if (nIndex & 1)
925 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
926 else
927 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
928 nIndex >>= 1;
930 return hash;
934 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
936 // Open history file to append
937 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
938 if (!fileout)
939 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
941 // Write index header
942 unsigned int nSize = fileout.GetSerializeSize(*this);
943 fileout << FLATDATA(pchMessageStart) << nSize;
945 // Write block
946 long fileOutPos = ftell(fileout);
947 if (fileOutPos < 0)
948 return error("CBlock::WriteToDisk() : ftell failed");
949 nBlockPosRet = fileOutPos;
950 fileout << *this;
952 // Flush stdio buffers and commit to disk before returning
953 fflush(fileout);
954 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
955 FileCommit(fileout);
957 return true;
960 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
962 SetNull();
964 // Open history file to read
965 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
966 if (!filein)
967 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
968 if (!fReadTransactions)
969 filein.nType |= SER_BLOCKHEADERONLY;
971 // Read block
972 filein >> *this;
974 // Check the header
975 if (!CheckProofOfWork(GetHash(), nBits))
976 return error("CBlock::ReadFromDisk() : errors in block header");
978 return true;
983 void print() const
985 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
986 GetHash().ToString().substr(0,20).c_str(),
987 nVersion,
988 hashPrevBlock.ToString().substr(0,20).c_str(),
989 hashMerkleRoot.ToString().substr(0,10).c_str(),
990 nTime, nBits, nNonce,
991 vtx.size());
992 for (unsigned int i = 0; i < vtx.size(); i++)
994 printf(" ");
995 vtx[i].print();
997 printf(" vMerkleTree: ");
998 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
999 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1000 printf("\n");
1004 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1005 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1006 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1007 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1008 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1009 bool CheckBlock() const;
1010 bool AcceptBlock();
1012 private:
1013 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1021 /** The block chain is a tree shaped structure starting with the
1022 * genesis block at the root, with each block potentially having multiple
1023 * candidates to be the next block. pprev and pnext link a path through the
1024 * main/longest chain. A blockindex may have multiple pprev pointing back
1025 * to it, but pnext will only point forward to the longest branch, or will
1026 * be null if the block is not part of the longest chain.
1028 class CBlockIndex
1030 public:
1031 const uint256* phashBlock;
1032 CBlockIndex* pprev;
1033 CBlockIndex* pnext;
1034 unsigned int nFile;
1035 unsigned int nBlockPos;
1036 int nHeight;
1037 CBigNum bnChainWork;
1039 // block header
1040 int nVersion;
1041 uint256 hashMerkleRoot;
1042 unsigned int nTime;
1043 unsigned int nBits;
1044 unsigned int nNonce;
1047 CBlockIndex()
1049 phashBlock = NULL;
1050 pprev = NULL;
1051 pnext = NULL;
1052 nFile = 0;
1053 nBlockPos = 0;
1054 nHeight = 0;
1055 bnChainWork = 0;
1057 nVersion = 0;
1058 hashMerkleRoot = 0;
1059 nTime = 0;
1060 nBits = 0;
1061 nNonce = 0;
1064 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1066 phashBlock = NULL;
1067 pprev = NULL;
1068 pnext = NULL;
1069 nFile = nFileIn;
1070 nBlockPos = nBlockPosIn;
1071 nHeight = 0;
1072 bnChainWork = 0;
1074 nVersion = block.nVersion;
1075 hashMerkleRoot = block.hashMerkleRoot;
1076 nTime = block.nTime;
1077 nBits = block.nBits;
1078 nNonce = block.nNonce;
1081 CBlock GetBlockHeader() const
1083 CBlock block;
1084 block.nVersion = nVersion;
1085 if (pprev)
1086 block.hashPrevBlock = pprev->GetBlockHash();
1087 block.hashMerkleRoot = hashMerkleRoot;
1088 block.nTime = nTime;
1089 block.nBits = nBits;
1090 block.nNonce = nNonce;
1091 return block;
1094 uint256 GetBlockHash() const
1096 return *phashBlock;
1099 int64 GetBlockTime() const
1101 return (int64)nTime;
1104 CBigNum GetBlockWork() const
1106 CBigNum bnTarget;
1107 bnTarget.SetCompact(nBits);
1108 if (bnTarget <= 0)
1109 return 0;
1110 return (CBigNum(1)<<256) / (bnTarget+1);
1113 bool IsInMainChain() const
1115 return (pnext || this == pindexBest);
1118 bool CheckIndex() const
1120 return CheckProofOfWork(GetBlockHash(), nBits);
1123 enum { nMedianTimeSpan=11 };
1125 int64 GetMedianTimePast() const
1127 int64 pmedian[nMedianTimeSpan];
1128 int64* pbegin = &pmedian[nMedianTimeSpan];
1129 int64* pend = &pmedian[nMedianTimeSpan];
1131 const CBlockIndex* pindex = this;
1132 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1133 *(--pbegin) = pindex->GetBlockTime();
1135 std::sort(pbegin, pend);
1136 return pbegin[(pend - pbegin)/2];
1139 int64 GetMedianTime() const
1141 const CBlockIndex* pindex = this;
1142 for (int i = 0; i < nMedianTimeSpan/2; i++)
1144 if (!pindex->pnext)
1145 return GetBlockTime();
1146 pindex = pindex->pnext;
1148 return pindex->GetMedianTimePast();
1153 std::string ToString() const
1155 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1156 pprev, pnext, nFile, nBlockPos, nHeight,
1157 hashMerkleRoot.ToString().substr(0,10).c_str(),
1158 GetBlockHash().ToString().substr(0,20).c_str());
1161 void print() const
1163 printf("%s\n", ToString().c_str());
1169 /** Used to marshal pointers into hashes for db storage. */
1170 class CDiskBlockIndex : public CBlockIndex
1172 public:
1173 uint256 hashPrev;
1174 uint256 hashNext;
1176 CDiskBlockIndex()
1178 hashPrev = 0;
1179 hashNext = 0;
1182 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1184 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1185 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1188 IMPLEMENT_SERIALIZE
1190 if (!(nType & SER_GETHASH))
1191 READWRITE(nVersion);
1193 READWRITE(hashNext);
1194 READWRITE(nFile);
1195 READWRITE(nBlockPos);
1196 READWRITE(nHeight);
1198 // block header
1199 READWRITE(this->nVersion);
1200 READWRITE(hashPrev);
1201 READWRITE(hashMerkleRoot);
1202 READWRITE(nTime);
1203 READWRITE(nBits);
1204 READWRITE(nNonce);
1207 uint256 GetBlockHash() const
1209 CBlock block;
1210 block.nVersion = nVersion;
1211 block.hashPrevBlock = hashPrev;
1212 block.hashMerkleRoot = hashMerkleRoot;
1213 block.nTime = nTime;
1214 block.nBits = nBits;
1215 block.nNonce = nNonce;
1216 return block.GetHash();
1220 std::string ToString() const
1222 std::string str = "CDiskBlockIndex(";
1223 str += CBlockIndex::ToString();
1224 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1225 GetBlockHash().ToString().c_str(),
1226 hashPrev.ToString().substr(0,20).c_str(),
1227 hashNext.ToString().substr(0,20).c_str());
1228 return str;
1231 void print() const
1233 printf("%s\n", ToString().c_str());
1244 /** Describes a place in the block chain to another node such that if the
1245 * other node doesn't have the same branch, it can find a recent common trunk.
1246 * The further back it is, the further before the fork it may be.
1248 class CBlockLocator
1250 protected:
1251 std::vector<uint256> vHave;
1252 public:
1254 CBlockLocator()
1258 explicit CBlockLocator(const CBlockIndex* pindex)
1260 Set(pindex);
1263 explicit CBlockLocator(uint256 hashBlock)
1265 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1266 if (mi != mapBlockIndex.end())
1267 Set((*mi).second);
1270 CBlockLocator(const std::vector<uint256>& vHaveIn)
1272 vHave = vHaveIn;
1275 IMPLEMENT_SERIALIZE
1277 if (!(nType & SER_GETHASH))
1278 READWRITE(nVersion);
1279 READWRITE(vHave);
1282 void SetNull()
1284 vHave.clear();
1287 bool IsNull()
1289 return vHave.empty();
1292 void Set(const CBlockIndex* pindex)
1294 vHave.clear();
1295 int nStep = 1;
1296 while (pindex)
1298 vHave.push_back(pindex->GetBlockHash());
1300 // Exponentially larger steps back
1301 for (int i = 0; pindex && i < nStep; i++)
1302 pindex = pindex->pprev;
1303 if (vHave.size() > 10)
1304 nStep *= 2;
1306 vHave.push_back(hashGenesisBlock);
1309 int GetDistanceBack()
1311 // Retrace how far back it was in the sender's branch
1312 int nDistance = 0;
1313 int nStep = 1;
1314 BOOST_FOREACH(const uint256& hash, vHave)
1316 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1317 if (mi != mapBlockIndex.end())
1319 CBlockIndex* pindex = (*mi).second;
1320 if (pindex->IsInMainChain())
1321 return nDistance;
1323 nDistance += nStep;
1324 if (nDistance > 10)
1325 nStep *= 2;
1327 return nDistance;
1330 CBlockIndex* GetBlockIndex()
1332 // Find the first block the caller has in the main chain
1333 BOOST_FOREACH(const uint256& hash, vHave)
1335 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1336 if (mi != mapBlockIndex.end())
1338 CBlockIndex* pindex = (*mi).second;
1339 if (pindex->IsInMainChain())
1340 return pindex;
1343 return pindexGenesisBlock;
1346 uint256 GetBlockHash()
1348 // Find the first block the caller has in the main chain
1349 BOOST_FOREACH(const uint256& hash, vHave)
1351 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1352 if (mi != mapBlockIndex.end())
1354 CBlockIndex* pindex = (*mi).second;
1355 if (pindex->IsInMainChain())
1356 return hash;
1359 return hashGenesisBlock;
1362 int GetHeight()
1364 CBlockIndex* pindex = GetBlockIndex();
1365 if (!pindex)
1366 return 0;
1367 return pindex->nHeight;
1379 /** Alerts are for notifying old versions if they become too obsolete and
1380 * need to upgrade. The message is displayed in the status bar.
1381 * Alert messages are broadcast as a vector of signed data. Unserializing may
1382 * not read the entire buffer if the alert is for a newer version, but older
1383 * versions can still relay the original data.
1385 class CUnsignedAlert
1387 public:
1388 int nVersion;
1389 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1390 int64 nExpiration;
1391 int nID;
1392 int nCancel;
1393 std::set<int> setCancel;
1394 int nMinVer; // lowest version inclusive
1395 int nMaxVer; // highest version inclusive
1396 std::set<std::string> setSubVer; // empty matches all
1397 int nPriority;
1399 // Actions
1400 std::string strComment;
1401 std::string strStatusBar;
1402 std::string strReserved;
1404 IMPLEMENT_SERIALIZE
1406 READWRITE(this->nVersion);
1407 nVersion = this->nVersion;
1408 READWRITE(nRelayUntil);
1409 READWRITE(nExpiration);
1410 READWRITE(nID);
1411 READWRITE(nCancel);
1412 READWRITE(setCancel);
1413 READWRITE(nMinVer);
1414 READWRITE(nMaxVer);
1415 READWRITE(setSubVer);
1416 READWRITE(nPriority);
1418 READWRITE(strComment);
1419 READWRITE(strStatusBar);
1420 READWRITE(strReserved);
1423 void SetNull()
1425 nVersion = 1;
1426 nRelayUntil = 0;
1427 nExpiration = 0;
1428 nID = 0;
1429 nCancel = 0;
1430 setCancel.clear();
1431 nMinVer = 0;
1432 nMaxVer = 0;
1433 setSubVer.clear();
1434 nPriority = 0;
1436 strComment.clear();
1437 strStatusBar.clear();
1438 strReserved.clear();
1441 std::string ToString() const
1443 std::string strSetCancel;
1444 BOOST_FOREACH(int n, setCancel)
1445 strSetCancel += strprintf("%d ", n);
1446 std::string strSetSubVer;
1447 BOOST_FOREACH(std::string str, setSubVer)
1448 strSetSubVer += "\"" + str + "\" ";
1449 return strprintf(
1450 "CAlert(\n"
1451 " nVersion = %d\n"
1452 " nRelayUntil = %"PRI64d"\n"
1453 " nExpiration = %"PRI64d"\n"
1454 " nID = %d\n"
1455 " nCancel = %d\n"
1456 " setCancel = %s\n"
1457 " nMinVer = %d\n"
1458 " nMaxVer = %d\n"
1459 " setSubVer = %s\n"
1460 " nPriority = %d\n"
1461 " strComment = \"%s\"\n"
1462 " strStatusBar = \"%s\"\n"
1463 ")\n",
1464 nVersion,
1465 nRelayUntil,
1466 nExpiration,
1467 nID,
1468 nCancel,
1469 strSetCancel.c_str(),
1470 nMinVer,
1471 nMaxVer,
1472 strSetSubVer.c_str(),
1473 nPriority,
1474 strComment.c_str(),
1475 strStatusBar.c_str());
1478 void print() const
1480 printf("%s", ToString().c_str());
1484 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1485 class CAlert : public CUnsignedAlert
1487 public:
1488 std::vector<unsigned char> vchMsg;
1489 std::vector<unsigned char> vchSig;
1491 CAlert()
1493 SetNull();
1496 IMPLEMENT_SERIALIZE
1498 READWRITE(vchMsg);
1499 READWRITE(vchSig);
1502 void SetNull()
1504 CUnsignedAlert::SetNull();
1505 vchMsg.clear();
1506 vchSig.clear();
1509 bool IsNull() const
1511 return (nExpiration == 0);
1514 uint256 GetHash() const
1516 return SerializeHash(*this);
1519 bool IsInEffect() const
1521 return (GetAdjustedTime() < nExpiration);
1524 bool Cancels(const CAlert& alert) const
1526 if (!IsInEffect())
1527 return false; // this was a no-op before 31403
1528 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1531 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1533 // TODO: rework for client-version-embedded-in-strSubVer ?
1534 return (IsInEffect() &&
1535 nMinVer <= nVersion && nVersion <= nMaxVer &&
1536 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1539 bool AppliesToMe() const
1541 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1544 bool RelayTo(CNode* pnode) const
1546 if (!IsInEffect())
1547 return false;
1548 // returns true if wasn't already contained in the set
1549 if (pnode->setKnown.insert(GetHash()).second)
1551 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1552 AppliesToMe() ||
1553 GetAdjustedTime() < nRelayUntil)
1555 pnode->PushMessage("alert", *this);
1556 return true;
1559 return false;
1562 bool CheckSignature()
1564 CKey key;
1565 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1566 return error("CAlert::CheckSignature() : SetPubKey failed");
1567 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1568 return error("CAlert::CheckSignature() : verify signature failed");
1570 // Now unserialize the data
1571 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1572 sMsg >> *(CUnsignedAlert*)this;
1573 return true;
1576 bool ProcessAlert();
1579 class CTxMemPool
1581 public:
1582 mutable CCriticalSection cs;
1583 std::map<uint256, CTransaction> mapTx;
1584 std::map<COutPoint, CInPoint> mapNextTx;
1586 bool accept(CTxDB& txdb, CTransaction &tx,
1587 bool fCheckInputs, bool* pfMissingInputs);
1588 bool addUnchecked(CTransaction &tx);
1589 bool remove(CTransaction &tx);
1591 unsigned long size()
1593 LOCK(cs);
1594 return mapTx.size();
1597 bool exists(uint256 hash)
1599 return (mapTx.count(hash) != 0);
1602 CTransaction& lookup(uint256 hash)
1604 return mapTx[hash];
1608 extern CTxMemPool mempool;
1610 #endif