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_PPC = 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 unsigned int nStakeMinAge;
65 extern int nCoinbaseMaturity;
66 extern CBlockIndex* pindexGenesisBlock;
67 extern int nBestHeight;
68 extern CBigNum bnBestChainTrust;
69 extern CBigNum bnBestInvalidTrust;
70 extern uint256 hashBestChain;
71 extern CBlockIndex* pindexBest;
72 extern unsigned int nTransactionsUpdated;
73 extern uint64 nLastBlockTx;
74 extern uint64 nLastBlockSize;
75 extern int64 nLastCoinStakeSearchInterval;
76 extern const std::string strMessageMagic;
77 extern double dHashesPerSec;
78 extern int64 nHPSTimerStart;
79 extern int64 nTimeBestReceived;
80 extern CCriticalSection cs_setpwalletRegistered;
81 extern std::set<CWallet*> setpwalletRegistered;
82 extern std::map<uint256, CBlock*> mapOrphanBlocks;
85 extern int64 nTransactionFee;
95 void RegisterWallet(CWallet* pwalletIn);
96 void UnregisterWallet(CWallet* pwalletIn);
97 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
98 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
99 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
100 FILE* AppendBlockFile(unsigned int& nFileRet);
101 bool LoadBlockIndex(bool fAllowNew=true);
102 void PrintBlockTree();
103 bool ProcessMessages(CNode* pfrom);
104 bool SendMessages(CNode* pto, bool fSendTrickle);
105 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
106 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
107 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
108 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
109 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
110 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
111 int64 GetProofOfWorkReward(unsigned int nBits);
112 int64 GetProofOfStakeReward(int64 nCoinAge);
113 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
114 int GetNumBlocksOfPeers();
115 bool IsInitialBlockDownload();
116 std::string GetWarnings(std::string strFor);
117 uint256 WantedByOrphan(const CBlock* pblockOrphan);
118 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
119 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
131 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
133 /** Position on disk for a particular transaction. */
138 unsigned int nBlockPos;
146 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
149 nBlockPos = nBlockPosIn;
153 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
154 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
155 bool IsNull() const { return (nFile == -1); }
157 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
159 return (a.nFile == b.nFile &&
160 a.nBlockPos == b.nBlockPos &&
161 a.nTxPos == b.nTxPos);
164 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
169 std::string ToString() const
174 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
179 printf("%s", ToString().c_str());
185 /** An inpoint - a combination of a transaction and an index n into its vin */
192 CInPoint() { SetNull(); }
193 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
194 void SetNull() { ptx = NULL; n = -1; }
195 bool IsNull() const { return (ptx == NULL && n == -1); }
200 /** An outpoint - a combination of a transaction hash and an index n into its vout */
207 COutPoint() { SetNull(); }
208 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
209 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
210 void SetNull() { hash = 0; n = -1; }
211 bool IsNull() const { return (hash == 0 && n == -1); }
213 friend bool operator<(const COutPoint& a, const COutPoint& b)
215 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
218 friend bool operator==(const COutPoint& a, const COutPoint& b)
220 return (a.hash == b.hash && a.n == b.n);
223 friend bool operator!=(const COutPoint& a, const COutPoint& b)
228 std::string ToString() const
230 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
235 printf("%s\n", ToString().c_str());
242 /** An input of a transaction. It contains the location of the previous
243 * transaction's output that it claims and a signature that matches the
244 * output's public key.
251 unsigned int nSequence;
255 nSequence = std::numeric_limits<unsigned int>::max();
258 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
261 scriptSig = scriptSigIn;
262 nSequence = nSequenceIn;
265 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
267 prevout = COutPoint(hashPrevTx, nOut);
268 scriptSig = scriptSigIn;
269 nSequence = nSequenceIn;
275 READWRITE(scriptSig);
276 READWRITE(nSequence);
281 return (nSequence == std::numeric_limits<unsigned int>::max());
284 friend bool operator==(const CTxIn& a, const CTxIn& b)
286 return (a.prevout == b.prevout &&
287 a.scriptSig == b.scriptSig &&
288 a.nSequence == b.nSequence);
291 friend bool operator!=(const CTxIn& a, const CTxIn& b)
296 std::string ToStringShort() const
298 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
301 std::string ToString() const
305 str += prevout.ToString();
306 if (prevout.IsNull())
307 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
309 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
310 if (nSequence != std::numeric_limits<unsigned int>::max())
311 str += strprintf(", nSequence=%u", nSequence);
318 printf("%s\n", ToString().c_str());
325 /** An output of a transaction. It contains the public key that the next input
326 * must be able to sign with to claim it.
332 CScript scriptPubKey;
339 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
342 scriptPubKey = scriptPubKeyIn;
348 READWRITE(scriptPubKey);
354 scriptPubKey.clear();
359 return (nValue == -1);
365 scriptPubKey.clear();
370 return (nValue == 0 && scriptPubKey.empty());
373 uint256 GetHash() const
375 return SerializeHash(*this);
378 friend bool operator==(const CTxOut& a, const CTxOut& b)
380 return (a.nValue == b.nValue &&
381 a.scriptPubKey == b.scriptPubKey);
384 friend bool operator!=(const CTxOut& a, const CTxOut& b)
389 std::string ToStringShort() const
391 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
394 std::string ToString() const
396 if (IsEmpty()) return "CTxOut(empty)";
397 if (scriptPubKey.size() < 6)
398 return "CTxOut(error)";
399 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
404 printf("%s\n", ToString().c_str());
418 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
420 /** The basic transaction that is broadcasted on the network and contained in
421 * blocks. A transaction can contain multiple inputs and outputs.
428 std::vector<CTxIn> vin;
429 std::vector<CTxOut> vout;
430 unsigned int nLockTime;
432 // Denial-of-service detection:
434 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
443 READWRITE(this->nVersion);
444 nVersion = this->nVersion;
448 READWRITE(nLockTime);
454 nTime = GetAdjustedTime();
458 nDoS = 0; // Denial-of-service prevention
463 return (vin.empty() && vout.empty());
466 uint256 GetHash() const
468 return SerializeHash(*this);
471 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
473 // Time based nLockTime implemented in 0.1.6
476 if (nBlockHeight == 0)
477 nBlockHeight = nBestHeight;
479 nBlockTime = GetAdjustedTime();
480 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
482 BOOST_FOREACH(const CTxIn& txin, vin)
488 bool IsNewerThan(const CTransaction& old) const
490 if (vin.size() != old.vin.size())
492 for (unsigned int i = 0; i < vin.size(); i++)
493 if (vin[i].prevout != old.vin[i].prevout)
497 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
498 for (unsigned int i = 0; i < vin.size(); i++)
500 if (vin[i].nSequence != old.vin[i].nSequence)
502 if (vin[i].nSequence <= nLowest)
505 nLowest = vin[i].nSequence;
507 if (old.vin[i].nSequence < nLowest)
510 nLowest = old.vin[i].nSequence;
517 bool IsCoinBase() const
519 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
522 bool IsCoinStake() const
524 // ppcoin: the coin stake transaction is marked with the first output empty
525 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
528 /** Check for standard transaction types
529 @return True if all outputs (scriptPubKeys) use only standard transaction forms
531 bool IsStandard() const;
533 /** Check for standard transaction types
534 @param[in] mapInputs Map of previous transactions that have outputs we're spending
535 @return True if all inputs (scriptSigs) use only standard transaction forms
536 @see CTransaction::FetchInputs
538 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
540 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
541 @return number of sigops this transaction's outputs will produce when spent
542 @see CTransaction::FetchInputs
544 unsigned int GetLegacySigOpCount() const;
546 /** Count ECDSA signature operations in pay-to-script-hash inputs.
548 @param[in] mapInputs Map of previous transactions that have outputs we're spending
549 @return maximum number of sigops required to validate this transaction's inputs
550 @see CTransaction::FetchInputs
552 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
554 /** Amount of bitcoins spent by this transaction.
555 @return sum of all outputs (note: does not include fees)
557 int64 GetValueOut() const
560 BOOST_FOREACH(const CTxOut& txout, vout)
562 nValueOut += txout.nValue;
563 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
564 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
569 /** Amount of bitcoins coming in to this transaction
570 Note that lightweight clients may not know anything besides the hash of previous transactions,
571 so may not be able to calculate this.
573 @param[in] mapInputs Map of previous transactions that have outputs we're spending
574 @return Sum of value of all inputs (scriptSigs)
575 @see CTransaction::FetchInputs
577 int64 GetValueIn(const MapPrevTx& mapInputs) const;
579 static bool AllowFree(double dPriority)
581 // Large (in bytes) low-priority (new, small-coin) transactions
583 return dPriority > COIN * 144 / 250;
586 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
588 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
589 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
591 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
592 unsigned int nNewBlockSize = nBlockSize + nBytes;
593 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
599 // Transactions under 10K are free
600 // (about 4500bc if made of 50bc inputs)
606 // Free transaction area
607 if (nNewBlockSize < 27000)
612 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
613 if (nMinFee < nBaseFee)
615 BOOST_FOREACH(const CTxOut& txout, vout)
616 if (txout.nValue < CENT)
620 // Raise the price as the block approaches full
621 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
623 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
625 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
628 if (!MoneyRange(nMinFee))
634 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
636 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
638 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
641 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
642 return error("CTransaction::ReadFromDisk() : fseek failed");
647 catch (std::exception &e) {
648 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
651 // Return file pointer
654 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
655 return error("CTransaction::ReadFromDisk() : second fseek failed");
656 *pfileRet = filein.release();
661 friend bool operator==(const CTransaction& a, const CTransaction& b)
663 return (a.nVersion == b.nVersion &&
664 a.nTime == b.nTime &&
667 a.nLockTime == b.nLockTime);
670 friend bool operator!=(const CTransaction& a, const CTransaction& b)
676 std::string ToStringShort() const
679 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
683 std::string ToString() const
686 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
687 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
688 GetHash().ToString().substr(0,10).c_str(),
694 for (unsigned int i = 0; i < vin.size(); i++)
695 str += " " + vin[i].ToString() + "\n";
696 for (unsigned int i = 0; i < vout.size(); i++)
697 str += " " + vout[i].ToString() + "\n";
703 printf("%s", ToString().c_str());
707 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
708 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
709 bool ReadFromDisk(COutPoint prevout);
710 bool DisconnectInputs(CTxDB& txdb);
712 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
714 @param[in] txdb Transaction database
715 @param[in] mapTestPool List of pending changes to the transaction index database
716 @param[in] fBlock True if being called to add a new best-block to the chain
717 @param[in] fMiner True if being called by CreateNewBlock
718 @param[out] inputsRet Pointers to this transaction's inputs
719 @param[out] fInvalid returns true if transaction is invalid
720 @return Returns true if all inputs are in txdb or mapTestPool
722 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
723 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
725 /** Sanity check previous transactions, then, if all checks succeed,
726 mark them as spent by this transaction.
728 @param[in] inputs Previous transactions (from FetchInputs)
729 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
730 @param[in] posThisTx Position of this transaction on disk
731 @param[in] pindexBlock
732 @param[in] fBlock true if called from ConnectBlock
733 @param[in] fMiner true if called from CreateNewBlock
734 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
735 @return Returns true if all checks succeed
737 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
738 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
739 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
740 bool ClientConnectInputs();
741 bool CheckTransaction() const;
742 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
743 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
744 bool CheckProofOfStake(unsigned int nBits) const;
747 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
754 /** A transaction with a merkle branch linking it to the block chain. */
755 class CMerkleTx : public CTransaction
759 std::vector<uint256> vMerkleBranch;
763 mutable bool fMerkleVerified;
771 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
780 fMerkleVerified = false;
786 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
787 nVersion = this->nVersion;
788 READWRITE(hashBlock);
789 READWRITE(vMerkleBranch);
794 int SetMerkleBranch(const CBlock* pblock=NULL);
795 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
796 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
797 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
798 int GetBlocksToMaturity() const;
799 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
800 bool AcceptToMemoryPool();
806 /** A txdb record that contains the disk location of a transaction and the
807 * locations of transactions that spend its outputs. vSpent is really only
808 * used as a flag, but having the location is very helpful for debugging.
814 std::vector<CDiskTxPos> vSpent;
821 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
824 vSpent.resize(nOutputs);
829 if (!(nType & SER_GETHASH))
846 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
848 return (a.pos == b.pos &&
849 a.vSpent == b.vSpent);
852 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
856 int GetDepthInMainChain() const;
864 /** Nodes collect new transactions into a block, hash them into a hash tree,
865 * and scan through nonce values to make the block's hash satisfy proof-of-work
866 * requirements. When they solve the proof-of-work, they broadcast the block
867 * to everyone and the block is added to the block chain. The first transaction
868 * in the block is a special one that creates a new coin owned by the creator
871 * Blocks are appended to blk0001.dat files on disk. Their location on disk
872 * is indexed by CBlockIndex objects in memory.
879 uint256 hashPrevBlock;
880 uint256 hashMerkleRoot;
886 std::vector<CTransaction> vtx;
888 // ppcoin: block signature - signed by coin base txout[0]'s owner
889 std::vector<unsigned char> vchBlockSig;
892 mutable std::vector<uint256> vMerkleTree;
894 // Denial-of-service detection:
896 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
905 READWRITE(this->nVersion);
906 nVersion = this->nVersion;
907 READWRITE(hashPrevBlock);
908 READWRITE(hashMerkleRoot);
913 // ConnectBlock depends on vtx following header to generate CDiskTxPos
914 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
917 READWRITE(vchBlockSig);
921 const_cast<CBlock*>(this)->vtx.clear();
922 const_cast<CBlock*>(this)->vchBlockSig.clear();
945 uint256 GetHash() const
947 return Hash(BEGIN(nVersion), END(nNonce));
950 int64 GetBlockTime() const
955 void UpdateTime(const CBlockIndex* pindexPrev);
957 // ppcoin: two types of block: proof-of-work or proof-of-stake
958 bool IsProofOfStake() const
960 return (vtx.size() > 1 && vtx[1].IsCoinStake());
963 bool IsProofOfWork() const
965 return !IsProofOfStake();
968 std::pair<COutPoint, unsigned int> GetProofOfStake() const
970 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
973 // ppcoin: get max transaction timestamp
974 int64 GetMaxTransactionTime() const
976 int64 maxTransactionTime = 0;
977 BOOST_FOREACH(const CTransaction& tx, vtx)
978 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
979 return maxTransactionTime;
982 uint256 BuildMerkleTree() const
985 BOOST_FOREACH(const CTransaction& tx, vtx)
986 vMerkleTree.push_back(tx.GetHash());
988 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
990 for (int i = 0; i < nSize; i += 2)
992 int i2 = std::min(i+1, nSize-1);
993 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
994 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
998 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1001 std::vector<uint256> GetMerkleBranch(int nIndex) const
1003 if (vMerkleTree.empty())
1005 std::vector<uint256> vMerkleBranch;
1007 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1009 int i = std::min(nIndex^1, nSize-1);
1010 vMerkleBranch.push_back(vMerkleTree[j+i]);
1014 return vMerkleBranch;
1017 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1021 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1024 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1026 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1033 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1035 // Open history file to append
1036 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1038 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1040 // Write index header
1041 unsigned char pchMessageStart[4];
1042 GetMessageStart(pchMessageStart, true);
1043 unsigned int nSize = fileout.GetSerializeSize(*this);
1044 fileout << FLATDATA(pchMessageStart) << nSize;
1047 long fileOutPos = ftell(fileout);
1049 return error("CBlock::WriteToDisk() : ftell failed");
1050 nBlockPosRet = fileOutPos;
1053 // Flush stdio buffers and commit to disk before returning
1055 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1058 _commit(_fileno(fileout));
1060 fsync(fileno(fileout));
1067 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1071 // Open history file to read
1072 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1074 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1075 if (!fReadTransactions)
1076 filein.nType |= SER_BLOCKHEADERONLY;
1082 catch (std::exception &e) {
1083 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1087 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1088 return error("CBlock::ReadFromDisk() : errors in block header");
1097 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1098 GetHash().ToString().substr(0,20).c_str(),
1100 hashPrevBlock.ToString().substr(0,20).c_str(),
1101 hashMerkleRoot.ToString().substr(0,10).c_str(),
1102 nTime, nBits, nNonce,
1104 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1105 for (unsigned int i = 0; i < vtx.size(); i++)
1110 printf(" vMerkleTree: ");
1111 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1112 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1117 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1118 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1119 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1120 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1121 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1122 bool CheckBlock() const;
1124 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1125 bool SignBlock(const CKeyStore& keystore);
1126 bool CheckBlockSignature() const;
1129 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1137 /** The block chain is a tree shaped structure starting with the
1138 * genesis block at the root, with each block potentially having multiple
1139 * candidates to be the next block. pprev and pnext link a path through the
1140 * main/longest chain. A blockindex may have multiple pprev pointing back
1141 * to it, but pnext will only point forward to the longest branch, or will
1142 * be null if the block is not part of the longest chain.
1147 const uint256* phashBlock;
1151 unsigned int nBlockPos;
1152 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1156 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1157 COutPoint prevoutStake;
1158 unsigned int nStakeTime;
1162 uint256 hashMerkleRoot;
1165 unsigned int nNonce;
1179 fProofOfStake = true;
1180 prevoutStake.SetNull();
1190 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1196 nBlockPos = nBlockPosIn;
1201 fProofOfStake = block.IsProofOfStake();
1204 prevoutStake = block.vtx[1].vin[0].prevout;
1205 nStakeTime = block.vtx[1].nTime;
1209 prevoutStake.SetNull();
1213 nVersion = block.nVersion;
1214 hashMerkleRoot = block.hashMerkleRoot;
1215 nTime = block.nTime;
1216 nBits = block.nBits;
1217 nNonce = block.nNonce;
1220 CBlock GetBlockHeader() const
1223 block.nVersion = nVersion;
1225 block.hashPrevBlock = pprev->GetBlockHash();
1226 block.hashMerkleRoot = hashMerkleRoot;
1227 block.nTime = nTime;
1228 block.nBits = nBits;
1229 block.nNonce = nNonce;
1233 uint256 GetBlockHash() const
1238 int64 GetBlockTime() const
1240 return (int64)nTime;
1243 CBigNum GetBlockTrust() const
1246 bnTarget.SetCompact(nBits);
1249 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1252 bool IsInMainChain() const
1254 return (pnext || this == pindexBest);
1257 bool CheckIndex() const
1259 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1262 bool EraseBlockFromDisk()
1264 // Open history file
1265 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1269 // Overwrite with empty null block
1277 enum { nMedianTimeSpan=11 };
1279 int64 GetMedianTimePast() const
1281 int64 pmedian[nMedianTimeSpan];
1282 int64* pbegin = &pmedian[nMedianTimeSpan];
1283 int64* pend = &pmedian[nMedianTimeSpan];
1285 const CBlockIndex* pindex = this;
1286 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1287 *(--pbegin) = pindex->GetBlockTime();
1289 std::sort(pbegin, pend);
1290 return pbegin[(pend - pbegin)/2];
1293 int64 GetMedianTime() const
1295 const CBlockIndex* pindex = this;
1296 for (int i = 0; i < nMedianTimeSpan/2; i++)
1299 return GetBlockTime();
1300 pindex = pindex->pnext;
1302 return pindex->GetMedianTimePast();
1305 bool IsProofOfWork() const
1307 return !fProofOfStake;
1310 bool IsProofOfStake() const
1312 return fProofOfStake;
1315 std::string ToString() const
1317 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)",
1318 pprev, pnext, nFile, nBlockPos, nHeight,
1319 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1320 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1321 hashMerkleRoot.ToString().substr(0,10).c_str(),
1322 GetBlockHash().ToString().substr(0,20).c_str());
1327 printf("%s\n", ToString().c_str());
1333 /** Used to marshal pointers into hashes for db storage. */
1334 class CDiskBlockIndex : public CBlockIndex
1346 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1348 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1349 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1354 if (!(nType & SER_GETHASH))
1355 READWRITE(nVersion);
1357 READWRITE(hashNext);
1359 READWRITE(nBlockPos);
1362 READWRITE(nMoneySupply);
1363 READWRITE(fProofOfStake);
1366 READWRITE(prevoutStake);
1367 READWRITE(nStakeTime);
1371 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1372 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1376 READWRITE(this->nVersion);
1377 READWRITE(hashPrev);
1378 READWRITE(hashMerkleRoot);
1384 uint256 GetBlockHash() const
1387 block.nVersion = nVersion;
1388 block.hashPrevBlock = hashPrev;
1389 block.hashMerkleRoot = hashMerkleRoot;
1390 block.nTime = nTime;
1391 block.nBits = nBits;
1392 block.nNonce = nNonce;
1393 return block.GetHash();
1397 std::string ToString() const
1399 std::string str = "CDiskBlockIndex(";
1400 str += CBlockIndex::ToString();
1401 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1402 GetBlockHash().ToString().c_str(),
1403 hashPrev.ToString().substr(0,20).c_str(),
1404 hashNext.ToString().substr(0,20).c_str());
1410 printf("%s\n", ToString().c_str());
1421 /** Describes a place in the block chain to another node such that if the
1422 * other node doesn't have the same branch, it can find a recent common trunk.
1423 * The further back it is, the further before the fork it may be.
1428 std::vector<uint256> vHave;
1435 explicit CBlockLocator(const CBlockIndex* pindex)
1440 explicit CBlockLocator(uint256 hashBlock)
1442 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1443 if (mi != mapBlockIndex.end())
1447 CBlockLocator(const std::vector<uint256>& vHaveIn)
1454 if (!(nType & SER_GETHASH))
1455 READWRITE(nVersion);
1466 return vHave.empty();
1469 void Set(const CBlockIndex* pindex)
1475 vHave.push_back(pindex->GetBlockHash());
1477 // Exponentially larger steps back
1478 for (int i = 0; pindex && i < nStep; i++)
1479 pindex = pindex->pprev;
1480 if (vHave.size() > 10)
1483 vHave.push_back(hashGenesisBlock);
1486 int GetDistanceBack()
1488 // Retrace how far back it was in the sender's branch
1491 BOOST_FOREACH(const uint256& hash, vHave)
1493 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1494 if (mi != mapBlockIndex.end())
1496 CBlockIndex* pindex = (*mi).second;
1497 if (pindex->IsInMainChain())
1507 CBlockIndex* GetBlockIndex()
1509 // Find the first block the caller has in the main chain
1510 BOOST_FOREACH(const uint256& hash, vHave)
1512 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1513 if (mi != mapBlockIndex.end())
1515 CBlockIndex* pindex = (*mi).second;
1516 if (pindex->IsInMainChain())
1520 return pindexGenesisBlock;
1523 uint256 GetBlockHash()
1525 // Find the first block the caller has in the main chain
1526 BOOST_FOREACH(const uint256& hash, vHave)
1528 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1529 if (mi != mapBlockIndex.end())
1531 CBlockIndex* pindex = (*mi).second;
1532 if (pindex->IsInMainChain())
1536 return hashGenesisBlock;
1541 CBlockIndex* pindex = GetBlockIndex();
1544 return pindex->nHeight;
1556 /** Alerts are for notifying old versions if they become too obsolete and
1557 * need to upgrade. The message is displayed in the status bar.
1558 * Alert messages are broadcast as a vector of signed data. Unserializing may
1559 * not read the entire buffer if the alert is for a newer version, but older
1560 * versions can still relay the original data.
1562 class CUnsignedAlert
1566 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1570 std::set<int> setCancel;
1571 int nMinVer; // lowest version inclusive
1572 int nMaxVer; // highest version inclusive
1573 std::set<std::string> setSubVer; // empty matches all
1577 std::string strComment;
1578 std::string strStatusBar;
1579 std::string strReserved;
1583 READWRITE(this->nVersion);
1584 nVersion = this->nVersion;
1585 READWRITE(nRelayUntil);
1586 READWRITE(nExpiration);
1589 READWRITE(setCancel);
1592 READWRITE(setSubVer);
1593 READWRITE(nPriority);
1595 READWRITE(strComment);
1596 READWRITE(strStatusBar);
1597 READWRITE(strReserved);
1614 strStatusBar.clear();
1615 strReserved.clear();
1618 std::string ToString() const
1620 std::string strSetCancel;
1621 BOOST_FOREACH(int n, setCancel)
1622 strSetCancel += strprintf("%d ", n);
1623 std::string strSetSubVer;
1624 BOOST_FOREACH(std::string str, setSubVer)
1625 strSetSubVer += "\"" + str + "\" ";
1629 " nRelayUntil = %"PRI64d"\n"
1630 " nExpiration = %"PRI64d"\n"
1638 " strComment = \"%s\"\n"
1639 " strStatusBar = \"%s\"\n"
1646 strSetCancel.c_str(),
1649 strSetSubVer.c_str(),
1652 strStatusBar.c_str());
1657 printf("%s", ToString().c_str());
1661 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1662 class CAlert : public CUnsignedAlert
1665 std::vector<unsigned char> vchMsg;
1666 std::vector<unsigned char> vchSig;
1681 CUnsignedAlert::SetNull();
1688 return (nExpiration == 0);
1691 uint256 GetHash() const
1693 return SerializeHash(*this);
1696 bool IsInEffect() const
1698 return (GetAdjustedTime() < nExpiration);
1701 bool Cancels(const CAlert& alert) const
1704 return false; // this was a no-op before 31403
1705 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1708 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1710 // TODO: rework for client-version-embedded-in-strSubVer ?
1711 return (IsInEffect() &&
1712 nMinVer <= nVersion && nVersion <= nMaxVer &&
1713 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1716 bool AppliesToMe() const
1718 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1721 bool RelayTo(CNode* pnode) const
1725 // returns true if wasn't already contained in the set
1726 if (pnode->setKnown.insert(GetHash()).second)
1728 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1730 GetAdjustedTime() < nRelayUntil)
1732 pnode->PushMessage("alert", *this);
1739 bool CheckSignature()
1742 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1743 return error("CAlert::CheckSignature() : SetPubKey failed");
1744 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1745 return error("CAlert::CheckSignature() : verify signature failed");
1747 // Now unserialize the data
1748 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1749 sMsg >> *(CUnsignedAlert*)this;
1753 bool ProcessAlert();
1759 mutable CCriticalSection cs;
1760 std::map<uint256, CTransaction> mapTx;
1761 std::map<COutPoint, CInPoint> mapNextTx;
1763 bool accept(CTxDB& txdb, CTransaction &tx,
1764 bool fCheckInputs, bool* pfMissingInputs);
1765 bool addUnchecked(CTransaction &tx);
1766 bool remove(CTransaction &tx);
1768 unsigned long size()
1771 return mapTx.size();
1774 bool exists(uint256 hash)
1776 return (mapTx.count(hash) != 0);
1779 CTransaction& lookup(uint256 hash)
1785 extern CTxMemPool mempool;