1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
14 #include <io.h> /* for _commit */
28 class CRequestTracker;
31 static const unsigned int MAX_BLOCK_SIZE = 1000000;
32 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
33 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
34 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
35 static const int64 MIN_TX_FEE = CENT;
36 static const int64 MIN_RELAY_TX_FEE = CENT;
37 static const int64 MAX_MONEY = 2000000000 * COIN;
38 static const int64 MAX_MINT_PROOF_OF_WORK = 9999 * COIN;
39 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
40 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
41 static const int COINBASE_MATURITY = 500;
42 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
43 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
45 static const int fHaveUPnP = true;
47 static const int fHaveUPnP = false;
50 static const uint256 hashGenesisBlockOfficial("0x0000000032fe677166d54963b62a4677d8957e87c508eaa4fd7eb1c880cd27e3");
51 static const uint256 hashGenesisBlockTestNet("0x00000001f757bb737f6596503e17cd17b0658ce630cc727c0cca81aec47c9f06");
53 extern CScript COINBASE_FLAGS;
60 extern CCriticalSection cs_main;
61 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
62 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
63 extern uint256 hashGenesisBlock;
64 extern CBlockIndex* pindexGenesisBlock;
65 extern int nBestHeight;
66 extern CBigNum bnBestChainTrust;
67 extern CBigNum bnBestInvalidTrust;
68 extern uint256 hashBestChain;
69 extern CBlockIndex* pindexBest;
70 extern unsigned int nTransactionsUpdated;
71 extern uint64 nLastBlockTx;
72 extern uint64 nLastBlockSize;
73 extern const std::string strMessageMagic;
74 extern double dHashesPerSec;
75 extern int64 nHPSTimerStart;
76 extern int64 nTimeBestReceived;
77 extern CCriticalSection cs_setpwalletRegistered;
78 extern std::set<CWallet*> setpwalletRegistered;
79 extern std::map<uint256, CBlock*> mapOrphanBlocks;
82 extern int64 nTransactionFee;
92 void RegisterWallet(CWallet* pwalletIn);
93 void UnregisterWallet(CWallet* pwalletIn);
94 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
95 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
96 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
97 FILE* AppendBlockFile(unsigned int& nFileRet);
98 bool LoadBlockIndex(bool fAllowNew=true);
99 void PrintBlockTree();
100 bool ProcessMessages(CNode* pfrom);
101 bool SendMessages(CNode* pto, bool fSendTrickle);
102 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
103 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
104 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
105 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
106 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
107 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
108 int64 GetProofOfWorkReward(unsigned int nBits);
109 int64 GetProofOfStakeReward(int64 nCoinAge);
110 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
111 int GetNumBlocksOfPeers();
112 bool IsInitialBlockDownload();
113 std::string GetWarnings(std::string strFor);
114 uint256 WantedByOrphan(const CBlock* pblockOrphan);
115 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
116 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
128 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
130 /** Position on disk for a particular transaction. */
135 unsigned int nBlockPos;
143 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
146 nBlockPos = nBlockPosIn;
150 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
151 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
152 bool IsNull() const { return (nFile == -1); }
154 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
156 return (a.nFile == b.nFile &&
157 a.nBlockPos == b.nBlockPos &&
158 a.nTxPos == b.nTxPos);
161 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
166 std::string ToString() const
171 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
176 printf("%s", ToString().c_str());
182 /** An inpoint - a combination of a transaction and an index n into its vin */
189 CInPoint() { SetNull(); }
190 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
191 void SetNull() { ptx = NULL; n = -1; }
192 bool IsNull() const { return (ptx == NULL && n == -1); }
197 /** An outpoint - a combination of a transaction hash and an index n into its vout */
204 COutPoint() { SetNull(); }
205 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
206 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
207 void SetNull() { hash = 0; n = -1; }
208 bool IsNull() const { return (hash == 0 && n == -1); }
210 friend bool operator<(const COutPoint& a, const COutPoint& b)
212 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
215 friend bool operator==(const COutPoint& a, const COutPoint& b)
217 return (a.hash == b.hash && a.n == b.n);
220 friend bool operator!=(const COutPoint& a, const COutPoint& b)
225 std::string ToString() const
227 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
232 printf("%s\n", ToString().c_str());
239 /** An input of a transaction. It contains the location of the previous
240 * transaction's output that it claims and a signature that matches the
241 * output's public key.
248 unsigned int nSequence;
252 nSequence = std::numeric_limits<unsigned int>::max();
255 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
258 scriptSig = scriptSigIn;
259 nSequence = nSequenceIn;
262 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
264 prevout = COutPoint(hashPrevTx, nOut);
265 scriptSig = scriptSigIn;
266 nSequence = nSequenceIn;
272 READWRITE(scriptSig);
273 READWRITE(nSequence);
278 return (nSequence == std::numeric_limits<unsigned int>::max());
281 friend bool operator==(const CTxIn& a, const CTxIn& b)
283 return (a.prevout == b.prevout &&
284 a.scriptSig == b.scriptSig &&
285 a.nSequence == b.nSequence);
288 friend bool operator!=(const CTxIn& a, const CTxIn& b)
293 std::string ToStringShort() const
295 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
298 std::string ToString() const
302 str += prevout.ToString();
303 if (prevout.IsNull())
304 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
306 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
307 if (nSequence != std::numeric_limits<unsigned int>::max())
308 str += strprintf(", nSequence=%u", nSequence);
315 printf("%s\n", ToString().c_str());
322 /** An output of a transaction. It contains the public key that the next input
323 * must be able to sign with to claim it.
329 CScript scriptPubKey;
336 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
339 scriptPubKey = scriptPubKeyIn;
345 READWRITE(scriptPubKey);
351 scriptPubKey.clear();
356 return (nValue == -1);
362 scriptPubKey.clear();
367 return (nValue == 0 && scriptPubKey.empty());
370 uint256 GetHash() const
372 return SerializeHash(*this);
375 friend bool operator==(const CTxOut& a, const CTxOut& b)
377 return (a.nValue == b.nValue &&
378 a.scriptPubKey == b.scriptPubKey);
381 friend bool operator!=(const CTxOut& a, const CTxOut& b)
386 std::string ToStringShort() const
388 return strprintf(" out amount %s", FormatMoney(nValue).c_str());
391 std::string ToString() const
393 if (IsEmpty()) return "CTxOut(empty)";
394 if (scriptPubKey.size() < 6)
395 return "CTxOut(error)";
396 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
401 printf("%s\n", ToString().c_str());
415 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
417 /** The basic transaction that is broadcasted on the network and contained in
418 * blocks. A transaction can contain multiple inputs and outputs.
425 std::vector<CTxIn> vin;
426 std::vector<CTxOut> vout;
427 unsigned int nLockTime;
429 // Denial-of-service detection:
431 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
440 READWRITE(this->nVersion);
441 nVersion = this->nVersion;
445 READWRITE(nLockTime);
451 nTime = GetAdjustedTime();
455 nDoS = 0; // Denial-of-service prevention
460 return (vin.empty() && vout.empty());
463 uint256 GetHash() const
465 return SerializeHash(*this);
468 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
470 // Time based nLockTime implemented in 0.1.6
473 if (nBlockHeight == 0)
474 nBlockHeight = nBestHeight;
476 nBlockTime = GetAdjustedTime();
477 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
479 BOOST_FOREACH(const CTxIn& txin, vin)
485 bool IsNewerThan(const CTransaction& old) const
487 if (vin.size() != old.vin.size())
489 for (unsigned int i = 0; i < vin.size(); i++)
490 if (vin[i].prevout != old.vin[i].prevout)
494 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
495 for (unsigned int i = 0; i < vin.size(); i++)
497 if (vin[i].nSequence != old.vin[i].nSequence)
499 if (vin[i].nSequence <= nLowest)
502 nLowest = vin[i].nSequence;
504 if (old.vin[i].nSequence < nLowest)
507 nLowest = old.vin[i].nSequence;
514 bool IsCoinBase() const
516 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
519 bool IsCoinStake() const
521 // ppcoin: the coin stake transaction is marked with the first output empty
522 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
525 /** Check for standard transaction types
526 @return True if all outputs (scriptPubKeys) use only standard transaction forms
528 bool IsStandard() const;
530 /** Check for standard transaction types
531 @param[in] mapInputs Map of previous transactions that have outputs we're spending
532 @return True if all inputs (scriptSigs) use only standard transaction forms
533 @see CTransaction::FetchInputs
535 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
537 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
538 @return number of sigops this transaction's outputs will produce when spent
539 @see CTransaction::FetchInputs
541 unsigned int GetLegacySigOpCount() const;
543 /** Count ECDSA signature operations in pay-to-script-hash inputs.
545 @param[in] mapInputs Map of previous transactions that have outputs we're spending
546 @return maximum number of sigops required to validate this transaction's inputs
547 @see CTransaction::FetchInputs
549 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
551 /** Amount of bitcoins spent by this transaction.
552 @return sum of all outputs (note: does not include fees)
554 int64 GetValueOut() const
557 BOOST_FOREACH(const CTxOut& txout, vout)
559 nValueOut += txout.nValue;
560 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
561 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
566 /** Amount of bitcoins coming in to this transaction
567 Note that lightweight clients may not know anything besides the hash of previous transactions,
568 so may not be able to calculate this.
570 @param[in] mapInputs Map of previous transactions that have outputs we're spending
571 @return Sum of value of all inputs (scriptSigs)
572 @see CTransaction::FetchInputs
574 int64 GetValueIn(const MapPrevTx& mapInputs) const;
576 static bool AllowFree(double dPriority)
578 // Large (in bytes) low-priority (new, small-coin) transactions
580 return dPriority > COIN * 144 / 250;
583 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
585 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
586 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
588 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
589 unsigned int nNewBlockSize = nBlockSize + nBytes;
590 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
596 // Transactions under 10K are free
597 // (about 4500bc if made of 50bc inputs)
603 // Free transaction area
604 if (nNewBlockSize < 27000)
609 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
610 if (nMinFee < nBaseFee)
612 BOOST_FOREACH(const CTxOut& txout, vout)
613 if (txout.nValue < CENT)
617 // Raise the price as the block approaches full
618 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
620 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
622 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
625 if (!MoneyRange(nMinFee))
631 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
633 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
635 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
638 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
639 return error("CTransaction::ReadFromDisk() : fseek failed");
644 catch (std::exception &e) {
645 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
648 // Return file pointer
651 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
652 return error("CTransaction::ReadFromDisk() : second fseek failed");
653 *pfileRet = filein.release();
658 friend bool operator==(const CTransaction& a, const CTransaction& b)
660 return (a.nVersion == b.nVersion &&
661 a.nTime == b.nTime &&
664 a.nLockTime == b.nLockTime);
667 friend bool operator!=(const CTransaction& a, const CTransaction& b)
673 std::string ToStringShort() const
676 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
680 std::string ToString() const
683 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
684 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
685 GetHash().ToString().substr(0,10).c_str(),
691 for (unsigned int i = 0; i < vin.size(); i++)
692 str += " " + vin[i].ToString() + "\n";
693 for (unsigned int i = 0; i < vout.size(); i++)
694 str += " " + vout[i].ToString() + "\n";
700 printf("%s", ToString().c_str());
704 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
705 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
706 bool ReadFromDisk(COutPoint prevout);
707 bool DisconnectInputs(CTxDB& txdb);
709 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
711 @param[in] txdb Transaction database
712 @param[in] mapTestPool List of pending changes to the transaction index database
713 @param[in] fBlock True if being called to add a new best-block to the chain
714 @param[in] fMiner True if being called by CreateNewBlock
715 @param[out] inputsRet Pointers to this transaction's inputs
716 @param[out] fInvalid returns true if transaction is invalid
717 @return Returns true if all inputs are in txdb or mapTestPool
719 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
720 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
722 /** Sanity check previous transactions, then, if all checks succeed,
723 mark them as spent by this transaction.
725 @param[in] inputs Previous transactions (from FetchInputs)
726 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
727 @param[in] posThisTx Position of this transaction on disk
728 @param[in] pindexBlock
729 @param[in] fBlock true if called from ConnectBlock
730 @param[in] fMiner true if called from CreateNewBlock
731 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
732 @return Returns true if all checks succeed
734 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
735 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
736 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
737 bool ClientConnectInputs();
738 bool CheckTransaction() const;
739 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
740 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
741 bool CheckProofOfStake(unsigned int nBits) const;
744 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
751 /** A transaction with a merkle branch linking it to the block chain. */
752 class CMerkleTx : public CTransaction
756 std::vector<uint256> vMerkleBranch;
760 mutable bool fMerkleVerified;
768 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
777 fMerkleVerified = false;
783 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
784 nVersion = this->nVersion;
785 READWRITE(hashBlock);
786 READWRITE(vMerkleBranch);
791 int SetMerkleBranch(const CBlock* pblock=NULL);
792 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
793 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
794 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
795 int GetBlocksToMaturity() const;
796 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
797 bool AcceptToMemoryPool();
803 /** A txdb record that contains the disk location of a transaction and the
804 * locations of transactions that spend its outputs. vSpent is really only
805 * used as a flag, but having the location is very helpful for debugging.
811 std::vector<CDiskTxPos> vSpent;
818 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
821 vSpent.resize(nOutputs);
826 if (!(nType & SER_GETHASH))
843 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
845 return (a.pos == b.pos &&
846 a.vSpent == b.vSpent);
849 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
853 int GetDepthInMainChain() const;
861 /** Nodes collect new transactions into a block, hash them into a hash tree,
862 * and scan through nonce values to make the block's hash satisfy proof-of-work
863 * requirements. When they solve the proof-of-work, they broadcast the block
864 * to everyone and the block is added to the block chain. The first transaction
865 * in the block is a special one that creates a new coin owned by the creator
868 * Blocks are appended to blk0001.dat files on disk. Their location on disk
869 * is indexed by CBlockIndex objects in memory.
876 uint256 hashPrevBlock;
877 uint256 hashMerkleRoot;
883 std::vector<CTransaction> vtx;
885 // ppcoin: block signature - signed by coin base txout[0]'s owner
886 std::vector<unsigned char> vchBlockSig;
889 mutable std::vector<uint256> vMerkleTree;
891 // Denial-of-service detection:
893 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
902 READWRITE(this->nVersion);
903 nVersion = this->nVersion;
904 READWRITE(hashPrevBlock);
905 READWRITE(hashMerkleRoot);
910 // ConnectBlock depends on vtx following header to generate CDiskTxPos
911 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
914 READWRITE(vchBlockSig);
918 const_cast<CBlock*>(this)->vtx.clear();
919 const_cast<CBlock*>(this)->vchBlockSig.clear();
942 uint256 GetHash() const
944 return Hash(BEGIN(nVersion), END(nNonce));
947 int64 GetBlockTime() const
952 void UpdateTime(const CBlockIndex* pindexPrev);
954 // ppcoin: two types of block: proof-of-work or proof-of-stake
955 bool IsProofOfStake() const
957 return (vtx.size() > 1 && vtx[1].IsCoinStake());
960 bool IsProofOfWork() const
962 return !IsProofOfStake();
965 std::pair<COutPoint, unsigned int> GetProofOfStake() const
967 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
970 // ppcoin: get max transaction timestamp
971 int64 GetMaxTransactionTime() const
973 int64 maxTransactionTime = 0;
974 BOOST_FOREACH(const CTransaction& tx, vtx)
975 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
976 return maxTransactionTime;
979 uint256 BuildMerkleTree() const
982 BOOST_FOREACH(const CTransaction& tx, vtx)
983 vMerkleTree.push_back(tx.GetHash());
985 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
987 for (int i = 0; i < nSize; i += 2)
989 int i2 = std::min(i+1, nSize-1);
990 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
991 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
995 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
998 std::vector<uint256> GetMerkleBranch(int nIndex) const
1000 if (vMerkleTree.empty())
1002 std::vector<uint256> vMerkleBranch;
1004 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1006 int i = std::min(nIndex^1, nSize-1);
1007 vMerkleBranch.push_back(vMerkleTree[j+i]);
1011 return vMerkleBranch;
1014 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1018 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1021 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1023 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1030 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1032 // Open history file to append
1033 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1035 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1037 // Write index header
1038 unsigned int nSize = fileout.GetSerializeSize(*this);
1039 fileout << FLATDATA(pchMessageStart) << nSize;
1042 long fileOutPos = ftell(fileout);
1044 return error("CBlock::WriteToDisk() : ftell failed");
1045 nBlockPosRet = fileOutPos;
1048 // Flush stdio buffers and commit to disk before returning
1050 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1053 _commit(_fileno(fileout));
1055 fsync(fileno(fileout));
1062 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1066 // Open history file to read
1067 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1069 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1070 if (!fReadTransactions)
1071 filein.nType |= SER_BLOCKHEADERONLY;
1077 catch (std::exception &e) {
1078 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1082 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1083 return error("CBlock::ReadFromDisk() : errors in block header");
1092 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1093 GetHash().ToString().substr(0,20).c_str(),
1095 hashPrevBlock.ToString().substr(0,20).c_str(),
1096 hashMerkleRoot.ToString().substr(0,10).c_str(),
1097 nTime, nBits, nNonce,
1099 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1100 for (unsigned int i = 0; i < vtx.size(); i++)
1105 printf(" vMerkleTree: ");
1106 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1107 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1112 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1113 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1114 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1115 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1116 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1117 bool CheckBlock() const;
1119 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1120 bool SignBlock(const CKeyStore& keystore);
1121 bool CheckBlockSignature() const;
1124 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1132 /** The block chain is a tree shaped structure starting with the
1133 * genesis block at the root, with each block potentially having multiple
1134 * candidates to be the next block. pprev and pnext link a path through the
1135 * main/longest chain. A blockindex may have multiple pprev pointing back
1136 * to it, but pnext will only point forward to the longest branch, or will
1137 * be null if the block is not part of the longest chain.
1142 const uint256* phashBlock;
1146 unsigned int nBlockPos;
1147 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1151 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1152 COutPoint prevoutStake;
1153 unsigned int nStakeTime;
1157 uint256 hashMerkleRoot;
1160 unsigned int nNonce;
1174 fProofOfStake = true;
1175 prevoutStake.SetNull();
1185 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1191 nBlockPos = nBlockPosIn;
1196 fProofOfStake = block.IsProofOfStake();
1199 prevoutStake = block.vtx[1].vin[0].prevout;
1200 nStakeTime = block.vtx[1].nTime;
1204 prevoutStake.SetNull();
1208 nVersion = block.nVersion;
1209 hashMerkleRoot = block.hashMerkleRoot;
1210 nTime = block.nTime;
1211 nBits = block.nBits;
1212 nNonce = block.nNonce;
1215 CBlock GetBlockHeader() const
1218 block.nVersion = nVersion;
1220 block.hashPrevBlock = pprev->GetBlockHash();
1221 block.hashMerkleRoot = hashMerkleRoot;
1222 block.nTime = nTime;
1223 block.nBits = nBits;
1224 block.nNonce = nNonce;
1228 uint256 GetBlockHash() const
1233 int64 GetBlockTime() const
1235 return (int64)nTime;
1238 CBigNum GetBlockTrust() const
1241 bnTarget.SetCompact(nBits);
1244 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1247 bool IsInMainChain() const
1249 return (pnext || this == pindexBest);
1252 bool CheckIndex() const
1254 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1257 bool EraseBlockFromDisk()
1259 // Open history file
1260 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1264 // Overwrite with empty null block
1272 enum { nMedianTimeSpan=11 };
1274 int64 GetMedianTimePast() const
1276 int64 pmedian[nMedianTimeSpan];
1277 int64* pbegin = &pmedian[nMedianTimeSpan];
1278 int64* pend = &pmedian[nMedianTimeSpan];
1280 const CBlockIndex* pindex = this;
1281 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1282 *(--pbegin) = pindex->GetBlockTime();
1284 std::sort(pbegin, pend);
1285 return pbegin[(pend - pbegin)/2];
1288 int64 GetMedianTime() const
1290 const CBlockIndex* pindex = this;
1291 for (int i = 0; i < nMedianTimeSpan/2; i++)
1294 return GetBlockTime();
1295 pindex = pindex->pnext;
1297 return pindex->GetMedianTimePast();
1300 bool IsProofOfWork() const
1302 return !fProofOfStake;
1305 bool IsProofOfStake() const
1307 return fProofOfStake;
1310 std::string ToString() const
1312 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1313 pprev, pnext, nFile, nBlockPos, nHeight,
1314 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1315 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1316 hashMerkleRoot.ToString().substr(0,10).c_str(),
1317 GetBlockHash().ToString().substr(0,20).c_str());
1322 printf("%s\n", ToString().c_str());
1328 /** Used to marshal pointers into hashes for db storage. */
1329 class CDiskBlockIndex : public CBlockIndex
1341 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1343 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1344 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1349 if (!(nType & SER_GETHASH))
1350 READWRITE(nVersion);
1352 READWRITE(hashNext);
1354 READWRITE(nBlockPos);
1357 READWRITE(nMoneySupply);
1358 READWRITE(fProofOfStake);
1361 READWRITE(prevoutStake);
1362 READWRITE(nStakeTime);
1366 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1367 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1371 READWRITE(this->nVersion);
1372 READWRITE(hashPrev);
1373 READWRITE(hashMerkleRoot);
1379 uint256 GetBlockHash() const
1382 block.nVersion = nVersion;
1383 block.hashPrevBlock = hashPrev;
1384 block.hashMerkleRoot = hashMerkleRoot;
1385 block.nTime = nTime;
1386 block.nBits = nBits;
1387 block.nNonce = nNonce;
1388 return block.GetHash();
1392 std::string ToString() const
1394 std::string str = "CDiskBlockIndex(";
1395 str += CBlockIndex::ToString();
1396 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1397 GetBlockHash().ToString().c_str(),
1398 hashPrev.ToString().substr(0,20).c_str(),
1399 hashNext.ToString().substr(0,20).c_str());
1405 printf("%s\n", ToString().c_str());
1416 /** Describes a place in the block chain to another node such that if the
1417 * other node doesn't have the same branch, it can find a recent common trunk.
1418 * The further back it is, the further before the fork it may be.
1423 std::vector<uint256> vHave;
1430 explicit CBlockLocator(const CBlockIndex* pindex)
1435 explicit CBlockLocator(uint256 hashBlock)
1437 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1438 if (mi != mapBlockIndex.end())
1442 CBlockLocator(const std::vector<uint256>& vHaveIn)
1449 if (!(nType & SER_GETHASH))
1450 READWRITE(nVersion);
1461 return vHave.empty();
1464 void Set(const CBlockIndex* pindex)
1470 vHave.push_back(pindex->GetBlockHash());
1472 // Exponentially larger steps back
1473 for (int i = 0; pindex && i < nStep; i++)
1474 pindex = pindex->pprev;
1475 if (vHave.size() > 10)
1478 vHave.push_back(hashGenesisBlock);
1481 int GetDistanceBack()
1483 // Retrace how far back it was in the sender's branch
1486 BOOST_FOREACH(const uint256& hash, vHave)
1488 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1489 if (mi != mapBlockIndex.end())
1491 CBlockIndex* pindex = (*mi).second;
1492 if (pindex->IsInMainChain())
1502 CBlockIndex* GetBlockIndex()
1504 // Find the first block the caller has in the main chain
1505 BOOST_FOREACH(const uint256& hash, vHave)
1507 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1508 if (mi != mapBlockIndex.end())
1510 CBlockIndex* pindex = (*mi).second;
1511 if (pindex->IsInMainChain())
1515 return pindexGenesisBlock;
1518 uint256 GetBlockHash()
1520 // Find the first block the caller has in the main chain
1521 BOOST_FOREACH(const uint256& hash, vHave)
1523 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1524 if (mi != mapBlockIndex.end())
1526 CBlockIndex* pindex = (*mi).second;
1527 if (pindex->IsInMainChain())
1531 return hashGenesisBlock;
1536 CBlockIndex* pindex = GetBlockIndex();
1539 return pindex->nHeight;
1551 /** Alerts are for notifying old versions if they become too obsolete and
1552 * need to upgrade. The message is displayed in the status bar.
1553 * Alert messages are broadcast as a vector of signed data. Unserializing may
1554 * not read the entire buffer if the alert is for a newer version, but older
1555 * versions can still relay the original data.
1557 class CUnsignedAlert
1561 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1565 std::set<int> setCancel;
1566 int nMinVer; // lowest version inclusive
1567 int nMaxVer; // highest version inclusive
1568 std::set<std::string> setSubVer; // empty matches all
1572 std::string strComment;
1573 std::string strStatusBar;
1574 std::string strReserved;
1578 READWRITE(this->nVersion);
1579 nVersion = this->nVersion;
1580 READWRITE(nRelayUntil);
1581 READWRITE(nExpiration);
1584 READWRITE(setCancel);
1587 READWRITE(setSubVer);
1588 READWRITE(nPriority);
1590 READWRITE(strComment);
1591 READWRITE(strStatusBar);
1592 READWRITE(strReserved);
1609 strStatusBar.clear();
1610 strReserved.clear();
1613 std::string ToString() const
1615 std::string strSetCancel;
1616 BOOST_FOREACH(int n, setCancel)
1617 strSetCancel += strprintf("%d ", n);
1618 std::string strSetSubVer;
1619 BOOST_FOREACH(std::string str, setSubVer)
1620 strSetSubVer += "\"" + str + "\" ";
1624 " nRelayUntil = %"PRI64d"\n"
1625 " nExpiration = %"PRI64d"\n"
1633 " strComment = \"%s\"\n"
1634 " strStatusBar = \"%s\"\n"
1641 strSetCancel.c_str(),
1644 strSetSubVer.c_str(),
1647 strStatusBar.c_str());
1652 printf("%s", ToString().c_str());
1656 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1657 class CAlert : public CUnsignedAlert
1660 std::vector<unsigned char> vchMsg;
1661 std::vector<unsigned char> vchSig;
1676 CUnsignedAlert::SetNull();
1683 return (nExpiration == 0);
1686 uint256 GetHash() const
1688 return SerializeHash(*this);
1691 bool IsInEffect() const
1693 return (GetAdjustedTime() < nExpiration);
1696 bool Cancels(const CAlert& alert) const
1699 return false; // this was a no-op before 31403
1700 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1703 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1705 // TODO: rework for client-version-embedded-in-strSubVer ?
1706 return (IsInEffect() &&
1707 nMinVer <= nVersion && nVersion <= nMaxVer &&
1708 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1711 bool AppliesToMe() const
1713 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1716 bool RelayTo(CNode* pnode) const
1720 // returns true if wasn't already contained in the set
1721 if (pnode->setKnown.insert(GetHash()).second)
1723 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1725 GetAdjustedTime() < nRelayUntil)
1727 pnode->PushMessage("alert", *this);
1734 bool CheckSignature()
1737 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1738 return error("CAlert::CheckSignature() : SetPubKey failed");
1739 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1740 return error("CAlert::CheckSignature() : verify signature failed");
1742 // Now unserialize the data
1743 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1744 sMsg >> *(CUnsignedAlert*)this;
1748 bool ProcessAlert();
1754 mutable CCriticalSection cs;
1755 std::map<uint256, CTransaction> mapTx;
1756 std::map<COutPoint, CInPoint> mapNextTx;
1758 bool accept(CTxDB& txdb, CTransaction &tx,
1759 bool fCheckInputs, bool* pfMissingInputs);
1760 bool addUnchecked(CTransaction &tx);
1761 bool remove(CTransaction &tx);
1763 unsigned long size()
1766 return mapTx.size();
1769 bool exists(uint256 hash)
1771 return (mapTx.count(hash) != 0);
1774 CTransaction& lookup(uint256 hash)
1780 extern CTxMemPool mempool;