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 static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours
55 extern CScript COINBASE_FLAGS;
62 extern CCriticalSection cs_main;
63 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
64 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
65 extern uint256 hashGenesisBlock;
66 extern unsigned int nStakeMinAge;
67 extern int nCoinbaseMaturity;
68 extern CBlockIndex* pindexGenesisBlock;
69 extern int nBestHeight;
70 extern CBigNum bnBestChainTrust;
71 extern CBigNum bnBestInvalidTrust;
72 extern uint256 hashBestChain;
73 extern CBlockIndex* pindexBest;
74 extern unsigned int nTransactionsUpdated;
75 extern uint64 nLastBlockTx;
76 extern uint64 nLastBlockSize;
77 extern int64 nLastCoinStakeSearchInterval;
78 extern const std::string strMessageMagic;
79 extern double dHashesPerSec;
80 extern int64 nHPSTimerStart;
81 extern int64 nTimeBestReceived;
82 extern CCriticalSection cs_setpwalletRegistered;
83 extern std::set<CWallet*> setpwalletRegistered;
84 extern std::map<uint256, CBlock*> mapOrphanBlocks;
87 extern int64 nTransactionFee;
97 void RegisterWallet(CWallet* pwalletIn);
98 void UnregisterWallet(CWallet* pwalletIn);
99 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
100 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
101 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
102 FILE* AppendBlockFile(unsigned int& nFileRet);
103 bool LoadBlockIndex(bool fAllowNew=true);
104 void PrintBlockTree();
105 bool ProcessMessages(CNode* pfrom);
106 bool SendMessages(CNode* pto, bool fSendTrickle);
107 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
108 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
109 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
110 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
111 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
112 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
113 int64 GetProofOfWorkReward(unsigned int nBits);
114 int64 GetProofOfStakeReward(int64 nCoinAge);
115 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
116 int GetNumBlocksOfPeers();
117 bool IsInitialBlockDownload();
118 std::string GetWarnings(std::string strFor);
119 uint256 WantedByOrphan(const CBlock* pblockOrphan);
120 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
121 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
133 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
135 /** Position on disk for a particular transaction. */
140 unsigned int nBlockPos;
148 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
151 nBlockPos = nBlockPosIn;
155 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
156 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
157 bool IsNull() const { return (nFile == -1); }
159 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
161 return (a.nFile == b.nFile &&
162 a.nBlockPos == b.nBlockPos &&
163 a.nTxPos == b.nTxPos);
166 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
171 std::string ToString() const
176 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
181 printf("%s", ToString().c_str());
187 /** An inpoint - a combination of a transaction and an index n into its vin */
194 CInPoint() { SetNull(); }
195 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
196 void SetNull() { ptx = NULL; n = -1; }
197 bool IsNull() const { return (ptx == NULL && n == -1); }
202 /** An outpoint - a combination of a transaction hash and an index n into its vout */
209 COutPoint() { SetNull(); }
210 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
211 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
212 void SetNull() { hash = 0; n = -1; }
213 bool IsNull() const { return (hash == 0 && n == -1); }
215 friend bool operator<(const COutPoint& a, const COutPoint& b)
217 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
220 friend bool operator==(const COutPoint& a, const COutPoint& b)
222 return (a.hash == b.hash && a.n == b.n);
225 friend bool operator!=(const COutPoint& a, const COutPoint& b)
230 std::string ToString() const
232 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
237 printf("%s\n", ToString().c_str());
244 /** An input of a transaction. It contains the location of the previous
245 * transaction's output that it claims and a signature that matches the
246 * output's public key.
253 unsigned int nSequence;
257 nSequence = std::numeric_limits<unsigned int>::max();
260 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
263 scriptSig = scriptSigIn;
264 nSequence = nSequenceIn;
267 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
269 prevout = COutPoint(hashPrevTx, nOut);
270 scriptSig = scriptSigIn;
271 nSequence = nSequenceIn;
277 READWRITE(scriptSig);
278 READWRITE(nSequence);
283 return (nSequence == std::numeric_limits<unsigned int>::max());
286 friend bool operator==(const CTxIn& a, const CTxIn& b)
288 return (a.prevout == b.prevout &&
289 a.scriptSig == b.scriptSig &&
290 a.nSequence == b.nSequence);
293 friend bool operator!=(const CTxIn& a, const CTxIn& b)
298 std::string ToStringShort() const
300 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
303 std::string ToString() const
307 str += prevout.ToString();
308 if (prevout.IsNull())
309 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
311 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
312 if (nSequence != std::numeric_limits<unsigned int>::max())
313 str += strprintf(", nSequence=%u", nSequence);
320 printf("%s\n", ToString().c_str());
327 /** An output of a transaction. It contains the public key that the next input
328 * must be able to sign with to claim it.
334 CScript scriptPubKey;
341 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
344 scriptPubKey = scriptPubKeyIn;
350 READWRITE(scriptPubKey);
356 scriptPubKey.clear();
361 return (nValue == -1);
367 scriptPubKey.clear();
372 return (nValue == 0 && scriptPubKey.empty());
375 uint256 GetHash() const
377 return SerializeHash(*this);
380 friend bool operator==(const CTxOut& a, const CTxOut& b)
382 return (a.nValue == b.nValue &&
383 a.scriptPubKey == b.scriptPubKey);
386 friend bool operator!=(const CTxOut& a, const CTxOut& b)
391 std::string ToStringShort() const
393 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
396 std::string ToString() const
398 if (IsEmpty()) return "CTxOut(empty)";
399 if (scriptPubKey.size() < 6)
400 return "CTxOut(error)";
401 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
406 printf("%s\n", ToString().c_str());
420 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
422 /** The basic transaction that is broadcasted on the network and contained in
423 * blocks. A transaction can contain multiple inputs and outputs.
430 std::vector<CTxIn> vin;
431 std::vector<CTxOut> vout;
432 unsigned int nLockTime;
434 // Denial-of-service detection:
436 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
445 READWRITE(this->nVersion);
446 nVersion = this->nVersion;
450 READWRITE(nLockTime);
456 nTime = GetAdjustedTime();
460 nDoS = 0; // Denial-of-service prevention
465 return (vin.empty() && vout.empty());
468 uint256 GetHash() const
470 return SerializeHash(*this);
473 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
475 // Time based nLockTime implemented in 0.1.6
478 if (nBlockHeight == 0)
479 nBlockHeight = nBestHeight;
481 nBlockTime = GetAdjustedTime();
482 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
484 BOOST_FOREACH(const CTxIn& txin, vin)
490 bool IsNewerThan(const CTransaction& old) const
492 if (vin.size() != old.vin.size())
494 for (unsigned int i = 0; i < vin.size(); i++)
495 if (vin[i].prevout != old.vin[i].prevout)
499 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
500 for (unsigned int i = 0; i < vin.size(); i++)
502 if (vin[i].nSequence != old.vin[i].nSequence)
504 if (vin[i].nSequence <= nLowest)
507 nLowest = vin[i].nSequence;
509 if (old.vin[i].nSequence < nLowest)
512 nLowest = old.vin[i].nSequence;
519 bool IsCoinBase() const
521 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
524 bool IsCoinStake() const
526 // ppcoin: the coin stake transaction is marked with the first output empty
527 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
530 /** Check for standard transaction types
531 @return True if all outputs (scriptPubKeys) use only standard transaction forms
533 bool IsStandard() const;
535 /** Check for standard transaction types
536 @param[in] mapInputs Map of previous transactions that have outputs we're spending
537 @return True if all inputs (scriptSigs) use only standard transaction forms
538 @see CTransaction::FetchInputs
540 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
542 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
543 @return number of sigops this transaction's outputs will produce when spent
544 @see CTransaction::FetchInputs
546 unsigned int GetLegacySigOpCount() const;
548 /** Count ECDSA signature operations in pay-to-script-hash inputs.
550 @param[in] mapInputs Map of previous transactions that have outputs we're spending
551 @return maximum number of sigops required to validate this transaction's inputs
552 @see CTransaction::FetchInputs
554 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
556 /** Amount of bitcoins spent by this transaction.
557 @return sum of all outputs (note: does not include fees)
559 int64 GetValueOut() const
562 BOOST_FOREACH(const CTxOut& txout, vout)
564 nValueOut += txout.nValue;
565 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
566 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
571 /** Amount of bitcoins coming in to this transaction
572 Note that lightweight clients may not know anything besides the hash of previous transactions,
573 so may not be able to calculate this.
575 @param[in] mapInputs Map of previous transactions that have outputs we're spending
576 @return Sum of value of all inputs (scriptSigs)
577 @see CTransaction::FetchInputs
579 int64 GetValueIn(const MapPrevTx& mapInputs) const;
581 static bool AllowFree(double dPriority)
583 // Large (in bytes) low-priority (new, small-coin) transactions
585 return dPriority > COIN * 144 / 250;
588 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
590 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
591 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
593 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
594 unsigned int nNewBlockSize = nBlockSize + nBytes;
595 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
601 // Transactions under 10K are free
602 // (about 4500bc if made of 50bc inputs)
608 // Free transaction area
609 if (nNewBlockSize < 27000)
614 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
615 if (nMinFee < nBaseFee)
617 BOOST_FOREACH(const CTxOut& txout, vout)
618 if (txout.nValue < CENT)
622 // Raise the price as the block approaches full
623 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
625 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
627 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
630 if (!MoneyRange(nMinFee))
636 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
638 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
640 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
643 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
644 return error("CTransaction::ReadFromDisk() : fseek failed");
649 catch (std::exception &e) {
650 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
653 // Return file pointer
656 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
657 return error("CTransaction::ReadFromDisk() : second fseek failed");
658 *pfileRet = filein.release();
663 friend bool operator==(const CTransaction& a, const CTransaction& b)
665 return (a.nVersion == b.nVersion &&
666 a.nTime == b.nTime &&
669 a.nLockTime == b.nLockTime);
672 friend bool operator!=(const CTransaction& a, const CTransaction& b)
678 std::string ToStringShort() const
681 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
685 std::string ToString() const
688 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
689 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
690 GetHash().ToString().substr(0,10).c_str(),
696 for (unsigned int i = 0; i < vin.size(); i++)
697 str += " " + vin[i].ToString() + "\n";
698 for (unsigned int i = 0; i < vout.size(); i++)
699 str += " " + vout[i].ToString() + "\n";
705 printf("%s", ToString().c_str());
709 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
710 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
711 bool ReadFromDisk(COutPoint prevout);
712 bool DisconnectInputs(CTxDB& txdb);
714 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
716 @param[in] txdb Transaction database
717 @param[in] mapTestPool List of pending changes to the transaction index database
718 @param[in] fBlock True if being called to add a new best-block to the chain
719 @param[in] fMiner True if being called by CreateNewBlock
720 @param[out] inputsRet Pointers to this transaction's inputs
721 @param[out] fInvalid returns true if transaction is invalid
722 @return Returns true if all inputs are in txdb or mapTestPool
724 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
725 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
727 /** Sanity check previous transactions, then, if all checks succeed,
728 mark them as spent by this transaction.
730 @param[in] inputs Previous transactions (from FetchInputs)
731 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
732 @param[in] posThisTx Position of this transaction on disk
733 @param[in] pindexBlock
734 @param[in] fBlock true if called from ConnectBlock
735 @param[in] fMiner true if called from CreateNewBlock
736 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
737 @return Returns true if all checks succeed
739 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
740 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
741 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
742 bool ClientConnectInputs();
743 bool CheckTransaction() const;
744 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
745 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
746 bool CheckProofOfStake(unsigned int nBits) const;
749 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
756 /** A transaction with a merkle branch linking it to the block chain. */
757 class CMerkleTx : public CTransaction
761 std::vector<uint256> vMerkleBranch;
765 mutable bool fMerkleVerified;
773 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
782 fMerkleVerified = false;
788 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
789 nVersion = this->nVersion;
790 READWRITE(hashBlock);
791 READWRITE(vMerkleBranch);
796 int SetMerkleBranch(const CBlock* pblock=NULL);
797 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
798 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
799 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
800 int GetBlocksToMaturity() const;
801 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
802 bool AcceptToMemoryPool();
808 /** A txdb record that contains the disk location of a transaction and the
809 * locations of transactions that spend its outputs. vSpent is really only
810 * used as a flag, but having the location is very helpful for debugging.
816 std::vector<CDiskTxPos> vSpent;
823 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
826 vSpent.resize(nOutputs);
831 if (!(nType & SER_GETHASH))
848 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
850 return (a.pos == b.pos &&
851 a.vSpent == b.vSpent);
854 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
858 int GetDepthInMainChain() const;
866 /** Nodes collect new transactions into a block, hash them into a hash tree,
867 * and scan through nonce values to make the block's hash satisfy proof-of-work
868 * requirements. When they solve the proof-of-work, they broadcast the block
869 * to everyone and the block is added to the block chain. The first transaction
870 * in the block is a special one that creates a new coin owned by the creator
873 * Blocks are appended to blk0001.dat files on disk. Their location on disk
874 * is indexed by CBlockIndex objects in memory.
881 uint256 hashPrevBlock;
882 uint256 hashMerkleRoot;
888 std::vector<CTransaction> vtx;
890 // ppcoin: block signature - signed by coin base txout[0]'s owner
891 std::vector<unsigned char> vchBlockSig;
894 mutable std::vector<uint256> vMerkleTree;
896 // Denial-of-service detection:
898 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
907 READWRITE(this->nVersion);
908 nVersion = this->nVersion;
909 READWRITE(hashPrevBlock);
910 READWRITE(hashMerkleRoot);
915 // ConnectBlock depends on vtx following header to generate CDiskTxPos
916 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
919 READWRITE(vchBlockSig);
923 const_cast<CBlock*>(this)->vtx.clear();
924 const_cast<CBlock*>(this)->vchBlockSig.clear();
947 uint256 GetHash() const
949 return Hash(BEGIN(nVersion), END(nNonce));
952 int64 GetBlockTime() const
957 void UpdateTime(const CBlockIndex* pindexPrev);
959 // ppcoin: two types of block: proof-of-work or proof-of-stake
960 bool IsProofOfStake() const
962 return (vtx.size() > 1 && vtx[1].IsCoinStake());
965 bool IsProofOfWork() const
967 return !IsProofOfStake();
970 std::pair<COutPoint, unsigned int> GetProofOfStake() const
972 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
975 // ppcoin: get max transaction timestamp
976 int64 GetMaxTransactionTime() const
978 int64 maxTransactionTime = 0;
979 BOOST_FOREACH(const CTransaction& tx, vtx)
980 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
981 return maxTransactionTime;
984 uint256 BuildMerkleTree() const
987 BOOST_FOREACH(const CTransaction& tx, vtx)
988 vMerkleTree.push_back(tx.GetHash());
990 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
992 for (int i = 0; i < nSize; i += 2)
994 int i2 = std::min(i+1, nSize-1);
995 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
996 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1000 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1003 std::vector<uint256> GetMerkleBranch(int nIndex) const
1005 if (vMerkleTree.empty())
1007 std::vector<uint256> vMerkleBranch;
1009 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1011 int i = std::min(nIndex^1, nSize-1);
1012 vMerkleBranch.push_back(vMerkleTree[j+i]);
1016 return vMerkleBranch;
1019 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1023 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1026 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1028 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1035 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1037 // Open history file to append
1038 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1040 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1042 // Write index header
1043 unsigned char pchMessageStart[4];
1044 GetMessageStart(pchMessageStart, true);
1045 unsigned int nSize = fileout.GetSerializeSize(*this);
1046 fileout << FLATDATA(pchMessageStart) << nSize;
1049 long fileOutPos = ftell(fileout);
1051 return error("CBlock::WriteToDisk() : ftell failed");
1052 nBlockPosRet = fileOutPos;
1055 // Flush stdio buffers and commit to disk before returning
1057 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1060 _commit(_fileno(fileout));
1062 fsync(fileno(fileout));
1069 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1073 // Open history file to read
1074 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1076 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1077 if (!fReadTransactions)
1078 filein.nType |= SER_BLOCKHEADERONLY;
1084 catch (std::exception &e) {
1085 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1089 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1090 return error("CBlock::ReadFromDisk() : errors in block header");
1099 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1100 GetHash().ToString().substr(0,20).c_str(),
1102 hashPrevBlock.ToString().substr(0,20).c_str(),
1103 hashMerkleRoot.ToString().substr(0,10).c_str(),
1104 nTime, nBits, nNonce,
1106 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1107 for (unsigned int i = 0; i < vtx.size(); i++)
1112 printf(" vMerkleTree: ");
1113 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1114 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1119 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1120 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1121 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1122 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1123 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1124 bool CheckBlock() const;
1126 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1127 bool SignBlock(const CKeyStore& keystore);
1128 bool CheckBlockSignature() const;
1131 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1139 /** The block chain is a tree shaped structure starting with the
1140 * genesis block at the root, with each block potentially having multiple
1141 * candidates to be the next block. pprev and pnext link a path through the
1142 * main/longest chain. A blockindex may have multiple pprev pointing back
1143 * to it, but pnext will only point forward to the longest branch, or will
1144 * be null if the block is not part of the longest chain.
1149 const uint256* phashBlock;
1153 unsigned int nBlockPos;
1154 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1158 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1159 COutPoint prevoutStake;
1160 unsigned int nStakeTime;
1164 uint256 hashMerkleRoot;
1167 unsigned int nNonce;
1181 fProofOfStake = true;
1182 prevoutStake.SetNull();
1192 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1198 nBlockPos = nBlockPosIn;
1203 fProofOfStake = block.IsProofOfStake();
1206 prevoutStake = block.vtx[1].vin[0].prevout;
1207 nStakeTime = block.vtx[1].nTime;
1211 prevoutStake.SetNull();
1215 nVersion = block.nVersion;
1216 hashMerkleRoot = block.hashMerkleRoot;
1217 nTime = block.nTime;
1218 nBits = block.nBits;
1219 nNonce = block.nNonce;
1222 CBlock GetBlockHeader() const
1225 block.nVersion = nVersion;
1227 block.hashPrevBlock = pprev->GetBlockHash();
1228 block.hashMerkleRoot = hashMerkleRoot;
1229 block.nTime = nTime;
1230 block.nBits = nBits;
1231 block.nNonce = nNonce;
1235 uint256 GetBlockHash() const
1240 int64 GetBlockTime() const
1242 return (int64)nTime;
1245 CBigNum GetBlockTrust() const
1248 bnTarget.SetCompact(nBits);
1251 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1254 bool IsInMainChain() const
1256 return (pnext || this == pindexBest);
1259 bool CheckIndex() const
1261 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1264 bool EraseBlockFromDisk()
1266 // Open history file
1267 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1271 // Overwrite with empty null block
1279 enum { nMedianTimeSpan=11 };
1281 int64 GetMedianTimePast() const
1283 int64 pmedian[nMedianTimeSpan];
1284 int64* pbegin = &pmedian[nMedianTimeSpan];
1285 int64* pend = &pmedian[nMedianTimeSpan];
1287 const CBlockIndex* pindex = this;
1288 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1289 *(--pbegin) = pindex->GetBlockTime();
1291 std::sort(pbegin, pend);
1292 return pbegin[(pend - pbegin)/2];
1295 int64 GetMedianTime() const
1297 const CBlockIndex* pindex = this;
1298 for (int i = 0; i < nMedianTimeSpan/2; i++)
1301 return GetBlockTime();
1302 pindex = pindex->pnext;
1304 return pindex->GetMedianTimePast();
1307 bool IsProofOfWork() const
1309 return !fProofOfStake;
1312 bool IsProofOfStake() const
1314 return fProofOfStake;
1317 std::string ToString() const
1319 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)",
1320 pprev, pnext, nFile, nBlockPos, nHeight,
1321 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1322 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1323 hashMerkleRoot.ToString().substr(0,10).c_str(),
1324 GetBlockHash().ToString().substr(0,20).c_str());
1329 printf("%s\n", ToString().c_str());
1335 /** Used to marshal pointers into hashes for db storage. */
1336 class CDiskBlockIndex : public CBlockIndex
1348 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1350 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1351 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1356 if (!(nType & SER_GETHASH))
1357 READWRITE(nVersion);
1359 READWRITE(hashNext);
1361 READWRITE(nBlockPos);
1364 READWRITE(nMoneySupply);
1365 READWRITE(fProofOfStake);
1368 READWRITE(prevoutStake);
1369 READWRITE(nStakeTime);
1373 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1374 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1378 READWRITE(this->nVersion);
1379 READWRITE(hashPrev);
1380 READWRITE(hashMerkleRoot);
1386 uint256 GetBlockHash() const
1389 block.nVersion = nVersion;
1390 block.hashPrevBlock = hashPrev;
1391 block.hashMerkleRoot = hashMerkleRoot;
1392 block.nTime = nTime;
1393 block.nBits = nBits;
1394 block.nNonce = nNonce;
1395 return block.GetHash();
1399 std::string ToString() const
1401 std::string str = "CDiskBlockIndex(";
1402 str += CBlockIndex::ToString();
1403 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1404 GetBlockHash().ToString().c_str(),
1405 hashPrev.ToString().substr(0,20).c_str(),
1406 hashNext.ToString().substr(0,20).c_str());
1412 printf("%s\n", ToString().c_str());
1423 /** Describes a place in the block chain to another node such that if the
1424 * other node doesn't have the same branch, it can find a recent common trunk.
1425 * The further back it is, the further before the fork it may be.
1430 std::vector<uint256> vHave;
1437 explicit CBlockLocator(const CBlockIndex* pindex)
1442 explicit CBlockLocator(uint256 hashBlock)
1444 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1445 if (mi != mapBlockIndex.end())
1449 CBlockLocator(const std::vector<uint256>& vHaveIn)
1456 if (!(nType & SER_GETHASH))
1457 READWRITE(nVersion);
1468 return vHave.empty();
1471 void Set(const CBlockIndex* pindex)
1477 vHave.push_back(pindex->GetBlockHash());
1479 // Exponentially larger steps back
1480 for (int i = 0; pindex && i < nStep; i++)
1481 pindex = pindex->pprev;
1482 if (vHave.size() > 10)
1485 vHave.push_back(hashGenesisBlock);
1488 int GetDistanceBack()
1490 // Retrace how far back it was in the sender's branch
1493 BOOST_FOREACH(const uint256& hash, vHave)
1495 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1496 if (mi != mapBlockIndex.end())
1498 CBlockIndex* pindex = (*mi).second;
1499 if (pindex->IsInMainChain())
1509 CBlockIndex* GetBlockIndex()
1511 // Find the first block the caller has in the main chain
1512 BOOST_FOREACH(const uint256& hash, vHave)
1514 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1515 if (mi != mapBlockIndex.end())
1517 CBlockIndex* pindex = (*mi).second;
1518 if (pindex->IsInMainChain())
1522 return pindexGenesisBlock;
1525 uint256 GetBlockHash()
1527 // Find the first block the caller has in the main chain
1528 BOOST_FOREACH(const uint256& hash, vHave)
1530 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1531 if (mi != mapBlockIndex.end())
1533 CBlockIndex* pindex = (*mi).second;
1534 if (pindex->IsInMainChain())
1538 return hashGenesisBlock;
1543 CBlockIndex* pindex = GetBlockIndex();
1546 return pindex->nHeight;
1558 /** Alerts are for notifying old versions if they become too obsolete and
1559 * need to upgrade. The message is displayed in the status bar.
1560 * Alert messages are broadcast as a vector of signed data. Unserializing may
1561 * not read the entire buffer if the alert is for a newer version, but older
1562 * versions can still relay the original data.
1564 class CUnsignedAlert
1568 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1572 std::set<int> setCancel;
1573 int nMinVer; // lowest version inclusive
1574 int nMaxVer; // highest version inclusive
1575 std::set<std::string> setSubVer; // empty matches all
1579 std::string strComment;
1580 std::string strStatusBar;
1581 std::string strReserved;
1585 READWRITE(this->nVersion);
1586 nVersion = this->nVersion;
1587 READWRITE(nRelayUntil);
1588 READWRITE(nExpiration);
1591 READWRITE(setCancel);
1594 READWRITE(setSubVer);
1595 READWRITE(nPriority);
1597 READWRITE(strComment);
1598 READWRITE(strStatusBar);
1599 READWRITE(strReserved);
1616 strStatusBar.clear();
1617 strReserved.clear();
1620 std::string ToString() const
1622 std::string strSetCancel;
1623 BOOST_FOREACH(int n, setCancel)
1624 strSetCancel += strprintf("%d ", n);
1625 std::string strSetSubVer;
1626 BOOST_FOREACH(std::string str, setSubVer)
1627 strSetSubVer += "\"" + str + "\" ";
1631 " nRelayUntil = %"PRI64d"\n"
1632 " nExpiration = %"PRI64d"\n"
1640 " strComment = \"%s\"\n"
1641 " strStatusBar = \"%s\"\n"
1648 strSetCancel.c_str(),
1651 strSetSubVer.c_str(),
1654 strStatusBar.c_str());
1659 printf("%s", ToString().c_str());
1663 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1664 class CAlert : public CUnsignedAlert
1667 std::vector<unsigned char> vchMsg;
1668 std::vector<unsigned char> vchSig;
1683 CUnsignedAlert::SetNull();
1690 return (nExpiration == 0);
1693 uint256 GetHash() const
1695 return SerializeHash(*this);
1698 bool IsInEffect() const
1700 return (GetAdjustedTime() < nExpiration);
1703 bool Cancels(const CAlert& alert) const
1706 return false; // this was a no-op before 31403
1707 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1710 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1712 // TODO: rework for client-version-embedded-in-strSubVer ?
1713 return (IsInEffect() &&
1714 nMinVer <= nVersion && nVersion <= nMaxVer &&
1715 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1718 bool AppliesToMe() const
1720 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1723 bool RelayTo(CNode* pnode) const
1727 // returns true if wasn't already contained in the set
1728 if (pnode->setKnown.insert(GetHash()).second)
1730 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1732 GetAdjustedTime() < nRelayUntil)
1734 pnode->PushMessage("alert", *this);
1741 bool CheckSignature()
1744 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1745 return error("CAlert::CheckSignature() : SetPubKey failed");
1746 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1747 return error("CAlert::CheckSignature() : verify signature failed");
1749 // Now unserialize the data
1750 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1751 sMsg >> *(CUnsignedAlert*)this;
1755 bool ProcessAlert();
1761 mutable CCriticalSection cs;
1762 std::map<uint256, CTransaction> mapTx;
1763 std::map<COutPoint, CInPoint> mapNextTx;
1765 bool accept(CTxDB& txdb, CTransaction &tx,
1766 bool fCheckInputs, bool* pfMissingInputs);
1767 bool addUnchecked(CTransaction &tx);
1768 bool remove(CTransaction &tx);
1770 unsigned long size()
1773 return mapTx.size();
1776 bool exists(uint256 hash)
1778 return (mapTx.count(hash) != 0);
1781 CTransaction& lookup(uint256 hash)
1787 extern CTxMemPool mempool;